blob: 6faabc3b79c8d43a604fb2d6458df4222539cf72 [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
Andrew MacIntyrec4874392002-02-26 11:36:35 +000024#if defined(PYOS_OS2) && defined(PYCC_GCC)
25#include <io.h>
26#endif
27
Guido van Rossumc0b618a1997-05-02 03:12:38 +000028#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000029
Guido van Rossumff7e83d1999-08-27 20:39:37 +000030#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000031#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000032#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000033
Jack Jansen7b8c7542002-04-14 20:12:41 +000034#ifdef HAVE_GETC_UNLOCKED
35#define GETC(f) getc_unlocked(f)
36#define FLOCKFILE(f) flockfile(f)
37#define FUNLOCKFILE(f) funlockfile(f)
38#else
39#define GETC(f) getc(f)
40#define FLOCKFILE(f)
41#define FUNLOCKFILE(f)
42#endif
43
Jack Jansen7b8c7542002-04-14 20:12:41 +000044/* Bits in f_newlinetypes */
45#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
46#define NEWLINE_CR 1 /* \r newline seen */
47#define NEWLINE_LF 2 /* \n newline seen */
48#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000049
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000050FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000051PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000053 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000055 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000056 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057}
58
Guido van Rossumc0b618a1997-05-02 03:12:38 +000059PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000060PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000063 return NULL;
64 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066}
67
Neil Schemenauered19b882002-03-23 02:06:50 +000068/* On Unix, fopen will succeed for directories.
69 In Python, there should be no file objects referring to
70 directories, so we need a check. */
71
72static PyFileObject*
73dircheck(PyFileObject* f)
74{
75#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
76 struct stat buf;
77 if (f->f_fp == NULL)
78 return f;
79 if (fstat(fileno(f->f_fp), &buf) == 0 &&
80 S_ISDIR(buf.st_mode)) {
81#ifdef HAVE_STRERROR
82 char *msg = strerror(EISDIR);
83#else
84 char *msg = "Is a directory";
85#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000086 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000087 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000088 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000089 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000090 return NULL;
91 }
92#endif
93 return f;
94}
95
Tim Peters59c9a642001-09-13 05:38:56 +000096
97static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +000098fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
99 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100{
Tim Peters59c9a642001-09-13 05:38:56 +0000101 assert(f != NULL);
102 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000103 assert(f->f_fp == NULL);
104
105 Py_DECREF(f->f_name);
106 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000107 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000108
109 Py_INCREF (name);
110 f->f_name = name;
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000113
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000114 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000115 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000116 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000117 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000118 f->f_univ_newline = (strchr(mode, 'U') != NULL);
119 f->f_newlinetypes = NEWLINE_UNKNOWN;
120 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000121 Py_INCREF(Py_None);
122 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000123
Tim Peters59c9a642001-09-13 05:38:56 +0000124 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000127 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000128 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129}
130
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000131/* check for known incorrect mode strings - problem is, platforms are
132 free to accept any mode characters they like and are supposed to
133 ignore stuff they don't understand... write or append mode with
134 universal newline support is expressly forbidden by PEP 278. */
135/* zero return is kewl - one is un-kewl */
136static int
137check_the_mode(char *mode)
138{
Neal Norwitz76dc0812006-01-08 06:13:13 +0000139 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000140
141 switch (len) {
142 case 0:
143 PyErr_SetString(PyExc_ValueError, "empty mode string");
144 return 1;
145
146 /* reject wU, aU */
147 case 2:
148 switch (mode[0]) {
149 case 'w':
150 case 'a':
151 if (mode[1] == 'U') {
152 PyErr_SetString(PyExc_ValueError,
153 "invalid mode string");
154 return 1;
155 }
156 break;
157 }
158 break;
159
160 /* reject w+U, a+U, wU+, aU+ */
161 case 3:
162 switch (mode[0]) {
163 case 'w':
164 case 'a':
165 if ((mode[1] == '+' && mode[2] == 'U') ||
166 (mode[1] == 'U' && mode[2] == '+')) {
167 PyErr_SetString(PyExc_ValueError,
168 "invalid mode string");
169 return 1;
170 }
171 break;
172 }
173 break;
174 }
175
176 return 0;
177}
178
Tim Peters59c9a642001-09-13 05:38:56 +0000179static PyObject *
180open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181{
Tim Peters59c9a642001-09-13 05:38:56 +0000182 assert(f != NULL);
183 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000184#ifdef MS_WINDOWS
185 /* windows ignores the passed name in order to support Unicode */
186 assert(f->f_name != NULL);
187#else
Tim Peters59c9a642001-09-13 05:38:56 +0000188 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000189#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000190 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000191 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000192
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000193 if (check_the_mode(mode))
194 return NULL;
195
Tim Peters8fa45672001-09-13 21:01:29 +0000196 /* rexec.py can't stop a user from getting the file() constructor --
197 all they have to do is get *any* file object f, and then do
198 type(f). Here we prevent them from doing damage with it. */
199 if (PyEval_GetRestricted()) {
200 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000201 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000202 return NULL;
203 }
Tim Petersa27a1502001-11-09 20:59:14 +0000204 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000205
206 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
207 mode = "rb";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000208#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000209 if (PyUnicode_Check(f->f_name)) {
210 PyObject *wmode;
211 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
212 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000213 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000214 /* PyUnicode_AS_UNICODE OK without thread
215 lock as it is a simple dereference. */
216 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
217 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000218 Py_END_ALLOW_THREADS
219 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000220 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000221 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000222#endif
223 if (NULL == f->f_fp && NULL != name) {
224 Py_BEGIN_ALLOW_THREADS
225 f->f_fp = fopen(name, mode);
226 Py_END_ALLOW_THREADS
227 }
228
Guido van Rossuma08095a1991-02-13 23:25:27 +0000229 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000230#ifdef _MSC_VER
231 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
232 * across all Windows flavors. When it sets EINVAL varies
233 * across Windows flavors, the exact conditions aren't
234 * documented, and the answer lies in the OS's implementation
235 * of Win32's CreateFile function (whose source is secret).
236 * Seems the best we can do is map EINVAL to ENOENT.
237 */
238 if (errno == 0) /* bad mode string */
239 errno = EINVAL;
240 else if (errno == EINVAL) /* unknown, but not a mode string */
241 errno = ENOENT;
242#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000243 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000244 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000245 mode);
246 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000247 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000248 f = NULL;
249 }
Tim Peters2ea91112002-04-08 04:13:12 +0000250 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000251 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000252 return (PyObject *)f;
253}
254
255PyObject *
256PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
257{
Tim Peters44410012001-09-14 03:26:08 +0000258 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
259 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000260 if (f != NULL) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000261 PyObject *o_name = PyString_FromString(name);
262 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000263 Py_DECREF(f);
264 f = NULL;
265 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000266 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000267 }
268 return (PyObject *) f;
269}
270
271PyObject *
272PyFile_FromString(char *name, char *mode)
273{
274 extern int fclose(FILE *);
275 PyFileObject *f;
276
277 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
278 if (f != NULL) {
279 if (open_the_file(f, name, mode) == NULL) {
280 Py_DECREF(f);
281 f = NULL;
282 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000284 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285}
286
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287void
Fred Drakefd99de62000-07-09 05:02:18 +0000288PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000289{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000290 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000291 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292 int type;
293 switch (bufsize) {
294 case 0:
295 type = _IONBF;
296 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000297#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000298 case 1:
299 type = _IOLBF;
300 bufsize = BUFSIZ;
301 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000302#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303 default:
304 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000305#ifndef HAVE_SETVBUF
306 bufsize = BUFSIZ;
307#endif
308 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000309 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000310 fflush(file->f_fp);
311 if (type == _IONBF) {
312 PyMem_Free(file->f_setbuf);
313 file->f_setbuf = NULL;
314 } else {
315 file->f_setbuf = PyMem_Realloc(file->f_setbuf, bufsize);
316 }
317#ifdef HAVE_SETVBUF
318 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000319#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000320 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000321#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000322 }
323}
324
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000325/* Set the encoding used to output Unicode strings.
326 Returh 1 on success, 0 on failure. */
327
328int
329PyFile_SetEncoding(PyObject *f, const char *enc)
330{
331 PyFileObject *file = (PyFileObject*)f;
332 PyObject *str = PyString_FromString(enc);
333 if (!str)
334 return 0;
335 Py_DECREF(file->f_encoding);
336 file->f_encoding = str;
337 return 1;
338}
339
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000341err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000342{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000344 return NULL;
345}
346
Thomas Woutersc45251a2006-02-12 11:53:32 +0000347/* Refuse regular file I/O if there's data in the iteration-buffer.
348 * Mixing them would cause data to arrive out of order, as the read*
349 * methods don't use the iteration buffer. */
350static PyObject *
351err_iterbuffered(void)
352{
353 PyErr_SetString(PyExc_ValueError,
354 "Mixing iteration and read methods would lose data");
355 return NULL;
356}
357
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000358static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000359
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360/* Methods */
361
362static void
Fred Drakefd99de62000-07-09 05:02:18 +0000363file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000365 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000366 if (f->weakreflist != NULL)
367 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000368 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000370 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000372 if (sts == EOF)
373#ifdef HAVE_STRERROR
374 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
375#else
376 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
377#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000378 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000379 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000380 Py_XDECREF(f->f_name);
381 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000382 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000383 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000384 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385}
386
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000388file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000390 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000391#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000392 PyObject *ret = NULL;
393 PyObject *name;
394 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
395 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
396 f->f_fp == NULL ? "closed" : "open",
397 PyString_AsString(name),
398 PyString_AsString(f->f_mode),
399 f);
400 Py_XDECREF(name);
401 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000402#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000403 } else {
404 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000405 f->f_fp == NULL ? "closed" : "open",
406 PyString_AsString(f->f_name),
407 PyString_AsString(f->f_mode),
408 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000409 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410}
411
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000413file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000415 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000417 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000419 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000420 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000421 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000422 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000423 f->f_fp = NULL;
424 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000425 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000426 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000427 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000428 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000429 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430 return PyInt_FromLong((long)sts);
431 Py_INCREF(Py_None);
432 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433}
434
Trent Mickf29f47b2000-08-11 19:02:59 +0000435
Guido van Rossumb8552162001-09-05 14:58:11 +0000436/* Our very own off_t-like type, 64-bit if possible */
437#if !defined(HAVE_LARGEFILE_SUPPORT)
438typedef off_t Py_off_t;
439#elif SIZEOF_OFF_T >= 8
440typedef off_t Py_off_t;
441#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000442typedef fpos_t Py_off_t;
443#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000444#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000445#endif
446
447
Trent Mickf29f47b2000-08-11 19:02:59 +0000448/* a portable fseek() function
449 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000450static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000451_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000452{
Guido van Rossumb8552162001-09-05 14:58:11 +0000453#if !defined(HAVE_LARGEFILE_SUPPORT)
454 return fseek(fp, offset, whence);
455#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000456 return fseeko(fp, offset, whence);
457#elif defined(HAVE_FSEEK64)
458 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000459#elif defined(__BEOS__)
460 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000461#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000462 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
463 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000464 fpos_t pos;
465 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000466 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000467#ifdef MS_WINDOWS
468 fflush(fp);
469 if (_lseeki64(fileno(fp), 0, 2) == -1)
470 return -1;
471#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000472 if (fseek(fp, 0, SEEK_END) != 0)
473 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000474#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000475 /* fall through */
476 case SEEK_CUR:
477 if (fgetpos(fp, &pos) != 0)
478 return -1;
479 offset += pos;
480 break;
481 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000482 }
483 return fsetpos(fp, &offset);
484#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000485#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000486#endif
487}
488
489
490/* a portable ftell() function
491 Return -1 on failure with errno set appropriately, current file
492 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000493static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000494_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000495{
Guido van Rossumb8552162001-09-05 14:58:11 +0000496#if !defined(HAVE_LARGEFILE_SUPPORT)
497 return ftell(fp);
498#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
499 return ftello(fp);
500#elif defined(HAVE_FTELL64)
501 return ftell64(fp);
502#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000503 fpos_t pos;
504 if (fgetpos(fp, &pos) != 0)
505 return -1;
506 return pos;
507#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000508#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000509#endif
510}
511
512
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000514file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000515{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000516 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000517 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000518 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000519 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000520
Guido van Rossumd7297e61992-07-06 14:19:26 +0000521 if (f->f_fp == NULL)
522 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000523 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000524 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000525 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000526 return NULL;
527#if !defined(HAVE_LARGEFILE_SUPPORT)
528 offset = PyInt_AsLong(offobj);
529#else
530 offset = PyLong_Check(offobj) ?
531 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
532#endif
533 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000534 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000535
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000537 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000538 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000539 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000540
Guido van Rossumff4949e1992-08-05 19:58:53 +0000541 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000543 clearerr(f->f_fp);
544 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000545 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000546 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547 Py_INCREF(Py_None);
548 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000549}
550
Trent Mickf29f47b2000-08-11 19:02:59 +0000551
Guido van Rossumd7047b31995-01-02 19:07:15 +0000552#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000554file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000555{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000556 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000557 PyObject *newsizeobj = NULL;
558 Py_off_t initialpos;
559 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000560
Guido van Rossumd7047b31995-01-02 19:07:15 +0000561 if (f->f_fp == NULL)
562 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000563 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000564 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000565
Tim Petersf1827cf2003-09-07 03:30:18 +0000566 /* Get current file position. If the file happens to be open for
567 * update and the last operation was an input operation, C doesn't
568 * define what the later fflush() will do, but we promise truncate()
569 * won't change the current position (and fflush() *does* change it
570 * then at least on Windows). The easiest thing is to capture
571 * current pos now and seek back to it at the end.
572 */
573 Py_BEGIN_ALLOW_THREADS
574 errno = 0;
575 initialpos = _portable_ftell(f->f_fp);
576 Py_END_ALLOW_THREADS
577 if (initialpos == -1)
578 goto onioerror;
579
Tim Petersfb05db22002-03-11 00:24:00 +0000580 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000581 * specified value.
582 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000583 if (newsizeobj != NULL) {
584#if !defined(HAVE_LARGEFILE_SUPPORT)
585 newsize = PyInt_AsLong(newsizeobj);
586#else
587 newsize = PyLong_Check(newsizeobj) ?
588 PyLong_AsLongLong(newsizeobj) :
589 PyInt_AsLong(newsizeobj);
590#endif
591 if (PyErr_Occurred())
592 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000593 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000594 else /* default to current position */
595 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000596
Tim Petersf1827cf2003-09-07 03:30:18 +0000597 /* Flush the stream. We're mixing stream-level I/O with lower-level
598 * I/O, and a flush may be necessary to synch both platform views
599 * of the current file state.
600 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000601 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000602 errno = 0;
603 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000604 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000605 if (ret != 0)
606 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000607
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000608#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000609 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000610 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000611 {
Tim Petersfb05db22002-03-11 00:24:00 +0000612 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000613
Tim Petersf1827cf2003-09-07 03:30:18 +0000614 /* Have to move current pos to desired endpoint on Windows. */
615 Py_BEGIN_ALLOW_THREADS
616 errno = 0;
617 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
618 Py_END_ALLOW_THREADS
619 if (ret)
620 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000621
Tim Peters8f01b682002-03-12 03:04:44 +0000622 /* Truncate. Note that this may grow the file! */
623 Py_BEGIN_ALLOW_THREADS
624 errno = 0;
625 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000626 ret = hFile == (HANDLE)-1;
627 if (ret == 0) {
628 ret = SetEndOfFile(hFile) == 0;
629 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000630 errno = EACCES;
631 }
632 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000633 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000634 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000635 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000636#else
637 Py_BEGIN_ALLOW_THREADS
638 errno = 0;
639 ret = ftruncate(fileno(f->f_fp), newsize);
640 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000641 if (ret != 0)
642 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000643#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000644
Tim Petersf1827cf2003-09-07 03:30:18 +0000645 /* Restore original file position. */
646 Py_BEGIN_ALLOW_THREADS
647 errno = 0;
648 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
649 Py_END_ALLOW_THREADS
650 if (ret)
651 goto onioerror;
652
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653 Py_INCREF(Py_None);
654 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000655
656onioerror:
657 PyErr_SetFromErrno(PyExc_IOError);
658 clearerr(f->f_fp);
659 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000660}
661#endif /* HAVE_FTRUNCATE */
662
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000664file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000665{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000666 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000667
Guido van Rossumd7297e61992-07-06 14:19:26 +0000668 if (f->f_fp == NULL)
669 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000670 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000671 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000672 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000674 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000676 clearerr(f->f_fp);
677 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000678 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000679 if (f->f_skipnextlf) {
680 int c;
681 c = GETC(f->f_fp);
682 if (c == '\n') {
683 pos++;
684 f->f_skipnextlf = 0;
685 } else if (c != EOF) ungetc(c, f->f_fp);
686 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000687#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000688 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000689#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000690 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000691#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000692}
693
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000695file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000696{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000697 if (f->f_fp == NULL)
698 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000699 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000700}
701
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000702static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000703file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000704{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000705 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000706
Guido van Rossumd7297e61992-07-06 14:19:26 +0000707 if (f->f_fp == NULL)
708 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000709 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000710 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000711 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000713 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000715 clearerr(f->f_fp);
716 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000717 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718 Py_INCREF(Py_None);
719 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000720}
721
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000722static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000723file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000724{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000725 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000726 if (f->f_fp == NULL)
727 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000729 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000730 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000731 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000732}
733
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000734
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000735#if BUFSIZ < 8192
736#define SMALLCHUNK 8192
737#else
738#define SMALLCHUNK BUFSIZ
739#endif
740
Guido van Rossum3c259041999-01-14 19:00:14 +0000741#if SIZEOF_INT < 4
742#define BIGCHUNK (512 * 32)
743#else
744#define BIGCHUNK (512 * 1024)
745#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000746
747static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000748new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000749{
750#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000751 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000752 struct stat st;
753 if (fstat(fileno(f->f_fp), &st) == 0) {
754 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000755 /* The following is not a bug: we really need to call lseek()
756 *and* ftell(). The reason is that some stdio libraries
757 mistakenly flush their buffer when ftell() is called and
758 the lseek() call it makes fails, thereby throwing away
759 data that cannot be recovered in any way. To avoid this,
760 we first test lseek(), and only call ftell() if lseek()
761 works. We can't use the lseek() value either, because we
762 need to take the amount of buffered data into account.
763 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000764 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000765 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000766 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000767 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000768 if (pos < 0)
769 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000770 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000771 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000772 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000773 }
774#endif
775 if (currentsize > SMALLCHUNK) {
776 /* Keep doubling until we reach BIGCHUNK;
777 then keep adding BIGCHUNK. */
778 if (currentsize <= BIGCHUNK)
779 return currentsize + currentsize;
780 else
781 return currentsize + BIGCHUNK;
782 }
783 return currentsize + SMALLCHUNK;
784}
785
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000786#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
787#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
788#else
789#ifdef EWOULDBLOCK
790#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
791#else
792#ifdef EAGAIN
793#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
794#else
795#define BLOCKED_ERRNO(x) 0
796#endif
797#endif
798#endif
799
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000800static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000801file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000802{
Guido van Rossum789a1611997-05-10 22:33:55 +0000803 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000804 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000805 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000806
Guido van Rossumd7297e61992-07-06 14:19:26 +0000807 if (f->f_fp == NULL)
808 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000809 /* refuse to mix with f.next() */
810 if (f->f_buf != NULL &&
811 (f->f_bufend - f->f_bufptr) > 0 &&
812 f->f_buf[0] != '\0')
813 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000814 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000815 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000816 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000817 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000818 else
819 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000820 if (buffersize > INT_MAX) {
821 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000822 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000823 return NULL;
824 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000825 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000826 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000827 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000828 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000829 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000830 Py_BEGIN_ALLOW_THREADS
831 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000832 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000833 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000834 Py_END_ALLOW_THREADS
835 if (chunksize == 0) {
836 if (!ferror(f->f_fp))
837 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000838 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000839 /* When in non-blocking mode, data shouldn't
840 * be discarded if a blocking signal was
841 * received. That will also happen if
842 * chunksize != 0, but bytesread < buffersize. */
843 if (bytesread > 0 && BLOCKED_ERRNO(errno))
844 break;
845 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000846 Py_DECREF(v);
847 return NULL;
848 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000849 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000850 if (bytesread < buffersize) {
851 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000852 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000853 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000854 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000855 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000856 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000857 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000858 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000859 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000860 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000861 }
862 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000863 if (bytesread != buffersize)
864 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000865 return v;
866}
867
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000868static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000869file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000870{
871 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000872 int ntodo;
873 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000874
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000875 if (f->f_fp == NULL)
876 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000877 /* refuse to mix with f.next() */
878 if (f->f_buf != NULL &&
879 (f->f_bufend - f->f_bufptr) > 0 &&
880 f->f_buf[0] != '\0')
881 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000882 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000883 return NULL;
884 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000885 while (ntodo > 0) {
886 Py_BEGIN_ALLOW_THREADS
887 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000888 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000889 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000890 Py_END_ALLOW_THREADS
891 if (nnow == 0) {
892 if (!ferror(f->f_fp))
893 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000894 PyErr_SetFromErrno(PyExc_IOError);
895 clearerr(f->f_fp);
896 return NULL;
897 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000898 ndone += nnow;
899 ntodo -= nnow;
900 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000901 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000902}
903
Tim Peters86821b22001-01-07 21:19:34 +0000904/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000905Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000906
907Under MSVC 6:
908
Tim Peters1c733232001-01-08 04:02:07 +0000909+ MS threadsafe getc is very slow (multiple layers of function calls before+
910 after each character, to lock+unlock the stream).
911+ The stream-locking functions are MS-internal -- can't access them from user
912 code.
913+ There's nothing Tim could find in the MS C or platform SDK libraries that
914 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000915+ MS fgets locks/unlocks only once per line; it's the only hook we have.
916
917So we use fgets for speed(!), despite that it's painful.
918
919MS realloc is also slow.
920
Tim Petersf29b64d2001-01-15 06:33:19 +0000921Reports from other platforms on this method vs getc_unlocked (which MS doesn't
922have):
923 Linux a wash
924 Solaris a wash
925 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000926
Tim Petersf29b64d2001-01-15 06:33:19 +0000927CAUTION: The C std isn't clear about this: in those cases where fgets
928writes something into the buffer, can it write into any position beyond the
929required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
930known on which it does; and it would be a strange way to code fgets. Still,
931getline_via_fgets may not work correctly if it does. The std test
932test_bufio.py should fail if platform fgets() routinely writes beyond the
933trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000934**************************************************************************/
935
Tim Petersf29b64d2001-01-15 06:33:19 +0000936/* Use this routine if told to, or by default on non-get_unlocked()
937 * platforms unless told not to. Yikes! Let's spell that out:
938 * On a platform with getc_unlocked():
939 * By default, use getc_unlocked().
940 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
941 * On a platform without getc_unlocked():
942 * By default, use fgets().
943 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
944 */
945#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
946#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000947#endif
948
Tim Petersf29b64d2001-01-15 06:33:19 +0000949#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
950#undef USE_FGETS_IN_GETLINE
951#endif
952
953#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000954static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000955getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000956{
Tim Peters15b83852001-01-08 00:53:12 +0000957/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000958 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
959 * to fill this much of the buffer with a known value in order to figure out
960 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
961 * than "most" lines, we waste time filling unused buffer slots. 100 is
962 * surely adequate for most peoples' email archives, chewing over source code,
963 * etc -- "regular old text files".
964 * MAXBUFSIZE is the maximum line length that lets us get away with the less
965 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
966 * cautions about boosting that. 300 was chosen because the worst real-life
967 * text-crunching job reported on Python-Dev was a mail-log crawler where over
968 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000969 */
Tim Peters142297a2001-01-15 10:36:56 +0000970#define INITBUFSIZE 100
971#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000972 char* p; /* temp */
973 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000974 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000975 char* pvfree; /* address of next free slot */
976 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000977 size_t nfree; /* # of free buffer slots; pvend-pvfree */
978 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000979 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000980
Tim Peters15b83852001-01-08 00:53:12 +0000981 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000982 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000983 */
Tim Peters142297a2001-01-15 10:36:56 +0000984 total_v_size = INITBUFSIZE; /* start small and pray */
985 pvfree = buf;
986 for (;;) {
987 Py_BEGIN_ALLOW_THREADS
988 pvend = buf + total_v_size;
989 nfree = pvend - pvfree;
990 memset(pvfree, '\n', nfree);
991 p = fgets(pvfree, nfree, fp);
992 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000993
Tim Peters142297a2001-01-15 10:36:56 +0000994 if (p == NULL) {
995 clearerr(fp);
996 if (PyErr_CheckSignals())
997 return NULL;
998 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000999 return v;
1000 }
Tim Peters142297a2001-01-15 10:36:56 +00001001 /* fgets read *something* */
1002 p = memchr(pvfree, '\n', nfree);
1003 if (p != NULL) {
1004 /* Did the \n come from fgets or from us?
1005 * Since fgets stops at the first \n, and then writes
1006 * \0, if it's from fgets a \0 must be next. But if
1007 * that's so, it could not have come from us, since
1008 * the \n's we filled the buffer with have only more
1009 * \n's to the right.
1010 */
1011 if (p+1 < pvend && *(p+1) == '\0') {
1012 /* It's from fgets: we win! In particular,
1013 * we haven't done any mallocs yet, and can
1014 * build the final result on the first try.
1015 */
1016 ++p; /* include \n from fgets */
1017 }
1018 else {
1019 /* Must be from us: fgets didn't fill the
1020 * buffer and didn't find a newline, so it
1021 * must be the last and newline-free line of
1022 * the file.
1023 */
1024 assert(p > pvfree && *(p-1) == '\0');
1025 --p; /* don't include \0 from fgets */
1026 }
1027 v = PyString_FromStringAndSize(buf, p - buf);
1028 return v;
1029 }
1030 /* yuck: fgets overwrote all the newlines, i.e. the entire
1031 * buffer. So this line isn't over yet, or maybe it is but
1032 * we're exactly at EOF. If we haven't already, try using the
1033 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001034 */
Tim Peters142297a2001-01-15 10:36:56 +00001035 assert(*(pvend-1) == '\0');
1036 if (pvfree == buf) {
1037 pvfree = pvend - 1; /* overwrite trailing null */
1038 total_v_size = MAXBUFSIZE;
1039 }
1040 else
1041 break;
Tim Peters86821b22001-01-07 21:19:34 +00001042 }
Tim Peters142297a2001-01-15 10:36:56 +00001043
1044 /* The stack buffer isn't big enough; malloc a string object and read
1045 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001046 */
Tim Petersddea2082002-03-23 10:03:50 +00001047 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001048 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001049 if (v == NULL)
1050 return v;
1051 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001052 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1053 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001054
1055 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001056 * after setting p one beyond the end of the line. The code here is
1057 * very much like the code above, except reads into v's buffer; see
1058 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001059 */
1060 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001061 Py_BEGIN_ALLOW_THREADS
1062 pvend = BUF(v) + total_v_size;
1063 nfree = pvend - pvfree;
1064 memset(pvfree, '\n', nfree);
1065 p = fgets(pvfree, nfree, fp);
1066 Py_END_ALLOW_THREADS
1067
1068 if (p == NULL) {
1069 clearerr(fp);
1070 if (PyErr_CheckSignals()) {
1071 Py_DECREF(v);
1072 return NULL;
1073 }
1074 p = pvfree;
1075 break;
1076 }
Tim Peters86821b22001-01-07 21:19:34 +00001077 p = memchr(pvfree, '\n', nfree);
1078 if (p != NULL) {
1079 if (p+1 < pvend && *(p+1) == '\0') {
1080 /* \n came from fgets */
1081 ++p;
1082 break;
1083 }
1084 /* \n came from us; last line of file, no newline */
1085 assert(p > pvfree && *(p-1) == '\0');
1086 --p;
1087 break;
1088 }
1089 /* expand buffer and try again */
1090 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001091 increment = total_v_size >> 2; /* mild exponential growth */
1092 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001093 if (total_v_size > INT_MAX) {
1094 PyErr_SetString(PyExc_OverflowError,
1095 "line is longer than a Python string can hold");
1096 Py_DECREF(v);
1097 return NULL;
1098 }
1099 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1100 return NULL;
1101 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001102 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001103 }
1104 if (BUF(v) + total_v_size != p)
1105 _PyString_Resize(&v, p - BUF(v));
1106 return v;
1107#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001108#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001109}
Tim Petersf29b64d2001-01-15 06:33:19 +00001110#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001111
Guido van Rossum0bd24411991-04-04 15:21:57 +00001112/* Internal routine to get a line.
1113 Size argument interpretation:
1114 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001115 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001116*/
1117
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001118static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001119get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001120{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001121 FILE *fp = f->f_fp;
1122 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001123 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001124 size_t total_v_size; /* total # of slots in buffer */
1125 size_t used_v_size; /* # used slots in buffer */
1126 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001127 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001128 int newlinetypes = f->f_newlinetypes;
1129 int skipnextlf = f->f_skipnextlf;
1130 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001131
Jack Jansen7b8c7542002-04-14 20:12:41 +00001132#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001133 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001134 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001135#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001136 total_v_size = n > 0 ? n : 100;
1137 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001138 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001139 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001140 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001141 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001142
Guido van Rossumce5ba841991-03-06 13:06:18 +00001143 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001144 Py_BEGIN_ALLOW_THREADS
1145 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001146 if (univ_newline) {
1147 c = 'x'; /* Shut up gcc warning */
1148 while ( buf != end && (c = GETC(fp)) != EOF ) {
1149 if (skipnextlf ) {
1150 skipnextlf = 0;
1151 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001152 /* Seeing a \n here with
1153 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001154 * saw a \r before.
1155 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001156 newlinetypes |= NEWLINE_CRLF;
1157 c = GETC(fp);
1158 if (c == EOF) break;
1159 } else {
1160 newlinetypes |= NEWLINE_CR;
1161 }
1162 }
1163 if (c == '\r') {
1164 skipnextlf = 1;
1165 c = '\n';
1166 } else if ( c == '\n')
1167 newlinetypes |= NEWLINE_LF;
1168 *buf++ = c;
1169 if (c == '\n') break;
1170 }
1171 if ( c == EOF && skipnextlf )
1172 newlinetypes |= NEWLINE_CR;
1173 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001174 while ((c = GETC(fp)) != EOF &&
1175 (*buf++ = c) != '\n' &&
1176 buf != end)
1177 ;
1178 FUNLOCKFILE(fp);
1179 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001180 f->f_newlinetypes = newlinetypes;
1181 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001182 if (c == '\n')
1183 break;
1184 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001185 if (ferror(fp)) {
1186 PyErr_SetFromErrno(PyExc_IOError);
1187 clearerr(fp);
1188 Py_DECREF(v);
1189 return NULL;
1190 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001191 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001192 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001193 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001194 return NULL;
1195 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001196 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001197 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001198 /* Must be because buf == end */
1199 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001200 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001201 used_v_size = total_v_size;
1202 increment = total_v_size >> 2; /* mild exponential growth */
1203 total_v_size += increment;
1204 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001205 PyErr_SetString(PyExc_OverflowError,
1206 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001207 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001208 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001209 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001210 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001211 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001212 buf = BUF(v) + used_v_size;
1213 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001214 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001215
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001216 used_v_size = buf - BUF(v);
1217 if (used_v_size != total_v_size)
1218 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001219 return v;
1220}
1221
Guido van Rossum0bd24411991-04-04 15:21:57 +00001222/* External C interface */
1223
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001224PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001225PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001226{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001227 PyObject *result;
1228
Guido van Rossum3165fe61992-09-25 21:59:05 +00001229 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001230 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001231 return NULL;
1232 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001233
1234 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001235 PyFileObject *fo = (PyFileObject *)f;
1236 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001237 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001238 /* refuse to mix with f.next() */
1239 if (fo->f_buf != NULL &&
1240 (fo->f_bufend - fo->f_bufptr) > 0 &&
1241 fo->f_buf[0] != '\0')
1242 return err_iterbuffered();
1243 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001244 }
1245 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001246 PyObject *reader;
1247 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001248
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001249 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001250 if (reader == NULL)
1251 return NULL;
1252 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001253 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001254 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001255 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001256 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001257 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001258 return NULL;
1259 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001260 result = PyEval_CallObject(reader, args);
1261 Py_DECREF(reader);
1262 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001263 if (result != NULL && !PyString_Check(result) &&
1264 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001266 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001267 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001268 "object.readline() returned non-string");
1269 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001270 }
1271
1272 if (n < 0 && result != NULL && PyString_Check(result)) {
1273 char *s = PyString_AS_STRING(result);
1274 int len = PyString_GET_SIZE(result);
1275 if (len == 0) {
1276 Py_DECREF(result);
1277 result = NULL;
1278 PyErr_SetString(PyExc_EOFError,
1279 "EOF when reading a line");
1280 }
1281 else if (s[len-1] == '\n') {
1282 if (result->ob_refcnt == 1)
1283 _PyString_Resize(&result, len-1);
1284 else {
1285 PyObject *v;
1286 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001287 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001288 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001289 }
1290 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001291 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001292#ifdef Py_USING_UNICODE
1293 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1294 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1295 int len = PyUnicode_GET_SIZE(result);
1296 if (len == 0) {
1297 Py_DECREF(result);
1298 result = NULL;
1299 PyErr_SetString(PyExc_EOFError,
1300 "EOF when reading a line");
1301 }
1302 else if (s[len-1] == '\n') {
1303 if (result->ob_refcnt == 1)
1304 PyUnicode_Resize(&result, len-1);
1305 else {
1306 PyObject *v;
1307 v = PyUnicode_FromUnicode(s, len-1);
1308 Py_DECREF(result);
1309 result = v;
1310 }
1311 }
1312 }
1313#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001314 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001315}
1316
1317/* Python method */
1318
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001319static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001320file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001321{
Guido van Rossum789a1611997-05-10 22:33:55 +00001322 int n = -1;
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();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001326 /* refuse to mix with f.next() */
1327 if (f->f_buf != NULL &&
1328 (f->f_bufend - f->f_bufptr) > 0 &&
1329 f->f_buf[0] != '\0')
1330 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001331 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001332 return NULL;
1333 if (n == 0)
1334 return PyString_FromString("");
1335 if (n < 0)
1336 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001337 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001338}
1339
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001340static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001341file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001342{
Guido van Rossum789a1611997-05-10 22:33:55 +00001343 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001344 PyObject *list;
1345 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001346 char small_buffer[SMALLCHUNK];
1347 char *buffer = small_buffer;
1348 size_t buffersize = SMALLCHUNK;
1349 PyObject *big_buffer = NULL;
1350 size_t nfilled = 0;
1351 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001352 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001353 char *p, *q, *end;
1354 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001355 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001356
Guido van Rossumd7297e61992-07-06 14:19:26 +00001357 if (f->f_fp == NULL)
1358 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001359 /* refuse to mix with f.next() */
1360 if (f->f_buf != NULL &&
1361 (f->f_bufend - f->f_bufptr) > 0 &&
1362 f->f_buf[0] != '\0')
1363 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001364 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001365 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001366 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001367 return NULL;
1368 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001369 if (shortread)
1370 nread = 0;
1371 else {
1372 Py_BEGIN_ALLOW_THREADS
1373 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001374 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001375 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001376 Py_END_ALLOW_THREADS
1377 shortread = (nread < buffersize-nfilled);
1378 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001379 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001380 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001381 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001382 break;
1383 PyErr_SetFromErrno(PyExc_IOError);
1384 clearerr(f->f_fp);
1385 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001386 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001387 list = NULL;
1388 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001389 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001390 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001391 p = memchr(buffer+nfilled, '\n', nread);
1392 if (p == NULL) {
1393 /* Need a larger buffer to fit this line */
1394 nfilled += nread;
1395 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001396 if (buffersize > INT_MAX) {
1397 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001398 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001399 goto error;
1400 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001401 if (big_buffer == NULL) {
1402 /* Create the big buffer */
1403 big_buffer = PyString_FromStringAndSize(
1404 NULL, buffersize);
1405 if (big_buffer == NULL)
1406 goto error;
1407 buffer = PyString_AS_STRING(big_buffer);
1408 memcpy(buffer, small_buffer, nfilled);
1409 }
1410 else {
1411 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001412 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1413 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001414 buffer = PyString_AS_STRING(big_buffer);
1415 }
1416 continue;
1417 }
1418 end = buffer+nfilled+nread;
1419 q = buffer;
1420 do {
1421 /* Process complete lines */
1422 p++;
1423 line = PyString_FromStringAndSize(q, p-q);
1424 if (line == NULL)
1425 goto error;
1426 err = PyList_Append(list, line);
1427 Py_DECREF(line);
1428 if (err != 0)
1429 goto error;
1430 q = p;
1431 p = memchr(q, '\n', end-q);
1432 } while (p != NULL);
1433 /* Move the remaining incomplete line to the start */
1434 nfilled = end-q;
1435 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001436 if (sizehint > 0)
1437 if (totalread >= (size_t)sizehint)
1438 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001439 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001440 if (nfilled != 0) {
1441 /* Partial last line */
1442 line = PyString_FromStringAndSize(buffer, nfilled);
1443 if (line == NULL)
1444 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001445 if (sizehint > 0) {
1446 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001447 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001448 if (rest == NULL) {
1449 Py_DECREF(line);
1450 goto error;
1451 }
1452 PyString_Concat(&line, rest);
1453 Py_DECREF(rest);
1454 if (line == NULL)
1455 goto error;
1456 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001457 err = PyList_Append(list, line);
1458 Py_DECREF(line);
1459 if (err != 0)
1460 goto error;
1461 }
1462 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001463 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001464 return list;
1465}
1466
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001467static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001468file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001469{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001470 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001471 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001472 if (f->f_fp == NULL)
1473 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001474 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001475 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001476 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001477 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001478 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001479 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001480 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001481 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001482 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001483 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001484 return NULL;
1485 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001486 Py_INCREF(Py_None);
1487 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001488}
1489
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001491file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001492{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001493#define CHUNKSIZE 1000
1494 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001495 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001496 PyObject *result;
1497 int i, j, index, len, nwritten, islist;
1498
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001499 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001500 if (f->f_fp == NULL)
1501 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001502
1503 result = NULL;
1504 list = NULL;
1505 islist = PyList_Check(seq);
1506 if (islist)
1507 it = NULL;
1508 else {
1509 it = PyObject_GetIter(seq);
1510 if (it == NULL) {
1511 PyErr_SetString(PyExc_TypeError,
1512 "writelines() requires an iterable argument");
1513 return NULL;
1514 }
1515 /* From here on, fail by going to error, to reclaim "it". */
1516 list = PyList_New(CHUNKSIZE);
1517 if (list == NULL)
1518 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001519 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001520
1521 /* Strategy: slurp CHUNKSIZE lines into a private list,
1522 checking that they are all strings, then write that list
1523 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001524 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001525 if (islist) {
1526 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001527 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001528 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001529 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001530 j = PyList_GET_SIZE(list);
1531 }
1532 else {
1533 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001534 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001535 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001536 if (PyErr_Occurred())
1537 goto error;
1538 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001540 PyList_SetItem(list, j, line);
1541 }
1542 }
1543 if (j == 0)
1544 break;
1545
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001546 /* Check that all entries are indeed strings. If not,
1547 apply the same rules as for file.write() and
1548 convert the results to strings. This is slow, but
1549 seems to be the only way since all conversion APIs
1550 could potentially execute Python code. */
1551 for (i = 0; i < j; i++) {
1552 PyObject *v = PyList_GET_ITEM(list, i);
1553 if (!PyString_Check(v)) {
1554 const char *buffer;
1555 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001556 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001557 PyObject_AsReadBuffer(v,
1558 (const void**)&buffer,
1559 &len)) ||
1560 PyObject_AsCharBuffer(v,
1561 &buffer,
1562 &len))) {
1563 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001564 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001565 goto error;
1566 }
1567 line = PyString_FromStringAndSize(buffer,
1568 len);
1569 if (line == NULL)
1570 goto error;
1571 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001572 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001573 }
1574 }
1575
1576 /* Since we are releasing the global lock, the
1577 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001578 Py_BEGIN_ALLOW_THREADS
1579 f->f_softspace = 0;
1580 errno = 0;
1581 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001582 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001583 len = PyString_GET_SIZE(line);
1584 nwritten = fwrite(PyString_AS_STRING(line),
1585 1, len, f->f_fp);
1586 if (nwritten != len) {
1587 Py_BLOCK_THREADS
1588 PyErr_SetFromErrno(PyExc_IOError);
1589 clearerr(f->f_fp);
1590 goto error;
1591 }
1592 }
1593 Py_END_ALLOW_THREADS
1594
1595 if (j < CHUNKSIZE)
1596 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001597 }
1598
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001599 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001600 result = Py_None;
1601 error:
1602 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001603 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001604 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001605#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001606}
1607
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001608static PyObject *
1609file_getiter(PyFileObject *f)
1610{
1611 if (f->f_fp == NULL)
1612 return err_closed();
1613 Py_INCREF(f);
1614 return (PyObject *)f;
1615}
1616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001617PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001618"readline([size]) -> next line from the file, as a string.\n"
1619"\n"
1620"Retain newline. A non-negative size argument limits the maximum\n"
1621"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001622"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001624PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001625"read([size]) -> read at most size bytes, returned as a string.\n"
1626"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001627"If the size argument is negative or omitted, read until EOF is reached.\n"
1628"Notice that when in non-blocking mode, less data than what was requested\n"
1629"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001631PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001632"write(str) -> None. Write string str to file.\n"
1633"\n"
1634"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001636
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001637PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001638"fileno() -> integer \"file descriptor\".\n"
1639"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001640"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001642PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001643"seek(offset[, whence]) -> None. Move to new file position.\n"
1644"\n"
1645"Argument offset is a byte count. Optional argument whence defaults to\n"
1646"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1647"(move relative to current position, positive or negative), and 2 (move\n"
1648"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001649"seeking beyond the end of a file). If the file is opened in text mode,\n"
1650"only offsets returned by tell() are legal. Use of other offsets causes\n"
1651"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001652"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001653"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001654
Guido van Rossumd7047b31995-01-02 19:07:15 +00001655#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001656PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001657"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1658"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001659"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001660#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001661
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001662PyDoc_STRVAR(tell_doc,
1663"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001665PyDoc_STRVAR(readinto_doc,
1666"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001668PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001669"readlines([size]) -> list of strings, each a line from the file.\n"
1670"\n"
1671"Call readline() repeatedly and return a list of the lines so read.\n"
1672"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001673"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001674
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001675PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001676"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001677"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001678"For backward compatibility. File objects now include the performance\n"
1679"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001681PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001682"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001683"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001684"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001685"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001687PyDoc_STRVAR(flush_doc,
1688"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001690PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001691"close() -> None or (perhaps) an integer. Close the file.\n"
1692"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001693"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001694"further I/O operations. close() may be called more than once without\n"
1695"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001696"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001698PyDoc_STRVAR(isatty_doc,
1699"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001700
1701static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001702 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1703 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1704 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1705 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1706 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001707#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001708 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001709#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001710 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1711 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1712 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1713 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1714 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1715 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1716 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1717 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1718 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001719};
1720
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001721#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001722
Guido van Rossum6f799372001-09-20 20:46:19 +00001723static PyMemberDef file_memberlist[] = {
1724 {"softspace", T_INT, OFF(f_softspace), 0,
1725 "flag indicating that a space needs to be printed; used by print"},
1726 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001727 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001728 {"name", T_OBJECT, OFF(f_name), RO,
1729 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001730 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1731 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001732 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001733 {NULL} /* Sentinel */
1734};
1735
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001736static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001738{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001739 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001740}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001741static PyObject *
1742get_newlines(PyFileObject *f, void *closure)
1743{
1744 switch (f->f_newlinetypes) {
1745 case NEWLINE_UNKNOWN:
1746 Py_INCREF(Py_None);
1747 return Py_None;
1748 case NEWLINE_CR:
1749 return PyString_FromString("\r");
1750 case NEWLINE_LF:
1751 return PyString_FromString("\n");
1752 case NEWLINE_CR|NEWLINE_LF:
1753 return Py_BuildValue("(ss)", "\r", "\n");
1754 case NEWLINE_CRLF:
1755 return PyString_FromString("\r\n");
1756 case NEWLINE_CR|NEWLINE_CRLF:
1757 return Py_BuildValue("(ss)", "\r", "\r\n");
1758 case NEWLINE_LF|NEWLINE_CRLF:
1759 return Py_BuildValue("(ss)", "\n", "\r\n");
1760 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1761 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1762 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001763 PyErr_Format(PyExc_SystemError,
1764 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001765 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001766 return NULL;
1767 }
1768}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001769
Guido van Rossum32d34c82001-09-20 21:45:26 +00001770static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001771 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001772 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001773 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774 {0},
1775};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001776
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001777static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001778drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001779{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001780 if (f->f_buf != NULL) {
1781 PyMem_Free(f->f_buf);
1782 f->f_buf = NULL;
1783 }
Guido van Rossum65967252001-04-21 13:20:18 +00001784}
1785
Tim Petersf1827cf2003-09-07 03:30:18 +00001786/* Make sure that file has a readahead buffer with at least one byte
1787 (unless at EOF) and no more than bufsize. Returns negative value on
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001788 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001789static int
1790readahead(PyFileObject *f, int bufsize)
1791{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001792 int chunksize;
1793
1794 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001795 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001796 return 0;
1797 else
1798 drop_readahead(f);
1799 }
1800 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1801 return -1;
1802 }
1803 Py_BEGIN_ALLOW_THREADS
1804 errno = 0;
1805 chunksize = Py_UniversalNewlineFread(
1806 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1807 Py_END_ALLOW_THREADS
1808 if (chunksize == 0) {
1809 if (ferror(f->f_fp)) {
1810 PyErr_SetFromErrno(PyExc_IOError);
1811 clearerr(f->f_fp);
1812 drop_readahead(f);
1813 return -1;
1814 }
1815 }
1816 f->f_bufptr = f->f_buf;
1817 f->f_bufend = f->f_buf + chunksize;
1818 return 0;
1819}
1820
1821/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001822 uninitialized bytes followed by the remainder of the line. Don't be
1823 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001824 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1825
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001826static PyStringObject *
1827readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1828{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001829 PyStringObject* s;
1830 char *bufptr;
1831 char *buf;
1832 int len;
1833
1834 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001835 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001836 return NULL;
1837
1838 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001839 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001840 return (PyStringObject *)
1841 PyString_FromStringAndSize(NULL, skip);
1842 bufptr = memchr(f->f_bufptr, '\n', len);
1843 if (bufptr != NULL) {
1844 bufptr++; /* Count the '\n' */
1845 len = bufptr - f->f_bufptr;
1846 s = (PyStringObject *)
1847 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001848 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001849 return NULL;
1850 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1851 f->f_bufptr = bufptr;
1852 if (bufptr == f->f_bufend)
1853 drop_readahead(f);
1854 } else {
1855 bufptr = f->f_bufptr;
1856 buf = f->f_buf;
1857 f->f_buf = NULL; /* Force new readahead buffer */
1858 s = readahead_get_line_skip(
1859 f, skip+len, bufsize + (bufsize>>2) );
1860 if (s == NULL) {
1861 PyMem_Free(buf);
1862 return NULL;
1863 }
1864 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1865 PyMem_Free(buf);
1866 }
1867 return s;
1868}
1869
1870/* A larger buffer size may actually decrease performance. */
1871#define READAHEAD_BUFSIZE 8192
1872
1873static PyObject *
1874file_iternext(PyFileObject *f)
1875{
1876 PyStringObject* l;
1877
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001878 if (f->f_fp == NULL)
1879 return err_closed();
1880
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001881 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1882 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1883 Py_XDECREF(l);
1884 return NULL;
1885 }
1886 return (PyObject *)l;
1887}
1888
1889
Tim Peters59c9a642001-09-13 05:38:56 +00001890static PyObject *
1891file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1892{
Tim Peters44410012001-09-14 03:26:08 +00001893 PyObject *self;
1894 static PyObject *not_yet_string;
1895
1896 assert(type != NULL && type->tp_alloc != NULL);
1897
1898 if (not_yet_string == NULL) {
1899 not_yet_string = PyString_FromString("<uninitialized file>");
1900 if (not_yet_string == NULL)
1901 return NULL;
1902 }
1903
1904 self = type->tp_alloc(type, 0);
1905 if (self != NULL) {
1906 /* Always fill in the name and mode, so that nobody else
1907 needs to special-case NULLs there. */
1908 Py_INCREF(not_yet_string);
1909 ((PyFileObject *)self)->f_name = not_yet_string;
1910 Py_INCREF(not_yet_string);
1911 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001912 Py_INCREF(Py_None);
1913 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001914 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001915 }
1916 return self;
1917}
1918
1919static int
1920file_init(PyObject *self, PyObject *args, PyObject *kwds)
1921{
1922 PyFileObject *foself = (PyFileObject *)self;
1923 int ret = 0;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001924 static const char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001925 char *name = NULL;
1926 char *mode = "r";
1927 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001928 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001929
1930 assert(PyFile_Check(self));
1931 if (foself->f_fp != NULL) {
1932 /* Have to close the existing file first. */
1933 PyObject *closeresult = file_close(foself);
1934 if (closeresult == NULL)
1935 return -1;
1936 Py_DECREF(closeresult);
1937 }
Tim Peters59c9a642001-09-13 05:38:56 +00001938
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001939#ifdef Py_WIN_WIDE_FILENAMES
1940 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1941 PyObject *po;
1942 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1943 kwlist, &po, &mode, &bufsize)) {
1944 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001945 if (fill_file_fields(foself, NULL, po, mode,
1946 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001947 goto Error;
1948 } else {
1949 /* Drop the argument parsing error as narrow
1950 strings are also valid. */
1951 PyErr_Clear();
1952 }
1953 }
1954#endif
1955
1956 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001957 PyObject *o_name;
1958
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001959 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1960 Py_FileSystemDefaultEncoding,
1961 &name,
1962 &mode, &bufsize))
1963 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001964
1965 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001966 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1967 kwlist, &o_name, &mode,
1968 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001969 return -1;
1970
1971 if (fill_file_fields(foself, NULL, o_name, mode,
1972 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001973 goto Error;
1974 }
Tim Peters44410012001-09-14 03:26:08 +00001975 if (open_the_file(foself, name, mode) == NULL)
1976 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001977 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001978 PyFile_SetBufSize(self, bufsize);
1979 goto Done;
1980
1981Error:
1982 ret = -1;
1983 /* fall through */
1984Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001985 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001986 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001987}
1988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001989PyDoc_VAR(file_doc) =
1990PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001991"file(name[, mode[, buffering]]) -> file object\n"
1992"\n"
1993"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1994"writing or appending. The file will be created if it doesn't exist\n"
1995"when opened for writing or appending; it will be truncated when\n"
1996"opened for writing. Add a 'b' to the mode for binary files.\n"
1997"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1998"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001999"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002000)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002001PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002002"Add a 'U' to mode to open the file for input with universal newline\n"
2003"support. Any line ending in the input file will be seen as a '\\n'\n"
2004"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2005"the value for this attribute is one of None (no newline read yet),\n"
2006"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2007"\n"
2008"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002009)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002010PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002011"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002012"Note: open() is an alias for file()."
2013);
Tim Peters59c9a642001-09-13 05:38:56 +00002014
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002015PyTypeObject PyFile_Type = {
2016 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002017 0,
2018 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002020 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002021 (destructor)file_dealloc, /* tp_dealloc */
2022 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023 0, /* tp_getattr */
2024 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002025 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002027 0, /* tp_as_number */
2028 0, /* tp_as_sequence */
2029 0, /* tp_as_mapping */
2030 0, /* tp_hash */
2031 0, /* tp_call */
2032 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002034 /* softspace is writable: we must supply tp_setattro */
2035 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002036 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002037 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002038 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 0, /* tp_traverse */
2040 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002041 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002042 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002043 (getiterfunc)file_getiter, /* tp_iter */
2044 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 file_methods, /* tp_methods */
2046 file_memberlist, /* tp_members */
2047 file_getsetlist, /* tp_getset */
2048 0, /* tp_base */
2049 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002050 0, /* tp_descr_get */
2051 0, /* tp_descr_set */
2052 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00002053 (initproc)file_init, /* tp_init */
2054 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002055 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002056 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002057};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002058
2059/* Interface for the 'soft space' between print items. */
2060
2061int
Fred Drakefd99de62000-07-09 05:02:18 +00002062PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002063{
2064 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002065 if (f == NULL) {
2066 /* Do nothing */
2067 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068 else if (PyFile_Check(f)) {
2069 oldflag = ((PyFileObject *)f)->f_softspace;
2070 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002071 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002072 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073 PyObject *v;
2074 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002075 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002076 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002077 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002078 if (PyInt_Check(v))
2079 oldflag = PyInt_AsLong(v);
2080 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002081 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002083 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002084 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002085 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002086 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2087 PyErr_Clear();
2088 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002089 }
2090 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00002091 return oldflag;
2092}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002093
2094/* Interfaces to write objects/strings to file-like objects */
2095
2096int
Fred Drakefd99de62000-07-09 05:02:18 +00002097PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002098{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002100 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002101 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002102 return -1;
2103 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002104 else if (PyFile_Check(f)) {
2105 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002106#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002107 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2108 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002109#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002110 if (fp == NULL) {
2111 err_closed();
2112 return -1;
2113 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002114#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002115 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002116 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002117 char *cenc = PyString_AS_STRING(enc);
2118 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2119 if (value == NULL)
2120 return -1;
2121 } else {
2122 value = v;
2123 Py_INCREF(value);
2124 }
2125 result = PyObject_Print(value, fp, flags);
2126 Py_DECREF(value);
2127 return result;
2128#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002129 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002130#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002131 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002132 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002133 if (writer == NULL)
2134 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002135 if (flags & Py_PRINT_RAW) {
2136 if (PyUnicode_Check(v)) {
2137 value = v;
2138 Py_INCREF(value);
2139 } else
2140 value = PyObject_Str(v);
2141 }
2142 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002143 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002144 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002145 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002146 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002147 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002148 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002149 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150 Py_DECREF(value);
2151 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002152 return -1;
2153 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002154 result = PyEval_CallObject(writer, args);
2155 Py_DECREF(args);
2156 Py_DECREF(value);
2157 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002158 if (result == NULL)
2159 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002160 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002161 return 0;
2162}
2163
Guido van Rossum27a60b11997-05-22 22:25:11 +00002164int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002165PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002166{
2167 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002168 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002169 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002170 PyErr_SetString(PyExc_SystemError,
2171 "null file for PyFile_WriteString");
2172 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002173 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002174 else if (PyFile_Check(f)) {
2175 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002176 if (fp == NULL) {
2177 err_closed();
2178 return -1;
2179 }
2180 fputs(s, fp);
2181 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002182 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002183 else if (!PyErr_Occurred()) {
2184 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002185 int err;
2186 if (v == NULL)
2187 return -1;
2188 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2189 Py_DECREF(v);
2190 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002191 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002192 else
2193 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002194}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002195
2196/* Try to get a file-descriptor from a Python object. If the object
2197 is an integer or long integer, its value is returned. If not, the
2198 object's fileno() method is called if it exists; the method must return
2199 an integer or long integer, which is returned as the file descriptor value.
2200 -1 is returned on failure.
2201*/
2202
2203int PyObject_AsFileDescriptor(PyObject *o)
2204{
2205 int fd;
2206 PyObject *meth;
2207
2208 if (PyInt_Check(o)) {
2209 fd = PyInt_AsLong(o);
2210 }
2211 else if (PyLong_Check(o)) {
2212 fd = PyLong_AsLong(o);
2213 }
2214 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2215 {
2216 PyObject *fno = PyEval_CallObject(meth, NULL);
2217 Py_DECREF(meth);
2218 if (fno == NULL)
2219 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002220
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002221 if (PyInt_Check(fno)) {
2222 fd = PyInt_AsLong(fno);
2223 Py_DECREF(fno);
2224 }
2225 else if (PyLong_Check(fno)) {
2226 fd = PyLong_AsLong(fno);
2227 Py_DECREF(fno);
2228 }
2229 else {
2230 PyErr_SetString(PyExc_TypeError,
2231 "fileno() returned a non-integer");
2232 Py_DECREF(fno);
2233 return -1;
2234 }
2235 }
2236 else {
2237 PyErr_SetString(PyExc_TypeError,
2238 "argument must be an int, or have a fileno() method.");
2239 return -1;
2240 }
2241
2242 if (fd < 0) {
2243 PyErr_Format(PyExc_ValueError,
2244 "file descriptor cannot be a negative integer (%i)",
2245 fd);
2246 return -1;
2247 }
2248 return fd;
2249}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002250
Jack Jansen7b8c7542002-04-14 20:12:41 +00002251/* From here on we need access to the real fgets and fread */
2252#undef fgets
2253#undef fread
2254
2255/*
2256** Py_UniversalNewlineFgets is an fgets variation that understands
2257** all of \r, \n and \r\n conventions.
2258** The stream should be opened in binary mode.
2259** If fobj is NULL the routine always does newline conversion, and
2260** it may peek one char ahead to gobble the second char in \r\n.
2261** If fobj is non-NULL it must be a PyFileObject. In this case there
2262** is no readahead but in stead a flag is used to skip a following
2263** \n on the next read. Also, if the file is open in binary mode
2264** the whole conversion is skipped. Finally, the routine keeps track of
2265** the different types of newlines seen.
2266** Note that we need no error handling: fgets() treats error and eof
2267** identically.
2268*/
2269char *
2270Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2271{
2272 char *p = buf;
2273 int c;
2274 int newlinetypes = 0;
2275 int skipnextlf = 0;
2276 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002277
Jack Jansen7b8c7542002-04-14 20:12:41 +00002278 if (fobj) {
2279 if (!PyFile_Check(fobj)) {
2280 errno = ENXIO; /* What can you do... */
2281 return NULL;
2282 }
2283 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2284 if ( !univ_newline )
2285 return fgets(buf, n, stream);
2286 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2287 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2288 }
2289 FLOCKFILE(stream);
2290 c = 'x'; /* Shut up gcc warning */
2291 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2292 if (skipnextlf ) {
2293 skipnextlf = 0;
2294 if (c == '\n') {
2295 /* Seeing a \n here with skipnextlf true
2296 ** means we saw a \r before.
2297 */
2298 newlinetypes |= NEWLINE_CRLF;
2299 c = GETC(stream);
2300 if (c == EOF) break;
2301 } else {
2302 /*
2303 ** Note that c == EOF also brings us here,
2304 ** so we're okay if the last char in the file
2305 ** is a CR.
2306 */
2307 newlinetypes |= NEWLINE_CR;
2308 }
2309 }
2310 if (c == '\r') {
2311 /* A \r is translated into a \n, and we skip
2312 ** an adjacent \n, if any. We don't set the
2313 ** newlinetypes flag until we've seen the next char.
2314 */
2315 skipnextlf = 1;
2316 c = '\n';
2317 } else if ( c == '\n') {
2318 newlinetypes |= NEWLINE_LF;
2319 }
2320 *p++ = c;
2321 if (c == '\n') break;
2322 }
2323 if ( c == EOF && skipnextlf )
2324 newlinetypes |= NEWLINE_CR;
2325 FUNLOCKFILE(stream);
2326 *p = '\0';
2327 if (fobj) {
2328 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2329 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2330 } else if ( skipnextlf ) {
2331 /* If we have no file object we cannot save the
2332 ** skipnextlf flag. We have to readahead, which
2333 ** will cause a pause if we're reading from an
2334 ** interactive stream, but that is very unlikely
2335 ** unless we're doing something silly like
2336 ** execfile("/dev/tty").
2337 */
2338 c = GETC(stream);
2339 if ( c != '\n' )
2340 ungetc(c, stream);
2341 }
2342 if (p == buf)
2343 return NULL;
2344 return buf;
2345}
2346
2347/*
2348** Py_UniversalNewlineFread is an fread variation that understands
2349** all of \r, \n and \r\n conventions.
2350** The stream should be opened in binary mode.
2351** fobj must be a PyFileObject. In this case there
2352** is no readahead but in stead a flag is used to skip a following
2353** \n on the next read. Also, if the file is open in binary mode
2354** the whole conversion is skipped. Finally, the routine keeps track of
2355** the different types of newlines seen.
2356*/
2357size_t
Tim Peters058b1412002-04-21 07:29:14 +00002358Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002359 FILE *stream, PyObject *fobj)
2360{
Tim Peters058b1412002-04-21 07:29:14 +00002361 char *dst = buf;
2362 PyFileObject *f = (PyFileObject *)fobj;
2363 int newlinetypes, skipnextlf;
2364
2365 assert(buf != NULL);
2366 assert(stream != NULL);
2367
Jack Jansen7b8c7542002-04-14 20:12:41 +00002368 if (!fobj || !PyFile_Check(fobj)) {
2369 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002370 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002371 }
Tim Peters058b1412002-04-21 07:29:14 +00002372 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002373 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002374 newlinetypes = f->f_newlinetypes;
2375 skipnextlf = f->f_skipnextlf;
2376 /* Invariant: n is the number of bytes remaining to be filled
2377 * in the buffer.
2378 */
2379 while (n) {
2380 size_t nread;
2381 int shortread;
2382 char *src = dst;
2383
2384 nread = fread(dst, 1, n, stream);
2385 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002386 if (nread == 0)
2387 break;
2388
Tim Peterse1682a82002-04-21 18:15:20 +00002389 n -= nread; /* assuming 1 byte out for each in; will adjust */
2390 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002391 while (nread--) {
2392 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002393 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002394 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002395 *dst++ = '\n';
2396 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002397 }
2398 else if (skipnextlf && c == '\n') {
2399 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002400 skipnextlf = 0;
2401 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002402 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002403 }
2404 else {
2405 /* Normal char to be stored in buffer. Also
2406 * update the newlinetypes flag if either this
2407 * is an LF or the previous char was a CR.
2408 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002409 if (c == '\n')
2410 newlinetypes |= NEWLINE_LF;
2411 else if (skipnextlf)
2412 newlinetypes |= NEWLINE_CR;
2413 *dst++ = c;
2414 skipnextlf = 0;
2415 }
2416 }
Tim Peters058b1412002-04-21 07:29:14 +00002417 if (shortread) {
2418 /* If this is EOF, update type flags. */
2419 if (skipnextlf && feof(stream))
2420 newlinetypes |= NEWLINE_CR;
2421 break;
2422 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002423 }
Tim Peters058b1412002-04-21 07:29:14 +00002424 f->f_newlinetypes = newlinetypes;
2425 f->f_skipnextlf = skipnextlf;
2426 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002427}