blob: 13354c8839bf3aa29dd012bc8e8b330a59145df5 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossumff7e83d1999-08-27 20:39:37 +00006#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00007#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00008#endif /* DONT_HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +00009
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000010#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000011#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000012/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000013#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000014#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000015#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000016#endif
17
Mark Hammondc2e85bd2002-10-03 05:10:39 +000018#ifdef _MSC_VER
19/* Need GetVersion to see if on NT so safe to use _wfopen */
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22#endif /* _MSC_VER */
23
Guido van Rossumf2044e11998-04-28 16:05:59 +000024#ifdef macintosh
25#ifdef USE_GUSI
26#define HAVE_FTRUNCATE
27#endif
28#endif
29
Jack Jansene08dea191995-04-23 22:12:47 +000030#ifdef __MWERKS__
31/* Mwerks fopen() doesn't always set errno */
32#define NO_FOPEN_ERRNO
33#endif
Guido van Rossum295d1711995-02-19 15:55:19 +000034
Andrew MacIntyrec4874392002-02-26 11:36:35 +000035#if defined(PYOS_OS2) && defined(PYCC_GCC)
36#include <io.h>
37#endif
38
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000040
Guido van Rossumff7e83d1999-08-27 20:39:37 +000041#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000042#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000043#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
Jack Jansen7b8c7542002-04-14 20:12:41 +000045#ifdef HAVE_GETC_UNLOCKED
46#define GETC(f) getc_unlocked(f)
47#define FLOCKFILE(f) flockfile(f)
48#define FUNLOCKFILE(f) funlockfile(f)
49#else
50#define GETC(f) getc(f)
51#define FLOCKFILE(f)
52#define FUNLOCKFILE(f)
53#endif
54
55#ifdef WITH_UNIVERSAL_NEWLINES
56/* Bits in f_newlinetypes */
57#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
58#define NEWLINE_CR 1 /* \r newline seen */
59#define NEWLINE_LF 2 /* \n newline seen */
60#define NEWLINE_CRLF 4 /* \r\n newline seen */
61#endif
Trent Mickf29f47b2000-08-11 19:02:59 +000062
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000064PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000068 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000069 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070}
71
Guido van Rossumc0b618a1997-05-02 03:12:38 +000072PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000073PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000074{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000076 return NULL;
77 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000078 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000079}
80
Neil Schemenauered19b882002-03-23 02:06:50 +000081/* On Unix, fopen will succeed for directories.
82 In Python, there should be no file objects referring to
83 directories, so we need a check. */
84
85static PyFileObject*
86dircheck(PyFileObject* f)
87{
88#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
89 struct stat buf;
90 if (f->f_fp == NULL)
91 return f;
92 if (fstat(fileno(f->f_fp), &buf) == 0 &&
93 S_ISDIR(buf.st_mode)) {
94#ifdef HAVE_STRERROR
95 char *msg = strerror(EISDIR);
96#else
97 char *msg = "Is a directory";
98#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +000099 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
100 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +0000101 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000102 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000103 return NULL;
104 }
105#endif
106 return f;
107}
108
Tim Peters59c9a642001-09-13 05:38:56 +0000109
110static PyObject *
111fill_file_fields(PyFileObject *f, FILE *fp, char *name, char *mode,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000112 int (*close)(FILE *), PyObject *wname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000113{
Tim Peters59c9a642001-09-13 05:38:56 +0000114 assert(f != NULL);
115 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000116 assert(f->f_fp == NULL);
117
118 Py_DECREF(f->f_name);
119 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000120 Py_DECREF(f->f_encoding);
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000121#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000122 if (wname)
123 f->f_name = PyUnicode_FromObject(wname);
124 else
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000125#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000126 f->f_name = PyString_FromString(name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000128
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000129 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000130 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000131 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000132 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000133#ifdef WITH_UNIVERSAL_NEWLINES
134 f->f_univ_newline = (strchr(mode, 'U') != NULL);
135 f->f_newlinetypes = NEWLINE_UNKNOWN;
136 f->f_skipnextlf = 0;
137#endif
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000138 Py_INCREF(Py_None);
139 f->f_encoding = Py_None;
140
Tim Peters59c9a642001-09-13 05:38:56 +0000141 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000144 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146}
147
Tim Peters59c9a642001-09-13 05:38:56 +0000148static PyObject *
149open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150{
Tim Peters59c9a642001-09-13 05:38:56 +0000151 assert(f != NULL);
152 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000153#ifdef MS_WINDOWS
154 /* windows ignores the passed name in order to support Unicode */
155 assert(f->f_name != NULL);
156#else
Tim Peters59c9a642001-09-13 05:38:56 +0000157 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000158#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000159 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000160 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000161
Tim Peters8fa45672001-09-13 21:01:29 +0000162 /* rexec.py can't stop a user from getting the file() constructor --
163 all they have to do is get *any* file object f, and then do
164 type(f). Here we prevent them from doing damage with it. */
165 if (PyEval_GetRestricted()) {
166 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000167 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000168 return NULL;
169 }
Tim Petersa27a1502001-11-09 20:59:14 +0000170 errno = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000171#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000172 if (*mode == '*') {
173 FILE *fopenRF();
174 f->f_fp = fopenRF(name, mode+1);
175 }
176 else
177#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000178 {
Jack Jansen7b8c7542002-04-14 20:12:41 +0000179#ifdef WITH_UNIVERSAL_NEWLINES
180 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
181 mode = "rb";
182#else
183 /* Compatibility: specifying U in a Python without universal
184 ** newlines is allowed, and the file is opened as a normal text
185 ** file.
186 */
187 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
188 mode = "r";
189#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000190#ifdef MS_WINDOWS
191 if (PyUnicode_Check(f->f_name)) {
192 PyObject *wmode;
193 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
194 if (f->f_name && wmode) {
195 Py_BEGIN_ALLOW_THREADS
196 /* PyUnicode_AS_UNICODE OK without thread
197 lock as it is a simple dereference. */
198 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
199 PyUnicode_AS_UNICODE(wmode));
200 Py_END_ALLOW_THREADS
201 }
202 Py_XDECREF(wmode);
203 }
204#endif
205 if (NULL == f->f_fp && NULL != name) {
206 Py_BEGIN_ALLOW_THREADS
207 f->f_fp = fopen(name, mode);
208 Py_END_ALLOW_THREADS
209 }
Guido van Rossumff4949e1992-08-05 19:58:53 +0000210 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000211 if (f->f_fp == NULL) {
Jack Jansene08dea191995-04-23 22:12:47 +0000212#ifdef NO_FOPEN_ERRNO
Jack Jansenb3be2162001-11-30 14:16:36 +0000213 /* Metroworks only, wich does not always sets errno */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000214 if (errno == 0) {
Jack Jansenb3be2162001-11-30 14:16:36 +0000215 PyObject *v;
216 v = Py_BuildValue("(is)", 0, "Cannot open file");
217 if (v != NULL) {
218 PyErr_SetObject(PyExc_IOError, v);
219 Py_DECREF(v);
220 }
Jack Jansene08dea191995-04-23 22:12:47 +0000221 return NULL;
222 }
223#endif
Tim Peters2ea91112002-04-08 04:13:12 +0000224#ifdef _MSC_VER
225 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
226 * across all Windows flavors. When it sets EINVAL varies
227 * across Windows flavors, the exact conditions aren't
228 * documented, and the answer lies in the OS's implementation
229 * of Win32's CreateFile function (whose source is secret).
230 * Seems the best we can do is map EINVAL to ENOENT.
231 */
232 if (errno == 0) /* bad mode string */
233 errno = EINVAL;
234 else if (errno == EINVAL) /* unknown, but not a mode string */
235 errno = ENOENT;
236#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000237 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000238 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000239 mode);
240 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000241#ifdef MS_WINDOWS
242 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
243#else
Jeremy Hylton41c83212001-11-09 16:17:24 +0000244 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000245#endif /* MS_WINDOWS */
Tim Peters59c9a642001-09-13 05:38:56 +0000246 f = NULL;
247 }
Tim Peters2ea91112002-04-08 04:13:12 +0000248 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000249 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000250 return (PyObject *)f;
251}
252
253PyObject *
254PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
255{
Tim Peters44410012001-09-14 03:26:08 +0000256 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
257 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000258 if (f != NULL) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000259 if (fill_file_fields(f, fp, name, mode, close, NULL) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000260 Py_DECREF(f);
261 f = NULL;
262 }
263 }
264 return (PyObject *) f;
265}
266
267PyObject *
268PyFile_FromString(char *name, char *mode)
269{
270 extern int fclose(FILE *);
271 PyFileObject *f;
272
273 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
274 if (f != NULL) {
275 if (open_the_file(f, name, mode) == NULL) {
276 Py_DECREF(f);
277 f = NULL;
278 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000280 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281}
282
Guido van Rossumb6775db1994-08-01 11:34:53 +0000283void
Fred Drakefd99de62000-07-09 05:02:18 +0000284PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000285{
286 if (bufsize >= 0) {
287#ifdef HAVE_SETVBUF
288 int type;
289 switch (bufsize) {
290 case 0:
291 type = _IONBF;
292 break;
293 case 1:
294 type = _IOLBF;
295 bufsize = BUFSIZ;
296 break;
297 default:
298 type = _IOFBF;
299 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300 setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
301 type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000302#else /* !HAVE_SETVBUF */
303 if (bufsize <= 1)
304 setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
305#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000306 }
307}
308
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000309/* Set the encoding used to output Unicode strings.
310 Returh 1 on success, 0 on failure. */
311
312int
313PyFile_SetEncoding(PyObject *f, const char *enc)
314{
315 PyFileObject *file = (PyFileObject*)f;
316 PyObject *str = PyString_FromString(enc);
317 if (!str)
318 return 0;
319 Py_DECREF(file->f_encoding);
320 file->f_encoding = str;
321 return 1;
322}
323
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000325err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000326{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000328 return NULL;
329}
330
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000331static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000332
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333/* Methods */
334
335static void
Fred Drakefd99de62000-07-09 05:02:18 +0000336file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000338 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000340 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000342 }
Tim Peters44410012001-09-14 03:26:08 +0000343 Py_XDECREF(f->f_name);
344 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000345 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000346 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000347 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348}
349
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000351file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000353 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000354#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000355 PyObject *ret = NULL;
356 PyObject *name;
357 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
358 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
359 f->f_fp == NULL ? "closed" : "open",
360 PyString_AsString(name),
361 PyString_AsString(f->f_mode),
362 f);
363 Py_XDECREF(name);
364 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000365#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000366 } else {
367 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000368 f->f_fp == NULL ? "closed" : "open",
369 PyString_AsString(f->f_name),
370 PyString_AsString(f->f_mode),
371 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000372 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373}
374
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000376file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000378 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000380 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000381 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000382 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000383 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000384 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000385 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000386 f->f_fp = NULL;
387 }
Guido van Rossumfebd5511992-03-04 16:39:24 +0000388 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000389 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000390 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000391 return PyInt_FromLong((long)sts);
392 Py_INCREF(Py_None);
393 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394}
395
Trent Mickf29f47b2000-08-11 19:02:59 +0000396
Guido van Rossumb8552162001-09-05 14:58:11 +0000397/* Our very own off_t-like type, 64-bit if possible */
398#if !defined(HAVE_LARGEFILE_SUPPORT)
399typedef off_t Py_off_t;
400#elif SIZEOF_OFF_T >= 8
401typedef off_t Py_off_t;
402#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000403typedef fpos_t Py_off_t;
404#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000405#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000406#endif
407
408
Trent Mickf29f47b2000-08-11 19:02:59 +0000409/* a portable fseek() function
410 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000411static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000412_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000413{
Guido van Rossumb8552162001-09-05 14:58:11 +0000414#if !defined(HAVE_LARGEFILE_SUPPORT)
415 return fseek(fp, offset, whence);
416#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000417 return fseeko(fp, offset, whence);
418#elif defined(HAVE_FSEEK64)
419 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000420#elif defined(__BEOS__)
421 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000422#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000423 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
424 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000425 fpos_t pos;
426 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000427 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000428#ifdef MS_WINDOWS
429 fflush(fp);
430 if (_lseeki64(fileno(fp), 0, 2) == -1)
431 return -1;
432#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000433 if (fseek(fp, 0, SEEK_END) != 0)
434 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000435#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000436 /* fall through */
437 case SEEK_CUR:
438 if (fgetpos(fp, &pos) != 0)
439 return -1;
440 offset += pos;
441 break;
442 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000443 }
444 return fsetpos(fp, &offset);
445#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000446#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000447#endif
448}
449
450
451/* a portable ftell() function
452 Return -1 on failure with errno set appropriately, current file
453 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000454static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000455_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000456{
Guido van Rossumb8552162001-09-05 14:58:11 +0000457#if !defined(HAVE_LARGEFILE_SUPPORT)
458 return ftell(fp);
459#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
460 return ftello(fp);
461#elif defined(HAVE_FTELL64)
462 return ftell64(fp);
463#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000464 fpos_t pos;
465 if (fgetpos(fp, &pos) != 0)
466 return -1;
467 return pos;
468#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000469#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000470#endif
471}
472
473
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000475file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000477 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000478 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000479 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000480 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000481
Guido van Rossumd7297e61992-07-06 14:19:26 +0000482 if (f->f_fp == NULL)
483 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000484 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000485 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000486 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000487 return NULL;
488#if !defined(HAVE_LARGEFILE_SUPPORT)
489 offset = PyInt_AsLong(offobj);
490#else
491 offset = PyLong_Check(offobj) ?
492 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
493#endif
494 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000495 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000496
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000497 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000498 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000499 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000501
Guido van Rossumff4949e1992-08-05 19:58:53 +0000502 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000503 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000504 clearerr(f->f_fp);
505 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000506 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000507#ifdef WITH_UNIVERSAL_NEWLINES
508 f->f_skipnextlf = 0;
509#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510 Py_INCREF(Py_None);
511 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000512}
513
Trent Mickf29f47b2000-08-11 19:02:59 +0000514
Guido van Rossumd7047b31995-01-02 19:07:15 +0000515#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000517file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000518{
Guido van Rossumd7047b31995-01-02 19:07:15 +0000519 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000520 Py_off_t newsize;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000521 PyObject *newsizeobj;
Tim Peters86821b22001-01-07 21:19:34 +0000522
Guido van Rossumd7047b31995-01-02 19:07:15 +0000523 if (f->f_fp == NULL)
524 return err_closed();
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000525 newsizeobj = NULL;
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000526 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000527 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000528
529 /* Set newsize to current postion if newsizeobj NULL, else to the
530 specified value. */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000531 if (newsizeobj != NULL) {
532#if !defined(HAVE_LARGEFILE_SUPPORT)
533 newsize = PyInt_AsLong(newsizeobj);
534#else
535 newsize = PyLong_Check(newsizeobj) ?
536 PyLong_AsLongLong(newsizeobj) :
537 PyInt_AsLong(newsizeobj);
538#endif
539 if (PyErr_Occurred())
540 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000541 }
542 else {
543 /* Default to current position. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000545 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000546 newsize = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000548 if (newsize == -1)
549 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000550 }
Tim Petersfb05db22002-03-11 00:24:00 +0000551
552 /* Flush the file. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000554 errno = 0;
555 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000556 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000557 if (ret != 0)
558 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000559
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000560#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000561 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000562 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000563 {
Tim Peters8f01b682002-03-12 03:04:44 +0000564 Py_off_t current; /* current file position */
Tim Petersfb05db22002-03-11 00:24:00 +0000565 HANDLE hFile;
566 int error;
567
Tim Peters8f01b682002-03-12 03:04:44 +0000568 /* current <- current file postion. */
569 if (newsizeobj == NULL)
570 current = newsize;
571 else {
Tim Petersfb05db22002-03-11 00:24:00 +0000572 Py_BEGIN_ALLOW_THREADS
573 errno = 0;
Tim Peters8f01b682002-03-12 03:04:44 +0000574 current = _portable_ftell(f->f_fp);
575 Py_END_ALLOW_THREADS
576 if (current == -1)
577 goto onioerror;
578 }
579
580 /* Move to newsize. */
581 if (current != newsize) {
582 Py_BEGIN_ALLOW_THREADS
583 errno = 0;
584 error = _portable_fseek(f->f_fp, newsize, SEEK_SET)
585 != 0;
Tim Petersfb05db22002-03-11 00:24:00 +0000586 Py_END_ALLOW_THREADS
587 if (error)
588 goto onioerror;
589 }
590
Tim Peters8f01b682002-03-12 03:04:44 +0000591 /* Truncate. Note that this may grow the file! */
592 Py_BEGIN_ALLOW_THREADS
593 errno = 0;
594 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
595 error = hFile == (HANDLE)-1;
596 if (!error) {
597 error = SetEndOfFile(hFile) == 0;
598 if (error)
599 errno = EACCES;
600 }
601 Py_END_ALLOW_THREADS
602 if (error)
603 goto onioerror;
604
605 /* Restore original file position. */
606 if (current != newsize) {
607 Py_BEGIN_ALLOW_THREADS
608 errno = 0;
609 error = _portable_fseek(f->f_fp, current, SEEK_SET)
610 != 0;
611 Py_END_ALLOW_THREADS
612 if (error)
613 goto onioerror;
614 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000615 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000616#else
617 Py_BEGIN_ALLOW_THREADS
618 errno = 0;
619 ret = ftruncate(fileno(f->f_fp), newsize);
620 Py_END_ALLOW_THREADS
621 if (ret != 0) goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000622#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000623
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624 Py_INCREF(Py_None);
625 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000626
627onioerror:
628 PyErr_SetFromErrno(PyExc_IOError);
629 clearerr(f->f_fp);
630 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000631}
632#endif /* HAVE_FTRUNCATE */
633
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000635file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000636{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000637 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000638
Guido van Rossumd7297e61992-07-06 14:19:26 +0000639 if (f->f_fp == NULL)
640 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000641 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000642 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000643 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000645 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000646 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000647 clearerr(f->f_fp);
648 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000649 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000650#ifdef WITH_UNIVERSAL_NEWLINES
651 if (f->f_skipnextlf) {
652 int c;
653 c = GETC(f->f_fp);
654 if (c == '\n') {
655 pos++;
656 f->f_skipnextlf = 0;
657 } else if (c != EOF) ungetc(c, f->f_fp);
658 }
659#endif
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000660#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000661 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000662#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000663 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000664#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000665}
666
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000668file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000669{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000670 if (f->f_fp == NULL)
671 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000672 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000673}
674
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000676file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000677{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000678 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000679
Guido van Rossumd7297e61992-07-06 14:19:26 +0000680 if (f->f_fp == NULL)
681 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000683 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000684 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000686 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000688 clearerr(f->f_fp);
689 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000690 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691 Py_INCREF(Py_None);
692 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000693}
694
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000695static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000696file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000697{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000698 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000699 if (f->f_fp == NULL)
700 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000701 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000702 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000703 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000704 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000705}
706
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000707
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000708#if BUFSIZ < 8192
709#define SMALLCHUNK 8192
710#else
711#define SMALLCHUNK BUFSIZ
712#endif
713
Guido van Rossum3c259041999-01-14 19:00:14 +0000714#if SIZEOF_INT < 4
715#define BIGCHUNK (512 * 32)
716#else
717#define BIGCHUNK (512 * 1024)
718#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000719
720static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000721new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000722{
723#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000724 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000725 struct stat st;
726 if (fstat(fileno(f->f_fp), &st) == 0) {
727 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000728 /* The following is not a bug: we really need to call lseek()
729 *and* ftell(). The reason is that some stdio libraries
730 mistakenly flush their buffer when ftell() is called and
731 the lseek() call it makes fails, thereby throwing away
732 data that cannot be recovered in any way. To avoid this,
733 we first test lseek(), and only call ftell() if lseek()
734 works. We can't use the lseek() value either, because we
735 need to take the amount of buffered data into account.
736 (Yet another reason why stdio stinks. :-) */
Jack Jansen2771b5b2001-10-10 22:03:27 +0000737#ifdef USE_GUSI2
738 pos = lseek(fileno(f->f_fp), 1L, SEEK_CUR);
739 pos = lseek(fileno(f->f_fp), -1L, SEEK_CUR);
740#else
Guido van Rossum91aaa921998-05-05 22:21:35 +0000741 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000742#endif
743 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000744 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000745 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000746 if (pos < 0)
747 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000748 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000749 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000750 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000751 }
752#endif
753 if (currentsize > SMALLCHUNK) {
754 /* Keep doubling until we reach BIGCHUNK;
755 then keep adding BIGCHUNK. */
756 if (currentsize <= BIGCHUNK)
757 return currentsize + currentsize;
758 else
759 return currentsize + BIGCHUNK;
760 }
761 return currentsize + SMALLCHUNK;
762}
763
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000764#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
765#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
766#else
767#ifdef EWOULDBLOCK
768#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
769#else
770#ifdef EAGAIN
771#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
772#else
773#define BLOCKED_ERRNO(x) 0
774#endif
775#endif
776#endif
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000779file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000780{
Guido van Rossum789a1611997-05-10 22:33:55 +0000781 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000782 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000784
Guido van Rossumd7297e61992-07-06 14:19:26 +0000785 if (f->f_fp == NULL)
786 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000787 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000788 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000789 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000790 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000791 else
792 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000793 if (buffersize > INT_MAX) {
794 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000795 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000796 return NULL;
797 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000798 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000799 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000801 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000802 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000803 Py_BEGIN_ALLOW_THREADS
804 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000805 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000806 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000807 Py_END_ALLOW_THREADS
808 if (chunksize == 0) {
809 if (!ferror(f->f_fp))
810 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000811 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000812 /* When in non-blocking mode, data shouldn't
813 * be discarded if a blocking signal was
814 * received. That will also happen if
815 * chunksize != 0, but bytesread < buffersize. */
816 if (bytesread > 0 && BLOCKED_ERRNO(errno))
817 break;
818 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000819 Py_DECREF(v);
820 return NULL;
821 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000822 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000823 if (bytesread < buffersize) {
824 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000825 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000826 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000827 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000828 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000829 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000830 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000831 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000832 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000833 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000834 }
835 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000836 if (bytesread != buffersize)
837 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000838 return v;
839}
840
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000841static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000842file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000843{
844 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000845 int ntodo;
846 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000847
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000848 if (f->f_fp == NULL)
849 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000850 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000851 return NULL;
852 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000853 while (ntodo > 0) {
854 Py_BEGIN_ALLOW_THREADS
855 errno = 0;
Jeremy Hylton8b735422002-08-14 21:01:41 +0000856 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
857 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000858 Py_END_ALLOW_THREADS
859 if (nnow == 0) {
860 if (!ferror(f->f_fp))
861 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000862 PyErr_SetFromErrno(PyExc_IOError);
863 clearerr(f->f_fp);
864 return NULL;
865 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000866 ndone += nnow;
867 ntodo -= nnow;
868 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000869 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000870}
871
Tim Peters86821b22001-01-07 21:19:34 +0000872/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000873Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000874
875Under MSVC 6:
876
Tim Peters1c733232001-01-08 04:02:07 +0000877+ MS threadsafe getc is very slow (multiple layers of function calls before+
878 after each character, to lock+unlock the stream).
879+ The stream-locking functions are MS-internal -- can't access them from user
880 code.
881+ There's nothing Tim could find in the MS C or platform SDK libraries that
882 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000883+ MS fgets locks/unlocks only once per line; it's the only hook we have.
884
885So we use fgets for speed(!), despite that it's painful.
886
887MS realloc is also slow.
888
Tim Petersf29b64d2001-01-15 06:33:19 +0000889Reports from other platforms on this method vs getc_unlocked (which MS doesn't
890have):
891 Linux a wash
892 Solaris a wash
893 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000894
Tim Petersf29b64d2001-01-15 06:33:19 +0000895CAUTION: The C std isn't clear about this: in those cases where fgets
896writes something into the buffer, can it write into any position beyond the
897required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
898known on which it does; and it would be a strange way to code fgets. Still,
899getline_via_fgets may not work correctly if it does. The std test
900test_bufio.py should fail if platform fgets() routinely writes beyond the
901trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000902**************************************************************************/
903
Tim Petersf29b64d2001-01-15 06:33:19 +0000904/* Use this routine if told to, or by default on non-get_unlocked()
905 * platforms unless told not to. Yikes! Let's spell that out:
906 * On a platform with getc_unlocked():
907 * By default, use getc_unlocked().
908 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
909 * On a platform without getc_unlocked():
910 * By default, use fgets().
911 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
912 */
913#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
914#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000915#endif
916
Tim Petersf29b64d2001-01-15 06:33:19 +0000917#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
918#undef USE_FGETS_IN_GETLINE
919#endif
920
921#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000922static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000923getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000924{
Tim Peters15b83852001-01-08 00:53:12 +0000925/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000926 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
927 * to fill this much of the buffer with a known value in order to figure out
928 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
929 * than "most" lines, we waste time filling unused buffer slots. 100 is
930 * surely adequate for most peoples' email archives, chewing over source code,
931 * etc -- "regular old text files".
932 * MAXBUFSIZE is the maximum line length that lets us get away with the less
933 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
934 * cautions about boosting that. 300 was chosen because the worst real-life
935 * text-crunching job reported on Python-Dev was a mail-log crawler where over
936 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000937 */
Tim Peters142297a2001-01-15 10:36:56 +0000938#define INITBUFSIZE 100
939#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000940 char* p; /* temp */
941 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000942 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000943 char* pvfree; /* address of next free slot */
944 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000945 size_t nfree; /* # of free buffer slots; pvend-pvfree */
946 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000947 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000948
Tim Peters15b83852001-01-08 00:53:12 +0000949 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000950 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000951 */
Tim Peters142297a2001-01-15 10:36:56 +0000952 total_v_size = INITBUFSIZE; /* start small and pray */
953 pvfree = buf;
954 for (;;) {
955 Py_BEGIN_ALLOW_THREADS
956 pvend = buf + total_v_size;
957 nfree = pvend - pvfree;
958 memset(pvfree, '\n', nfree);
959 p = fgets(pvfree, nfree, fp);
960 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000961
Tim Peters142297a2001-01-15 10:36:56 +0000962 if (p == NULL) {
963 clearerr(fp);
964 if (PyErr_CheckSignals())
965 return NULL;
966 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000967 return v;
968 }
Tim Peters142297a2001-01-15 10:36:56 +0000969 /* fgets read *something* */
970 p = memchr(pvfree, '\n', nfree);
971 if (p != NULL) {
972 /* Did the \n come from fgets or from us?
973 * Since fgets stops at the first \n, and then writes
974 * \0, if it's from fgets a \0 must be next. But if
975 * that's so, it could not have come from us, since
976 * the \n's we filled the buffer with have only more
977 * \n's to the right.
978 */
979 if (p+1 < pvend && *(p+1) == '\0') {
980 /* It's from fgets: we win! In particular,
981 * we haven't done any mallocs yet, and can
982 * build the final result on the first try.
983 */
984 ++p; /* include \n from fgets */
985 }
986 else {
987 /* Must be from us: fgets didn't fill the
988 * buffer and didn't find a newline, so it
989 * must be the last and newline-free line of
990 * the file.
991 */
992 assert(p > pvfree && *(p-1) == '\0');
993 --p; /* don't include \0 from fgets */
994 }
995 v = PyString_FromStringAndSize(buf, p - buf);
996 return v;
997 }
998 /* yuck: fgets overwrote all the newlines, i.e. the entire
999 * buffer. So this line isn't over yet, or maybe it is but
1000 * we're exactly at EOF. If we haven't already, try using the
1001 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001002 */
Tim Peters142297a2001-01-15 10:36:56 +00001003 assert(*(pvend-1) == '\0');
1004 if (pvfree == buf) {
1005 pvfree = pvend - 1; /* overwrite trailing null */
1006 total_v_size = MAXBUFSIZE;
1007 }
1008 else
1009 break;
Tim Peters86821b22001-01-07 21:19:34 +00001010 }
Tim Peters142297a2001-01-15 10:36:56 +00001011
1012 /* The stack buffer isn't big enough; malloc a string object and read
1013 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001014 */
Tim Petersddea2082002-03-23 10:03:50 +00001015 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001016 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001017 if (v == NULL)
1018 return v;
1019 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001020 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1021 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001022
1023 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001024 * after setting p one beyond the end of the line. The code here is
1025 * very much like the code above, except reads into v's buffer; see
1026 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001027 */
1028 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001029 Py_BEGIN_ALLOW_THREADS
1030 pvend = BUF(v) + total_v_size;
1031 nfree = pvend - pvfree;
1032 memset(pvfree, '\n', nfree);
1033 p = fgets(pvfree, nfree, fp);
1034 Py_END_ALLOW_THREADS
1035
1036 if (p == NULL) {
1037 clearerr(fp);
1038 if (PyErr_CheckSignals()) {
1039 Py_DECREF(v);
1040 return NULL;
1041 }
1042 p = pvfree;
1043 break;
1044 }
Tim Peters86821b22001-01-07 21:19:34 +00001045 p = memchr(pvfree, '\n', nfree);
1046 if (p != NULL) {
1047 if (p+1 < pvend && *(p+1) == '\0') {
1048 /* \n came from fgets */
1049 ++p;
1050 break;
1051 }
1052 /* \n came from us; last line of file, no newline */
1053 assert(p > pvfree && *(p-1) == '\0');
1054 --p;
1055 break;
1056 }
1057 /* expand buffer and try again */
1058 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001059 increment = total_v_size >> 2; /* mild exponential growth */
1060 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001061 if (total_v_size > INT_MAX) {
1062 PyErr_SetString(PyExc_OverflowError,
1063 "line is longer than a Python string can hold");
1064 Py_DECREF(v);
1065 return NULL;
1066 }
1067 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1068 return NULL;
1069 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001070 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001071 }
1072 if (BUF(v) + total_v_size != p)
1073 _PyString_Resize(&v, p - BUF(v));
1074 return v;
1075#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001076#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001077}
Tim Petersf29b64d2001-01-15 06:33:19 +00001078#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001079
Guido van Rossum0bd24411991-04-04 15:21:57 +00001080/* Internal routine to get a line.
1081 Size argument interpretation:
1082 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001083 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001084*/
1085
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001086static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001087get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001088{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001089 FILE *fp = f->f_fp;
1090 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001091 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001092 size_t total_v_size; /* total # of slots in buffer */
1093 size_t used_v_size; /* # used slots in buffer */
1094 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001095 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001096#ifdef WITH_UNIVERSAL_NEWLINES
1097 int newlinetypes = f->f_newlinetypes;
1098 int skipnextlf = f->f_skipnextlf;
1099 int univ_newline = f->f_univ_newline;
1100#endif
Guido van Rossum0bd24411991-04-04 15:21:57 +00001101
Jack Jansen7b8c7542002-04-14 20:12:41 +00001102#if defined(USE_FGETS_IN_GETLINE)
1103#ifdef WITH_UNIVERSAL_NEWLINES
1104 if (n <= 0 && !univ_newline )
1105#else
Guido van Rossum86282062001-01-08 01:26:47 +00001106 if (n <= 0)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001107#endif
Tim Petersf29b64d2001-01-15 06:33:19 +00001108 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001109#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001110 total_v_size = n > 0 ? n : 100;
1111 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001112 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001113 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001114 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001115 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001116
Guido van Rossumce5ba841991-03-06 13:06:18 +00001117 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001118 Py_BEGIN_ALLOW_THREADS
1119 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001120#ifdef WITH_UNIVERSAL_NEWLINES
1121 if (univ_newline) {
1122 c = 'x'; /* Shut up gcc warning */
1123 while ( buf != end && (c = GETC(fp)) != EOF ) {
1124 if (skipnextlf ) {
1125 skipnextlf = 0;
1126 if (c == '\n') {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001127 /* Seeing a \n here with
1128 * skipnextlf true means we
1129 * saw a \r before.
1130 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001131 newlinetypes |= NEWLINE_CRLF;
1132 c = GETC(fp);
1133 if (c == EOF) break;
1134 } else {
1135 newlinetypes |= NEWLINE_CR;
1136 }
1137 }
1138 if (c == '\r') {
1139 skipnextlf = 1;
1140 c = '\n';
1141 } else if ( c == '\n')
1142 newlinetypes |= NEWLINE_LF;
1143 *buf++ = c;
1144 if (c == '\n') break;
1145 }
1146 if ( c == EOF && skipnextlf )
1147 newlinetypes |= NEWLINE_CR;
1148 } else /* If not universal newlines use the normal loop */
1149#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001150 while ((c = GETC(fp)) != EOF &&
1151 (*buf++ = c) != '\n' &&
1152 buf != end)
1153 ;
1154 FUNLOCKFILE(fp);
1155 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001156#ifdef WITH_UNIVERSAL_NEWLINES
1157 f->f_newlinetypes = newlinetypes;
1158 f->f_skipnextlf = skipnextlf;
1159#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001160 if (c == '\n')
1161 break;
1162 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001163 if (ferror(fp)) {
1164 PyErr_SetFromErrno(PyExc_IOError);
1165 clearerr(fp);
1166 Py_DECREF(v);
1167 return NULL;
1168 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001169 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001170 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001171 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001172 return NULL;
1173 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001174 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001175 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001176 /* Must be because buf == end */
1177 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001178 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001179 used_v_size = total_v_size;
1180 increment = total_v_size >> 2; /* mild exponential growth */
1181 total_v_size += increment;
1182 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001183 PyErr_SetString(PyExc_OverflowError,
1184 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001185 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001186 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001187 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001188 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001189 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001190 buf = BUF(v) + used_v_size;
1191 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001192 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001193
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001194 used_v_size = buf - BUF(v);
1195 if (used_v_size != total_v_size)
1196 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001197 return v;
1198}
1199
Guido van Rossum0bd24411991-04-04 15:21:57 +00001200/* External C interface */
1201
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001202PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001203PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001204{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001205 PyObject *result;
1206
Guido van Rossum3165fe61992-09-25 21:59:05 +00001207 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001208 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001209 return NULL;
1210 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001211
1212 if (PyFile_Check(f)) {
1213 if (((PyFileObject*)f)->f_fp == NULL)
1214 return err_closed();
1215 result = get_line((PyFileObject *)f, n);
1216 }
1217 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001218 PyObject *reader;
1219 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001220
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001221 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001222 if (reader == NULL)
1223 return NULL;
1224 if (n <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001225 args = Py_BuildValue("()");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001226 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001227 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001228 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001229 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001230 return NULL;
1231 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001232 result = PyEval_CallObject(reader, args);
1233 Py_DECREF(reader);
1234 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001235 if (result != NULL && !PyString_Check(result) &&
1236 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001237 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001238 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001239 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001240 "object.readline() returned non-string");
1241 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001242 }
1243
1244 if (n < 0 && result != NULL && PyString_Check(result)) {
1245 char *s = PyString_AS_STRING(result);
1246 int len = PyString_GET_SIZE(result);
1247 if (len == 0) {
1248 Py_DECREF(result);
1249 result = NULL;
1250 PyErr_SetString(PyExc_EOFError,
1251 "EOF when reading a line");
1252 }
1253 else if (s[len-1] == '\n') {
1254 if (result->ob_refcnt == 1)
1255 _PyString_Resize(&result, len-1);
1256 else {
1257 PyObject *v;
1258 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001259 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001260 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001261 }
1262 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001263 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001264#ifdef Py_USING_UNICODE
1265 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1266 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1267 int len = PyUnicode_GET_SIZE(result);
1268 if (len == 0) {
1269 Py_DECREF(result);
1270 result = NULL;
1271 PyErr_SetString(PyExc_EOFError,
1272 "EOF when reading a line");
1273 }
1274 else if (s[len-1] == '\n') {
1275 if (result->ob_refcnt == 1)
1276 PyUnicode_Resize(&result, len-1);
1277 else {
1278 PyObject *v;
1279 v = PyUnicode_FromUnicode(s, len-1);
1280 Py_DECREF(result);
1281 result = v;
1282 }
1283 }
1284 }
1285#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001286 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001287}
1288
1289/* Python method */
1290
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001291static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001292file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001293{
Guido van Rossum789a1611997-05-10 22:33:55 +00001294 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001295
Guido van Rossumd7297e61992-07-06 14:19:26 +00001296 if (f->f_fp == NULL)
1297 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001298 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001299 return NULL;
1300 if (n == 0)
1301 return PyString_FromString("");
1302 if (n < 0)
1303 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001304 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001305}
1306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001308file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001309{
Guido van Rossum789a1611997-05-10 22:33:55 +00001310 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001311 PyObject *list;
1312 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001313 char small_buffer[SMALLCHUNK];
1314 char *buffer = small_buffer;
1315 size_t buffersize = SMALLCHUNK;
1316 PyObject *big_buffer = NULL;
1317 size_t nfilled = 0;
1318 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001319 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001320 char *p, *q, *end;
1321 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001322 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001323
Guido van Rossumd7297e61992-07-06 14:19:26 +00001324 if (f->f_fp == NULL)
1325 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001326 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001327 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001328 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001329 return NULL;
1330 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001331 if (shortread)
1332 nread = 0;
1333 else {
1334 Py_BEGIN_ALLOW_THREADS
1335 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001336 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001337 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001338 Py_END_ALLOW_THREADS
1339 shortread = (nread < buffersize-nfilled);
1340 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001341 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001342 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001343 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001344 break;
1345 PyErr_SetFromErrno(PyExc_IOError);
1346 clearerr(f->f_fp);
1347 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001348 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001349 list = NULL;
1350 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001351 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001352 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001353 p = memchr(buffer+nfilled, '\n', nread);
1354 if (p == NULL) {
1355 /* Need a larger buffer to fit this line */
1356 nfilled += nread;
1357 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001358 if (buffersize > INT_MAX) {
1359 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001360 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001361 goto error;
1362 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001363 if (big_buffer == NULL) {
1364 /* Create the big buffer */
1365 big_buffer = PyString_FromStringAndSize(
1366 NULL, buffersize);
1367 if (big_buffer == NULL)
1368 goto error;
1369 buffer = PyString_AS_STRING(big_buffer);
1370 memcpy(buffer, small_buffer, nfilled);
1371 }
1372 else {
1373 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001374 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1375 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001376 buffer = PyString_AS_STRING(big_buffer);
1377 }
1378 continue;
1379 }
1380 end = buffer+nfilled+nread;
1381 q = buffer;
1382 do {
1383 /* Process complete lines */
1384 p++;
1385 line = PyString_FromStringAndSize(q, p-q);
1386 if (line == NULL)
1387 goto error;
1388 err = PyList_Append(list, line);
1389 Py_DECREF(line);
1390 if (err != 0)
1391 goto error;
1392 q = p;
1393 p = memchr(q, '\n', end-q);
1394 } while (p != NULL);
1395 /* Move the remaining incomplete line to the start */
1396 nfilled = end-q;
1397 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001398 if (sizehint > 0)
1399 if (totalread >= (size_t)sizehint)
1400 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001401 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001402 if (nfilled != 0) {
1403 /* Partial last line */
1404 line = PyString_FromStringAndSize(buffer, nfilled);
1405 if (line == NULL)
1406 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001407 if (sizehint > 0) {
1408 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001409 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001410 if (rest == NULL) {
1411 Py_DECREF(line);
1412 goto error;
1413 }
1414 PyString_Concat(&line, rest);
1415 Py_DECREF(rest);
1416 if (line == NULL)
1417 goto error;
1418 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001419 err = PyList_Append(list, line);
1420 Py_DECREF(line);
1421 if (err != 0)
1422 goto error;
1423 }
1424 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001425 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001426 return list;
1427}
1428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001430file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001431{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001432 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001433 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001434 if (f->f_fp == NULL)
1435 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001436 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001437 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001438 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001439 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001440 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001441 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001442 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001443 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001444 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001445 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001446 return NULL;
1447 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001448 Py_INCREF(Py_None);
1449 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001450}
1451
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001452static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001453file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001454{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001455#define CHUNKSIZE 1000
1456 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001457 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001458 PyObject *result;
1459 int i, j, index, len, nwritten, islist;
1460
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001461 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001462 if (f->f_fp == NULL)
1463 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001464
1465 result = NULL;
1466 list = NULL;
1467 islist = PyList_Check(seq);
1468 if (islist)
1469 it = NULL;
1470 else {
1471 it = PyObject_GetIter(seq);
1472 if (it == NULL) {
1473 PyErr_SetString(PyExc_TypeError,
1474 "writelines() requires an iterable argument");
1475 return NULL;
1476 }
1477 /* From here on, fail by going to error, to reclaim "it". */
1478 list = PyList_New(CHUNKSIZE);
1479 if (list == NULL)
1480 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001481 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001482
1483 /* Strategy: slurp CHUNKSIZE lines into a private list,
1484 checking that they are all strings, then write that list
1485 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001486 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001487 if (islist) {
1488 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001489 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001490 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001491 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001492 j = PyList_GET_SIZE(list);
1493 }
1494 else {
1495 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001496 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001497 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001498 if (PyErr_Occurred())
1499 goto error;
1500 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001501 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001502 PyList_SetItem(list, j, line);
1503 }
1504 }
1505 if (j == 0)
1506 break;
1507
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001508 /* Check that all entries are indeed strings. If not,
1509 apply the same rules as for file.write() and
1510 convert the results to strings. This is slow, but
1511 seems to be the only way since all conversion APIs
1512 could potentially execute Python code. */
1513 for (i = 0; i < j; i++) {
1514 PyObject *v = PyList_GET_ITEM(list, i);
1515 if (!PyString_Check(v)) {
1516 const char *buffer;
1517 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001518 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001519 PyObject_AsReadBuffer(v,
1520 (const void**)&buffer,
1521 &len)) ||
1522 PyObject_AsCharBuffer(v,
1523 &buffer,
1524 &len))) {
1525 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001526 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001527 goto error;
1528 }
1529 line = PyString_FromStringAndSize(buffer,
1530 len);
1531 if (line == NULL)
1532 goto error;
1533 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001534 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001535 }
1536 }
1537
1538 /* Since we are releasing the global lock, the
1539 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001540 Py_BEGIN_ALLOW_THREADS
1541 f->f_softspace = 0;
1542 errno = 0;
1543 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001544 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001545 len = PyString_GET_SIZE(line);
1546 nwritten = fwrite(PyString_AS_STRING(line),
1547 1, len, f->f_fp);
1548 if (nwritten != len) {
1549 Py_BLOCK_THREADS
1550 PyErr_SetFromErrno(PyExc_IOError);
1551 clearerr(f->f_fp);
1552 goto error;
1553 }
1554 }
1555 Py_END_ALLOW_THREADS
1556
1557 if (j < CHUNKSIZE)
1558 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001559 }
1560
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001561 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001562 result = Py_None;
1563 error:
1564 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001565 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001566 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001567#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001568}
1569
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001570static PyObject *
1571file_getiter(PyFileObject *f)
1572{
1573 if (f->f_fp == NULL)
1574 return err_closed();
1575 Py_INCREF(f);
1576 return (PyObject *)f;
1577}
1578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001579PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001580"readline([size]) -> next line from the file, as a string.\n"
1581"\n"
1582"Retain newline. A non-negative size argument limits the maximum\n"
1583"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001584"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001586PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001587"read([size]) -> read at most size bytes, returned as a string.\n"
1588"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001589"If the size argument is negative or omitted, read until EOF is reached.\n"
1590"Notice that when in non-blocking mode, less data than what was requested\n"
1591"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001593PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001594"write(str) -> None. Write string str to file.\n"
1595"\n"
1596"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001597"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001598
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001599PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001600"fileno() -> integer \"file descriptor\".\n"
1601"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001602"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001604PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001605"seek(offset[, whence]) -> None. Move to new file position.\n"
1606"\n"
1607"Argument offset is a byte count. Optional argument whence defaults to\n"
1608"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1609"(move relative to current position, positive or negative), and 2 (move\n"
1610"relative to end of file, usually negative, although many platforms allow\n"
1611"seeking beyond the end of a file).\n"
1612"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001613"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001614
Guido van Rossumd7047b31995-01-02 19:07:15 +00001615#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001616PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001617"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1618"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001619"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001620#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001622PyDoc_STRVAR(tell_doc,
1623"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001625PyDoc_STRVAR(readinto_doc,
1626"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001628PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001629"readlines([size]) -> list of strings, each a line from the file.\n"
1630"\n"
1631"Call readline() repeatedly and return a list of the lines so read.\n"
1632"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001633"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001636"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001637"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001638"For backward compatibility. File objects now include the performance\n"
1639"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001641PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001642"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001643"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001644"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001646
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001647PyDoc_STRVAR(flush_doc,
1648"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001650PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001651"close() -> None or (perhaps) an integer. Close the file.\n"
1652"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001653"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001654"further I/O operations. close() may be called more than once without\n"
1655"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001656"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001658PyDoc_STRVAR(isatty_doc,
1659"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001660
1661static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001662 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1663 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1664 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1665 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1666 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001667#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001668 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001669#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001670 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1671 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1672 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1673 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1674 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1675 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1676 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1677 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1678 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001679};
1680
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001681#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001682
Guido van Rossum6f799372001-09-20 20:46:19 +00001683static PyMemberDef file_memberlist[] = {
1684 {"softspace", T_INT, OFF(f_softspace), 0,
1685 "flag indicating that a space needs to be printed; used by print"},
1686 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001687 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001688 {"name", T_OBJECT, OFF(f_name), RO,
1689 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001690 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1691 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001692 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001693 {NULL} /* Sentinel */
1694};
1695
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001696static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001697get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001698{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001699 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001700}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001701#ifdef WITH_UNIVERSAL_NEWLINES
1702static PyObject *
1703get_newlines(PyFileObject *f, void *closure)
1704{
1705 switch (f->f_newlinetypes) {
1706 case NEWLINE_UNKNOWN:
1707 Py_INCREF(Py_None);
1708 return Py_None;
1709 case NEWLINE_CR:
1710 return PyString_FromString("\r");
1711 case NEWLINE_LF:
1712 return PyString_FromString("\n");
1713 case NEWLINE_CR|NEWLINE_LF:
1714 return Py_BuildValue("(ss)", "\r", "\n");
1715 case NEWLINE_CRLF:
1716 return PyString_FromString("\r\n");
1717 case NEWLINE_CR|NEWLINE_CRLF:
1718 return Py_BuildValue("(ss)", "\r", "\r\n");
1719 case NEWLINE_LF|NEWLINE_CRLF:
1720 return Py_BuildValue("(ss)", "\n", "\r\n");
1721 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1722 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1723 default:
Jeremy Hylton8b735422002-08-14 21:01:41 +00001724 PyErr_Format(PyExc_SystemError,
1725 "Unknown newlines value 0x%x\n",
1726 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001727 return NULL;
1728 }
1729}
1730#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +00001731
Guido van Rossum32d34c82001-09-20 21:45:26 +00001732static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001733 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001734#ifdef WITH_UNIVERSAL_NEWLINES
Jeremy Hylton8b735422002-08-14 21:01:41 +00001735 {"newlines", (getter)get_newlines, NULL,
1736 "end-of-line convention used in this file"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001737#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00001738 {0},
1739};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001741static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001742drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001743{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001744 if (f->f_buf != NULL) {
1745 PyMem_Free(f->f_buf);
1746 f->f_buf = NULL;
1747 }
Guido van Rossum65967252001-04-21 13:20:18 +00001748}
1749
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001750/* Make sure that file has a readahead buffer with at least one byte
1751 (unless at EOF) and no more than bufsize. Returns negative value on
1752 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001753static int
1754readahead(PyFileObject *f, int bufsize)
1755{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001756 int chunksize;
1757
1758 if (f->f_buf != NULL) {
1759 if( (f->f_bufend - f->f_bufptr) >= 1)
1760 return 0;
1761 else
1762 drop_readahead(f);
1763 }
1764 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1765 return -1;
1766 }
1767 Py_BEGIN_ALLOW_THREADS
1768 errno = 0;
1769 chunksize = Py_UniversalNewlineFread(
1770 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1771 Py_END_ALLOW_THREADS
1772 if (chunksize == 0) {
1773 if (ferror(f->f_fp)) {
1774 PyErr_SetFromErrno(PyExc_IOError);
1775 clearerr(f->f_fp);
1776 drop_readahead(f);
1777 return -1;
1778 }
1779 }
1780 f->f_bufptr = f->f_buf;
1781 f->f_bufend = f->f_buf + chunksize;
1782 return 0;
1783}
1784
1785/* Used by file_iternext. The returned string will start with 'skip'
1786 uninitialized bytes followed by the remainder of the line. Don't be
1787 horrified by the recursive call: maximum recursion depth is limited by
1788 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1789
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001790static PyStringObject *
1791readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1792{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001793 PyStringObject* s;
1794 char *bufptr;
1795 char *buf;
1796 int len;
1797
1798 if (f->f_buf == NULL)
1799 if (readahead(f, bufsize) < 0)
1800 return NULL;
1801
1802 len = f->f_bufend - f->f_bufptr;
1803 if (len == 0)
1804 return (PyStringObject *)
1805 PyString_FromStringAndSize(NULL, skip);
1806 bufptr = memchr(f->f_bufptr, '\n', len);
1807 if (bufptr != NULL) {
1808 bufptr++; /* Count the '\n' */
1809 len = bufptr - f->f_bufptr;
1810 s = (PyStringObject *)
1811 PyString_FromStringAndSize(NULL, skip+len);
1812 if (s == NULL)
1813 return NULL;
1814 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1815 f->f_bufptr = bufptr;
1816 if (bufptr == f->f_bufend)
1817 drop_readahead(f);
1818 } else {
1819 bufptr = f->f_bufptr;
1820 buf = f->f_buf;
1821 f->f_buf = NULL; /* Force new readahead buffer */
1822 s = readahead_get_line_skip(
1823 f, skip+len, bufsize + (bufsize>>2) );
1824 if (s == NULL) {
1825 PyMem_Free(buf);
1826 return NULL;
1827 }
1828 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1829 PyMem_Free(buf);
1830 }
1831 return s;
1832}
1833
1834/* A larger buffer size may actually decrease performance. */
1835#define READAHEAD_BUFSIZE 8192
1836
1837static PyObject *
1838file_iternext(PyFileObject *f)
1839{
1840 PyStringObject* l;
1841
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001842 if (f->f_fp == NULL)
1843 return err_closed();
1844
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001845 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1846 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1847 Py_XDECREF(l);
1848 return NULL;
1849 }
1850 return (PyObject *)l;
1851}
1852
1853
Tim Peters59c9a642001-09-13 05:38:56 +00001854static PyObject *
1855file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1856{
Tim Peters44410012001-09-14 03:26:08 +00001857 PyObject *self;
1858 static PyObject *not_yet_string;
1859
1860 assert(type != NULL && type->tp_alloc != NULL);
1861
1862 if (not_yet_string == NULL) {
1863 not_yet_string = PyString_FromString("<uninitialized file>");
1864 if (not_yet_string == NULL)
1865 return NULL;
1866 }
1867
1868 self = type->tp_alloc(type, 0);
1869 if (self != NULL) {
1870 /* Always fill in the name and mode, so that nobody else
1871 needs to special-case NULLs there. */
1872 Py_INCREF(not_yet_string);
1873 ((PyFileObject *)self)->f_name = not_yet_string;
1874 Py_INCREF(not_yet_string);
1875 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001876 Py_INCREF(Py_None);
1877 ((PyFileObject *)self)->f_encoding = Py_None;
Tim Peters44410012001-09-14 03:26:08 +00001878 }
1879 return self;
1880}
1881
1882static int
1883file_init(PyObject *self, PyObject *args, PyObject *kwds)
1884{
1885 PyFileObject *foself = (PyFileObject *)self;
1886 int ret = 0;
Tim Peters59c9a642001-09-13 05:38:56 +00001887 static char *kwlist[] = {"name", "mode", "buffering", 0};
1888 char *name = NULL;
1889 char *mode = "r";
1890 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001891 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001892
1893 assert(PyFile_Check(self));
1894 if (foself->f_fp != NULL) {
1895 /* Have to close the existing file first. */
1896 PyObject *closeresult = file_close(foself);
1897 if (closeresult == NULL)
1898 return -1;
1899 Py_DECREF(closeresult);
1900 }
Tim Peters59c9a642001-09-13 05:38:56 +00001901
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001902#ifdef Py_WIN_WIDE_FILENAMES
1903 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1904 PyObject *po;
1905 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1906 kwlist, &po, &mode, &bufsize)) {
1907 wideargument = 1;
1908 if (fill_file_fields(foself, NULL, name, mode,
1909 fclose, po) == NULL)
1910 goto Error;
1911 } else {
1912 /* Drop the argument parsing error as narrow
1913 strings are also valid. */
1914 PyErr_Clear();
1915 }
1916 }
1917#endif
1918
1919 if (!wideargument) {
1920 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1921 Py_FileSystemDefaultEncoding,
1922 &name,
1923 &mode, &bufsize))
1924 return -1;
1925 if (fill_file_fields(foself, NULL, name, mode,
1926 fclose, NULL) == NULL)
1927 goto Error;
1928 }
Tim Peters44410012001-09-14 03:26:08 +00001929 if (open_the_file(foself, name, mode) == NULL)
1930 goto Error;
1931 PyFile_SetBufSize(self, bufsize);
1932 goto Done;
1933
1934Error:
1935 ret = -1;
1936 /* fall through */
1937Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001938 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001939 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001940}
1941
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001942PyDoc_VAR(file_doc) =
1943PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001944"file(name[, mode[, buffering]]) -> file object\n"
1945"\n"
1946"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1947"writing or appending. The file will be created if it doesn't exist\n"
1948"when opened for writing or appending; it will be truncated when\n"
1949"opened for writing. Add a 'b' to the mode for binary files.\n"
1950"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1951"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001952"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001953)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001954#ifdef WITH_UNIVERSAL_NEWLINES
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001955PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001956"Add a 'U' to mode to open the file for input with universal newline\n"
1957"support. Any line ending in the input file will be seen as a '\\n'\n"
1958"in Python. Also, a file so opened gains the attribute 'newlines';\n"
1959"the value for this attribute is one of None (no newline read yet),\n"
1960"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
1961"\n"
1962"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001963)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001964#endif /* WITH_UNIVERSAL_NEWLINES */
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001965PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001966"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967"Note: open() is an alias for file()."
1968);
Tim Peters59c9a642001-09-13 05:38:56 +00001969
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001970PyTypeObject PyFile_Type = {
1971 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001972 0,
1973 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001974 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001975 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001976 (destructor)file_dealloc, /* tp_dealloc */
1977 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001978 0, /* tp_getattr */
1979 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001980 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001982 0, /* tp_as_number */
1983 0, /* tp_as_sequence */
1984 0, /* tp_as_mapping */
1985 0, /* tp_hash */
1986 0, /* tp_call */
1987 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00001989 /* softspace is writable: we must supply tp_setattro */
1990 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00001991 0, /* tp_as_buffer */
Guido van Rossum9475a232001-10-05 20:51:39 +00001992 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00001993 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 0, /* tp_traverse */
1995 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00001996 0, /* tp_richcompare */
1997 0, /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001998 (getiterfunc)file_getiter, /* tp_iter */
1999 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002000 file_methods, /* tp_methods */
2001 file_memberlist, /* tp_members */
2002 file_getsetlist, /* tp_getset */
2003 0, /* tp_base */
2004 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002005 0, /* tp_descr_get */
2006 0, /* tp_descr_set */
2007 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00002008 (initproc)file_init, /* tp_init */
2009 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002010 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002011 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002012};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002013
2014/* Interface for the 'soft space' between print items. */
2015
2016int
Fred Drakefd99de62000-07-09 05:02:18 +00002017PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002018{
2019 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002020 if (f == NULL) {
2021 /* Do nothing */
2022 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002023 else if (PyFile_Check(f)) {
2024 oldflag = ((PyFileObject *)f)->f_softspace;
2025 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002026 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002027 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002028 PyObject *v;
2029 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002030 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002031 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002032 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002033 if (PyInt_Check(v))
2034 oldflag = PyInt_AsLong(v);
2035 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002036 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002038 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002039 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002040 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002041 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2042 PyErr_Clear();
2043 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002044 }
2045 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00002046 return oldflag;
2047}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002048
2049/* Interfaces to write objects/strings to file-like objects */
2050
2051int
Fred Drakefd99de62000-07-09 05:02:18 +00002052PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002053{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002055 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002056 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002057 return -1;
2058 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002059 else if (PyFile_Check(f)) {
2060 FILE *fp = PyFile_AsFile(f);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002061 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2062 int result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002063 if (fp == NULL) {
2064 err_closed();
2065 return -1;
2066 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002067#ifdef Py_USING_UNICODE
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002068 if ((flags & Py_PRINT_RAW) &&
2069 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002070 char *cenc = PyString_AS_STRING(enc);
2071 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2072 if (value == NULL)
2073 return -1;
2074 } else {
2075 value = v;
2076 Py_INCREF(value);
2077 }
2078 result = PyObject_Print(value, fp, flags);
2079 Py_DECREF(value);
2080 return result;
2081#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002083#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002084 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002085 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002086 if (writer == NULL)
2087 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002088 if (flags & Py_PRINT_RAW) {
2089 if (PyUnicode_Check(v)) {
2090 value = v;
2091 Py_INCREF(value);
2092 } else
2093 value = PyObject_Str(v);
2094 }
2095 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002097 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002099 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002100 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002101 args = Py_BuildValue("(O)", value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002102 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002103 Py_DECREF(value);
2104 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002105 return -1;
2106 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107 result = PyEval_CallObject(writer, args);
2108 Py_DECREF(args);
2109 Py_DECREF(value);
2110 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002111 if (result == NULL)
2112 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002114 return 0;
2115}
2116
Guido van Rossum27a60b11997-05-22 22:25:11 +00002117int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002118PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002119{
2120 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002121 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002122 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002123 PyErr_SetString(PyExc_SystemError,
2124 "null file for PyFile_WriteString");
2125 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002127 else if (PyFile_Check(f)) {
2128 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002129 if (fp == NULL) {
2130 err_closed();
2131 return -1;
2132 }
2133 fputs(s, fp);
2134 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 else if (!PyErr_Occurred()) {
2137 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002138 int err;
2139 if (v == NULL)
2140 return -1;
2141 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2142 Py_DECREF(v);
2143 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002144 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002145 else
2146 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002147}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002148
2149/* Try to get a file-descriptor from a Python object. If the object
2150 is an integer or long integer, its value is returned. If not, the
2151 object's fileno() method is called if it exists; the method must return
2152 an integer or long integer, which is returned as the file descriptor value.
2153 -1 is returned on failure.
2154*/
2155
2156int PyObject_AsFileDescriptor(PyObject *o)
2157{
2158 int fd;
2159 PyObject *meth;
2160
2161 if (PyInt_Check(o)) {
2162 fd = PyInt_AsLong(o);
2163 }
2164 else if (PyLong_Check(o)) {
2165 fd = PyLong_AsLong(o);
2166 }
2167 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2168 {
2169 PyObject *fno = PyEval_CallObject(meth, NULL);
2170 Py_DECREF(meth);
2171 if (fno == NULL)
2172 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002173
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002174 if (PyInt_Check(fno)) {
2175 fd = PyInt_AsLong(fno);
2176 Py_DECREF(fno);
2177 }
2178 else if (PyLong_Check(fno)) {
2179 fd = PyLong_AsLong(fno);
2180 Py_DECREF(fno);
2181 }
2182 else {
2183 PyErr_SetString(PyExc_TypeError,
2184 "fileno() returned a non-integer");
2185 Py_DECREF(fno);
2186 return -1;
2187 }
2188 }
2189 else {
2190 PyErr_SetString(PyExc_TypeError,
2191 "argument must be an int, or have a fileno() method.");
2192 return -1;
2193 }
2194
2195 if (fd < 0) {
2196 PyErr_Format(PyExc_ValueError,
2197 "file descriptor cannot be a negative integer (%i)",
2198 fd);
2199 return -1;
2200 }
2201 return fd;
2202}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002203
2204#ifdef WITH_UNIVERSAL_NEWLINES
2205/* From here on we need access to the real fgets and fread */
2206#undef fgets
2207#undef fread
2208
2209/*
2210** Py_UniversalNewlineFgets is an fgets variation that understands
2211** all of \r, \n and \r\n conventions.
2212** The stream should be opened in binary mode.
2213** If fobj is NULL the routine always does newline conversion, and
2214** it may peek one char ahead to gobble the second char in \r\n.
2215** If fobj is non-NULL it must be a PyFileObject. In this case there
2216** is no readahead but in stead a flag is used to skip a following
2217** \n on the next read. Also, if the file is open in binary mode
2218** the whole conversion is skipped. Finally, the routine keeps track of
2219** the different types of newlines seen.
2220** Note that we need no error handling: fgets() treats error and eof
2221** identically.
2222*/
2223char *
2224Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2225{
2226 char *p = buf;
2227 int c;
2228 int newlinetypes = 0;
2229 int skipnextlf = 0;
2230 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002231
Jack Jansen7b8c7542002-04-14 20:12:41 +00002232 if (fobj) {
2233 if (!PyFile_Check(fobj)) {
2234 errno = ENXIO; /* What can you do... */
2235 return NULL;
2236 }
2237 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2238 if ( !univ_newline )
2239 return fgets(buf, n, stream);
2240 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2241 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2242 }
2243 FLOCKFILE(stream);
2244 c = 'x'; /* Shut up gcc warning */
2245 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2246 if (skipnextlf ) {
2247 skipnextlf = 0;
2248 if (c == '\n') {
2249 /* Seeing a \n here with skipnextlf true
2250 ** means we saw a \r before.
2251 */
2252 newlinetypes |= NEWLINE_CRLF;
2253 c = GETC(stream);
2254 if (c == EOF) break;
2255 } else {
2256 /*
2257 ** Note that c == EOF also brings us here,
2258 ** so we're okay if the last char in the file
2259 ** is a CR.
2260 */
2261 newlinetypes |= NEWLINE_CR;
2262 }
2263 }
2264 if (c == '\r') {
2265 /* A \r is translated into a \n, and we skip
2266 ** an adjacent \n, if any. We don't set the
2267 ** newlinetypes flag until we've seen the next char.
2268 */
2269 skipnextlf = 1;
2270 c = '\n';
2271 } else if ( c == '\n') {
2272 newlinetypes |= NEWLINE_LF;
2273 }
2274 *p++ = c;
2275 if (c == '\n') break;
2276 }
2277 if ( c == EOF && skipnextlf )
2278 newlinetypes |= NEWLINE_CR;
2279 FUNLOCKFILE(stream);
2280 *p = '\0';
2281 if (fobj) {
2282 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2283 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2284 } else if ( skipnextlf ) {
2285 /* If we have no file object we cannot save the
2286 ** skipnextlf flag. We have to readahead, which
2287 ** will cause a pause if we're reading from an
2288 ** interactive stream, but that is very unlikely
2289 ** unless we're doing something silly like
2290 ** execfile("/dev/tty").
2291 */
2292 c = GETC(stream);
2293 if ( c != '\n' )
2294 ungetc(c, stream);
2295 }
2296 if (p == buf)
2297 return NULL;
2298 return buf;
2299}
2300
2301/*
2302** Py_UniversalNewlineFread is an fread variation that understands
2303** all of \r, \n and \r\n conventions.
2304** The stream should be opened in binary mode.
2305** fobj must be a PyFileObject. In this case there
2306** is no readahead but in stead a flag is used to skip a following
2307** \n on the next read. Also, if the file is open in binary mode
2308** the whole conversion is skipped. Finally, the routine keeps track of
2309** the different types of newlines seen.
2310*/
2311size_t
Tim Peters058b1412002-04-21 07:29:14 +00002312Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002313 FILE *stream, PyObject *fobj)
2314{
Tim Peters058b1412002-04-21 07:29:14 +00002315 char *dst = buf;
2316 PyFileObject *f = (PyFileObject *)fobj;
2317 int newlinetypes, skipnextlf;
2318
2319 assert(buf != NULL);
2320 assert(stream != NULL);
2321
Jack Jansen7b8c7542002-04-14 20:12:41 +00002322 if (!fobj || !PyFile_Check(fobj)) {
2323 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002324 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002325 }
Tim Peters058b1412002-04-21 07:29:14 +00002326 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002327 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002328 newlinetypes = f->f_newlinetypes;
2329 skipnextlf = f->f_skipnextlf;
2330 /* Invariant: n is the number of bytes remaining to be filled
2331 * in the buffer.
2332 */
2333 while (n) {
2334 size_t nread;
2335 int shortread;
2336 char *src = dst;
2337
2338 nread = fread(dst, 1, n, stream);
2339 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002340 if (nread == 0)
2341 break;
2342
Tim Peterse1682a82002-04-21 18:15:20 +00002343 n -= nread; /* assuming 1 byte out for each in; will adjust */
2344 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002345 while (nread--) {
2346 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002347 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002348 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002349 *dst++ = '\n';
2350 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002351 }
2352 else if (skipnextlf && c == '\n') {
2353 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002354 skipnextlf = 0;
2355 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002356 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002357 }
2358 else {
2359 /* Normal char to be stored in buffer. Also
2360 * update the newlinetypes flag if either this
2361 * is an LF or the previous char was a CR.
2362 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002363 if (c == '\n')
2364 newlinetypes |= NEWLINE_LF;
2365 else if (skipnextlf)
2366 newlinetypes |= NEWLINE_CR;
2367 *dst++ = c;
2368 skipnextlf = 0;
2369 }
2370 }
Tim Peters058b1412002-04-21 07:29:14 +00002371 if (shortread) {
2372 /* If this is EOF, update type flags. */
2373 if (skipnextlf && feof(stream))
2374 newlinetypes |= NEWLINE_CR;
2375 break;
2376 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002377 }
Tim Peters058b1412002-04-21 07:29:14 +00002378 f->f_newlinetypes = newlinetypes;
2379 f->f_skipnextlf = skipnextlf;
2380 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002381}
2382#endif