blob: d61e6a0bebea499469134f9c9d49912f48160a8b [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Mark Hammondc2e85bd2002-10-03 05:10:39 +000019#ifdef _MSC_VER
20/* Need GetVersion to see if on NT so safe to use _wfopen */
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#endif /* _MSC_VER */
24
Andrew MacIntyrec4874392002-02-26 11:36:35 +000025#if defined(PYOS_OS2) && defined(PYCC_GCC)
26#include <io.h>
27#endif
28
Guido van Rossumc0b618a1997-05-02 03:12:38 +000029#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000030
Guido van Rossumff7e83d1999-08-27 20:39:37 +000031#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000032#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000033#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Jack Jansen7b8c7542002-04-14 20:12:41 +000035#ifdef HAVE_GETC_UNLOCKED
36#define GETC(f) getc_unlocked(f)
37#define FLOCKFILE(f) flockfile(f)
38#define FUNLOCKFILE(f) funlockfile(f)
39#else
40#define GETC(f) getc(f)
41#define FLOCKFILE(f)
42#define FUNLOCKFILE(f)
43#endif
44
Jack Jansen7b8c7542002-04-14 20:12:41 +000045/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000050
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000051/*
52 * These macros release the GIL while preventing the f_close() function being
53 * called in the interval between them. For that purpose, a running total of
54 * the number of currently running unlocked code sections is kept in
55 * the unlocked_count field of the PyFileObject. The close() method raises
56 * an IOError if that field is non-zero. See issue #815646, #595601.
57 */
58
59#define FILE_BEGIN_ALLOW_THREADS(fobj) \
60{ \
61 fobj->unlocked_count++; \
62 Py_BEGIN_ALLOW_THREADS
63
64#define FILE_END_ALLOW_THREADS(fobj) \
65 Py_END_ALLOW_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0); \
68}
69
70#define FILE_ABORT_ALLOW_THREADS(fobj) \
71 Py_BLOCK_THREADS \
72 fobj->unlocked_count--; \
73 assert(fobj->unlocked_count >= 0);
74
Anthony Baxterac6bd462006-04-13 02:06:09 +000075#ifdef __cplusplus
76extern "C" {
77#endif
78
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000080PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000081{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000082 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000084 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086}
87
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000088void PyFile_IncUseCount(PyFileObject *fobj)
89{
90 fobj->unlocked_count++;
91}
92
93void PyFile_DecUseCount(PyFileObject *fobj)
94{
95 fobj->unlocked_count--;
96 assert(fobj->unlocked_count >= 0);
97}
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000100PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000103 return NULL;
104 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000106}
107
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000108/* This is a safe wrapper around PyObject_Print to print to the FILE
109 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
110 about PyFileObject. */
111static int
112file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
113{
114 int result;
115 PyFile_IncUseCount(f);
116 result = PyObject_Print(op, f->f_fp, flags);
117 PyFile_DecUseCount(f);
118 return result;
119}
120
Neil Schemenauered19b882002-03-23 02:06:50 +0000121/* On Unix, fopen will succeed for directories.
122 In Python, there should be no file objects referring to
123 directories, so we need a check. */
124
125static PyFileObject*
126dircheck(PyFileObject* f)
127{
128#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
129 struct stat buf;
130 if (f->f_fp == NULL)
131 return f;
132 if (fstat(fileno(f->f_fp), &buf) == 0 &&
133 S_ISDIR(buf.st_mode)) {
Neil Schemenauered19b882002-03-23 02:06:50 +0000134 char *msg = strerror(EISDIR);
Tim Petersf1827cf2003-09-07 03:30:18 +0000135 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +0000136 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +0000137 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000138 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000139 return NULL;
140 }
141#endif
142 return f;
143}
144
Tim Peters59c9a642001-09-13 05:38:56 +0000145
146static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000147fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
148 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000150 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000151 assert(f != NULL);
152 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000153 assert(f->f_fp == NULL);
154
155 Py_DECREF(f->f_name);
156 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000157 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000158
Neal Norwitzb337bb52006-07-17 00:55:45 +0000159 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000160 f->f_name = name;
161
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000163
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000164 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000165 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000166 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000167 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000168 f->f_univ_newline = (strchr(mode, 'U') != NULL);
169 f->f_newlinetypes = NEWLINE_UNKNOWN;
170 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000171 Py_INCREF(Py_None);
172 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000173
Neal Norwitzb337bb52006-07-17 00:55:45 +0000174 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000177 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179}
180
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000181/* check for known incorrect mode strings - problem is, platforms are
182 free to accept any mode characters they like and are supposed to
183 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000184 universal newline support is expressly forbidden by PEP 278.
185 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000186 won't know what it is. Non-zero return signals an exception */
187int
188_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000189{
Georg Brandl7b90e162006-05-18 07:01:27 +0000190 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000191 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000192
Georg Brandl7b90e162006-05-18 07:01:27 +0000193 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000194 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000195 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000196 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000197
Georg Brandl7b90e162006-05-18 07:01:27 +0000198 upos = strchr(mode, 'U');
199 if (upos) {
200 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000201
Georg Brandl7b90e162006-05-18 07:01:27 +0000202 if (mode[0] == 'w' || mode[0] == 'a') {
203 PyErr_Format(PyExc_ValueError, "universal newline "
204 "mode can only be used with modes "
205 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000206 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000207 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000208
209 if (mode[0] != 'r') {
210 memmove(mode+1, mode, strlen(mode)+1);
211 mode[0] = 'r';
212 }
213
214 if (!strchr(mode, 'b')) {
215 memmove(mode+2, mode+1, strlen(mode));
216 mode[1] = 'b';
217 }
218 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
219 PyErr_Format(PyExc_ValueError, "mode string must begin with "
220 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000221 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000222 }
223
224 return 0;
225}
226
Tim Peters59c9a642001-09-13 05:38:56 +0000227static PyObject *
228open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Georg Brandl7b90e162006-05-18 07:01:27 +0000230 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000231 assert(f != NULL);
232 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000233#ifdef MS_WINDOWS
234 /* windows ignores the passed name in order to support Unicode */
235 assert(f->f_name != NULL);
236#else
Tim Peters59c9a642001-09-13 05:38:56 +0000237 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000238#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000239 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000240 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000241
Georg Brandl7b90e162006-05-18 07:01:27 +0000242 /* probably need to replace 'U' by 'rb' */
243 newmode = PyMem_MALLOC(strlen(mode) + 3);
244 if (!newmode) {
245 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000246 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000247 }
248 strcpy(newmode, mode);
249
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000250 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000251 f = NULL;
252 goto cleanup;
253 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000254
Tim Peters8fa45672001-09-13 21:01:29 +0000255 /* rexec.py can't stop a user from getting the file() constructor --
256 all they have to do is get *any* file object f, and then do
257 type(f). Here we prevent them from doing damage with it. */
258 if (PyEval_GetRestricted()) {
259 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000260 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000261 f = NULL;
262 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000263 }
Tim Petersa27a1502001-11-09 20:59:14 +0000264 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000265
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000266#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000267 if (PyUnicode_Check(f->f_name)) {
268 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000269 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000270 if (f->f_name && wmode) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000271 FILE_BEGIN_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000272 /* PyUnicode_AS_UNICODE OK without thread
273 lock as it is a simple dereference. */
274 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
275 PyUnicode_AS_UNICODE(wmode));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000276 FILE_END_ALLOW_THREADS(f)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000277 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000278 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000279 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000280#endif
281 if (NULL == f->f_fp && NULL != name) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000282 FILE_BEGIN_ALLOW_THREADS(f)
Georg Brandl7b90e162006-05-18 07:01:27 +0000283 f->f_fp = fopen(name, newmode);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000284 FILE_END_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000285 }
286
Guido van Rossuma08095a1991-02-13 23:25:27 +0000287 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000288#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000289 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
290 * across all Windows flavors. When it sets EINVAL varies
291 * across Windows flavors, the exact conditions aren't
292 * documented, and the answer lies in the OS's implementation
293 * of Win32's CreateFile function (whose source is secret).
294 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000295 * Starting with Visual Studio .NET 2005, EINVAL is correctly
296 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000297 */
298 if (errno == 0) /* bad mode string */
299 errno = EINVAL;
300 else if (errno == EINVAL) /* unknown, but not a mode string */
301 errno = ENOENT;
302#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000303 /* EINVAL is returned when an invalid filename or
304 * an invalid mode is supplied. */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000305 if (errno == EINVAL)
Gregory P. Smith887290d2008-03-18 00:20:01 +0000306 PyErr_Format(PyExc_IOError,
307 "invalid filename: %s or mode: %s",
308 name, mode);
Jeremy Hylton41c83212001-11-09 16:17:24 +0000309 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000310 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000311 f = NULL;
312 }
Tim Peters2ea91112002-04-08 04:13:12 +0000313 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000314 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000315
316cleanup:
317 PyMem_FREE(newmode);
318
Tim Peters59c9a642001-09-13 05:38:56 +0000319 return (PyObject *)f;
320}
321
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000322static PyObject *
323close_the_file(PyFileObject *f)
324{
325 int sts = 0;
326 int (*local_close)(FILE *);
327 FILE *local_fp = f->f_fp;
328 if (local_fp != NULL) {
329 local_close = f->f_close;
330 if (local_close != NULL && f->unlocked_count > 0) {
331 if (f->ob_refcnt > 0) {
332 PyErr_SetString(PyExc_IOError,
333 "close() called during concurrent "
334 "operation on the same file object.");
335 } else {
336 /* This should not happen unless someone is
337 * carelessly playing with the PyFileObject
338 * struct fields and/or its associated FILE
339 * pointer. */
340 PyErr_SetString(PyExc_SystemError,
341 "PyFileObject locking error in "
342 "destructor (refcnt <= 0 at close).");
343 }
344 return NULL;
345 }
346 /* NULL out the FILE pointer before releasing the GIL, because
347 * it will not be valid anymore after the close() function is
348 * called. */
349 f->f_fp = NULL;
350 if (local_close != NULL) {
351 Py_BEGIN_ALLOW_THREADS
352 errno = 0;
353 sts = (*local_close)(local_fp);
354 Py_END_ALLOW_THREADS
355 if (sts == EOF)
356 return PyErr_SetFromErrno(PyExc_IOError);
357 if (sts != 0)
358 return PyInt_FromLong((long)sts);
359 }
360 }
361 Py_RETURN_NONE;
362}
363
Tim Peters59c9a642001-09-13 05:38:56 +0000364PyObject *
365PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
366{
Tim Peters44410012001-09-14 03:26:08 +0000367 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
368 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000369 if (f != NULL) {
Neal Norwitzb337bb52006-07-17 00:55:45 +0000370 PyObject *o_name = PyString_FromString(name);
371 if (o_name == NULL)
372 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000373 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000374 Py_DECREF(f);
375 f = NULL;
376 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000377 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000378 }
379 return (PyObject *) f;
380}
381
382PyObject *
383PyFile_FromString(char *name, char *mode)
384{
385 extern int fclose(FILE *);
386 PyFileObject *f;
387
388 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
389 if (f != NULL) {
390 if (open_the_file(f, name, mode) == NULL) {
391 Py_DECREF(f);
392 f = NULL;
393 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Guido van Rossumb6775db1994-08-01 11:34:53 +0000398void
Fred Drakefd99de62000-07-09 05:02:18 +0000399PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000400{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000401 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000402 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000403 int type;
404 switch (bufsize) {
405 case 0:
406 type = _IONBF;
407 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000408#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000409 case 1:
410 type = _IOLBF;
411 bufsize = BUFSIZ;
412 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000413#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000414 default:
415 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000416#ifndef HAVE_SETVBUF
417 bufsize = BUFSIZ;
418#endif
419 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000420 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000421 fflush(file->f_fp);
422 if (type == _IONBF) {
423 PyMem_Free(file->f_setbuf);
424 file->f_setbuf = NULL;
425 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000426 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
427 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000428 }
429#ifdef HAVE_SETVBUF
430 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000431#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000432 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000433#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000434 }
435}
436
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000437/* Set the encoding used to output Unicode strings.
438 Returh 1 on success, 0 on failure. */
439
440int
441PyFile_SetEncoding(PyObject *f, const char *enc)
442{
443 PyFileObject *file = (PyFileObject*)f;
444 PyObject *str = PyString_FromString(enc);
Thomas Woutersafea5292007-01-23 13:42:00 +0000445
446 assert(PyFile_Check(f));
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000447 if (!str)
448 return 0;
449 Py_DECREF(file->f_encoding);
450 file->f_encoding = str;
451 return 1;
452}
453
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000455err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000456{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000458 return NULL;
459}
460
Thomas Woutersc45251a2006-02-12 11:53:32 +0000461/* Refuse regular file I/O if there's data in the iteration-buffer.
462 * Mixing them would cause data to arrive out of order, as the read*
463 * methods don't use the iteration buffer. */
464static PyObject *
465err_iterbuffered(void)
466{
467 PyErr_SetString(PyExc_ValueError,
468 "Mixing iteration and read methods would lose data");
469 return NULL;
470}
471
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000472static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000473
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474/* Methods */
475
476static void
Fred Drakefd99de62000-07-09 05:02:18 +0000477file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000478{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000479 PyObject *ret;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000480 if (f->weakreflist != NULL)
481 PyObject_ClearWeakRefs((PyObject *) f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000482 ret = close_the_file(f);
483 if (!ret) {
484 PySys_WriteStderr("close failed in file object destructor:\n");
485 PyErr_Print();
486 }
487 else {
488 Py_DECREF(ret);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000489 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000490 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000491 Py_XDECREF(f->f_name);
492 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000493 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000494 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000495 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496}
497
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000499file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000501 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000502#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000503 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000504 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
505 const char *name_str = name ? PyString_AsString(name) : "?";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000506 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
507 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000508 name_str,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000509 PyString_AsString(f->f_mode),
510 f);
511 Py_XDECREF(name);
512 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000513#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000514 } else {
515 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000516 f->f_fp == NULL ? "closed" : "open",
517 PyString_AsString(f->f_name),
518 PyString_AsString(f->f_mode),
519 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000520 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521}
522
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000524file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000526 PyObject *sts = close_the_file(f);
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000527 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000528 f->f_setbuf = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000529 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530}
531
Trent Mickf29f47b2000-08-11 19:02:59 +0000532
Guido van Rossumb8552162001-09-05 14:58:11 +0000533/* Our very own off_t-like type, 64-bit if possible */
534#if !defined(HAVE_LARGEFILE_SUPPORT)
535typedef off_t Py_off_t;
536#elif SIZEOF_OFF_T >= 8
537typedef off_t Py_off_t;
538#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000539typedef fpos_t Py_off_t;
540#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000541#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000542#endif
543
544
Trent Mickf29f47b2000-08-11 19:02:59 +0000545/* a portable fseek() function
546 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000547static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000548_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000549{
Guido van Rossumb8552162001-09-05 14:58:11 +0000550#if !defined(HAVE_LARGEFILE_SUPPORT)
551 return fseek(fp, offset, whence);
552#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000553 return fseeko(fp, offset, whence);
554#elif defined(HAVE_FSEEK64)
555 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000556#elif defined(__BEOS__)
557 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000558#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000559 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
560 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000561 fpos_t pos;
562 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000563 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000564#ifdef MS_WINDOWS
565 fflush(fp);
566 if (_lseeki64(fileno(fp), 0, 2) == -1)
567 return -1;
568#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000569 if (fseek(fp, 0, SEEK_END) != 0)
570 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000571#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000572 /* fall through */
573 case SEEK_CUR:
574 if (fgetpos(fp, &pos) != 0)
575 return -1;
576 offset += pos;
577 break;
578 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000579 }
580 return fsetpos(fp, &offset);
581#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000582#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000583#endif
584}
585
586
587/* a portable ftell() function
588 Return -1 on failure with errno set appropriately, current file
589 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000590static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000591_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000592{
Guido van Rossumb8552162001-09-05 14:58:11 +0000593#if !defined(HAVE_LARGEFILE_SUPPORT)
594 return ftell(fp);
595#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
596 return ftello(fp);
597#elif defined(HAVE_FTELL64)
598 return ftell64(fp);
599#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000600 fpos_t pos;
601 if (fgetpos(fp, &pos) != 0)
602 return -1;
603 return pos;
604#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000605#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000606#endif
607}
608
609
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000611file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000612{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000613 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000614 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000615 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000616 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000617
Guido van Rossumd7297e61992-07-06 14:19:26 +0000618 if (f->f_fp == NULL)
619 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000620 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000621 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000622 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000623 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000624 off_index = PyNumber_Index(offobj);
625 if (!off_index) {
626 if (!PyFloat_Check(offobj))
627 return NULL;
628 /* Deprecated in 2.6 */
629 PyErr_Clear();
630 if (PyErr_Warn(PyExc_DeprecationWarning,
631 "integer argument expected, got float"))
632 return NULL;
633 off_index = offobj;
634 Py_INCREF(offobj);
635 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000636#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000637 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000638#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000639 offset = PyLong_Check(off_index) ?
640 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000641#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000642 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000643 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000644 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000645
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000646 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000647 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000648 ret = _portable_fseek(f->f_fp, offset, whence);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000649 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000650
Guido van Rossumff4949e1992-08-05 19:58:53 +0000651 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000653 clearerr(f->f_fp);
654 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000655 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000656 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657 Py_INCREF(Py_None);
658 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000659}
660
Trent Mickf29f47b2000-08-11 19:02:59 +0000661
Guido van Rossumd7047b31995-01-02 19:07:15 +0000662#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000664file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000665{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000666 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000667 PyObject *newsizeobj = NULL;
668 Py_off_t initialpos;
669 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000670
Guido van Rossumd7047b31995-01-02 19:07:15 +0000671 if (f->f_fp == NULL)
672 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000673 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000674 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000675
Tim Petersf1827cf2003-09-07 03:30:18 +0000676 /* Get current file position. If the file happens to be open for
677 * update and the last operation was an input operation, C doesn't
678 * define what the later fflush() will do, but we promise truncate()
679 * won't change the current position (and fflush() *does* change it
680 * then at least on Windows). The easiest thing is to capture
681 * current pos now and seek back to it at the end.
682 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000683 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000684 errno = 0;
685 initialpos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000686 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000687 if (initialpos == -1)
688 goto onioerror;
689
Tim Petersfb05db22002-03-11 00:24:00 +0000690 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000691 * specified value.
692 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000693 if (newsizeobj != NULL) {
694#if !defined(HAVE_LARGEFILE_SUPPORT)
695 newsize = PyInt_AsLong(newsizeobj);
696#else
697 newsize = PyLong_Check(newsizeobj) ?
698 PyLong_AsLongLong(newsizeobj) :
699 PyInt_AsLong(newsizeobj);
700#endif
701 if (PyErr_Occurred())
702 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000703 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000704 else /* default to current position */
705 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000706
Tim Petersf1827cf2003-09-07 03:30:18 +0000707 /* Flush the stream. We're mixing stream-level I/O with lower-level
708 * I/O, and a flush may be necessary to synch both platform views
709 * of the current file state.
710 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000711 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000712 errno = 0;
713 ret = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000714 FILE_END_ALLOW_THREADS(f)
Tim Petersfb05db22002-03-11 00:24:00 +0000715 if (ret != 0)
716 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000717
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000718#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000719 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000720 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000721 {
Tim Petersfb05db22002-03-11 00:24:00 +0000722 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000723
Tim Petersf1827cf2003-09-07 03:30:18 +0000724 /* Have to move current pos to desired endpoint on Windows. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000725 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000726 errno = 0;
727 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000728 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000729 if (ret)
730 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000731
Tim Peters8f01b682002-03-12 03:04:44 +0000732 /* Truncate. Note that this may grow the file! */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000733 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters8f01b682002-03-12 03:04:44 +0000734 errno = 0;
735 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000736 ret = hFile == (HANDLE)-1;
737 if (ret == 0) {
738 ret = SetEndOfFile(hFile) == 0;
739 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000740 errno = EACCES;
741 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000742 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000743 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000744 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000745 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000746#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000747 FILE_BEGIN_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000748 errno = 0;
749 ret = ftruncate(fileno(f->f_fp), newsize);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000750 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000751 if (ret != 0)
752 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000753#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000754
Tim Petersf1827cf2003-09-07 03:30:18 +0000755 /* Restore original file position. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000756 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000757 errno = 0;
758 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000759 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000760 if (ret)
761 goto onioerror;
762
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000763 Py_INCREF(Py_None);
764 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000765
766onioerror:
767 PyErr_SetFromErrno(PyExc_IOError);
768 clearerr(f->f_fp);
769 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000770}
771#endif /* HAVE_FTRUNCATE */
772
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000773static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000774file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000775{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000776 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000777
Guido van Rossumd7297e61992-07-06 14:19:26 +0000778 if (f->f_fp == NULL)
779 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000780 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000781 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000782 pos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000783 FILE_END_ALLOW_THREADS(f)
784
Trent Mickf29f47b2000-08-11 19:02:59 +0000785 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000786 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000787 clearerr(f->f_fp);
788 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000789 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000790 if (f->f_skipnextlf) {
791 int c;
792 c = GETC(f->f_fp);
793 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000794 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000795 pos++;
796 f->f_skipnextlf = 0;
797 } else if (c != EOF) ungetc(c, f->f_fp);
798 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000799#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000800 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000801#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000802 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000803#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000804}
805
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000807file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000808{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000809 if (f->f_fp == NULL)
810 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000812}
813
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000814static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000815file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000816{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000817 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000818
Guido van Rossumd7297e61992-07-06 14:19:26 +0000819 if (f->f_fp == NULL)
820 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000821 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000822 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000823 res = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000824 FILE_END_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000825 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000826 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000827 clearerr(f->f_fp);
828 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000829 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000830 Py_INCREF(Py_None);
831 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000832}
833
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000834static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000835file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000836{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000837 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000838 if (f->f_fp == NULL)
839 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000840 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000841 res = isatty((int)fileno(f->f_fp));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000842 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000843 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000844}
845
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000846
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000847#if BUFSIZ < 8192
848#define SMALLCHUNK 8192
849#else
850#define SMALLCHUNK BUFSIZ
851#endif
852
Guido van Rossum3c259041999-01-14 19:00:14 +0000853#if SIZEOF_INT < 4
854#define BIGCHUNK (512 * 32)
855#else
856#define BIGCHUNK (512 * 1024)
857#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000858
859static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000860new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000861{
862#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000863 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000864 struct stat st;
865 if (fstat(fileno(f->f_fp), &st) == 0) {
866 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000867 /* The following is not a bug: we really need to call lseek()
868 *and* ftell(). The reason is that some stdio libraries
869 mistakenly flush their buffer when ftell() is called and
870 the lseek() call it makes fails, thereby throwing away
871 data that cannot be recovered in any way. To avoid this,
872 we first test lseek(), and only call ftell() if lseek()
873 works. We can't use the lseek() value either, because we
874 need to take the amount of buffered data into account.
875 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000876 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000877 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000878 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000879 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000880 if (pos < 0)
881 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000882 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000883 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000884 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000885 }
886#endif
887 if (currentsize > SMALLCHUNK) {
888 /* Keep doubling until we reach BIGCHUNK;
889 then keep adding BIGCHUNK. */
890 if (currentsize <= BIGCHUNK)
891 return currentsize + currentsize;
892 else
893 return currentsize + BIGCHUNK;
894 }
895 return currentsize + SMALLCHUNK;
896}
897
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000898#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
899#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
900#else
901#ifdef EWOULDBLOCK
902#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
903#else
904#ifdef EAGAIN
905#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
906#else
907#define BLOCKED_ERRNO(x) 0
908#endif
909#endif
910#endif
911
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000912static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000913file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000914{
Guido van Rossum789a1611997-05-10 22:33:55 +0000915 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000916 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000917 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000918
Guido van Rossumd7297e61992-07-06 14:19:26 +0000919 if (f->f_fp == NULL)
920 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000921 /* refuse to mix with f.next() */
922 if (f->f_buf != NULL &&
923 (f->f_bufend - f->f_bufptr) > 0 &&
924 f->f_buf[0] != '\0')
925 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000926 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000927 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000928 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000929 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000930 else
931 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +0000932 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000933 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000934 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000935 return NULL;
936 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000937 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000938 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000939 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000940 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000941 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000942 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +0000943 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000944 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000945 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000946 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +0000947 if (chunksize == 0) {
948 if (!ferror(f->f_fp))
949 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000950 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000951 /* When in non-blocking mode, data shouldn't
952 * be discarded if a blocking signal was
953 * received. That will also happen if
954 * chunksize != 0, but bytesread < buffersize. */
955 if (bytesread > 0 && BLOCKED_ERRNO(errno))
956 break;
957 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000958 Py_DECREF(v);
959 return NULL;
960 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000961 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000962 if (bytesread < buffersize) {
963 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000964 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000965 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000966 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000967 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000968 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000969 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000970 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000971 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000972 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000973 }
974 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000975 if (bytesread != buffersize)
976 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000977 return v;
978}
979
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000980static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000981file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000982{
983 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000984 Py_ssize_t ntodo;
985 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000986
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000987 if (f->f_fp == NULL)
988 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000989 /* refuse to mix with f.next() */
990 if (f->f_buf != NULL &&
991 (f->f_bufend - f->f_bufptr) > 0 &&
992 f->f_buf[0] != '\0')
993 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000994 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000995 return NULL;
996 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000997 while (ntodo > 0) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000998 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +0000999 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +00001000 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001001 (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001002 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001003 if (nnow == 0) {
1004 if (!ferror(f->f_fp))
1005 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001006 PyErr_SetFromErrno(PyExc_IOError);
1007 clearerr(f->f_fp);
1008 return NULL;
1009 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001010 ndone += nnow;
1011 ntodo -= nnow;
1012 }
Neal Norwitz076d1e02006-08-21 18:20:10 +00001013 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001014}
1015
Tim Peters86821b22001-01-07 21:19:34 +00001016/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001017Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001018
1019Under MSVC 6:
1020
Tim Peters1c733232001-01-08 04:02:07 +00001021+ MS threadsafe getc is very slow (multiple layers of function calls before+
1022 after each character, to lock+unlock the stream).
1023+ The stream-locking functions are MS-internal -- can't access them from user
1024 code.
1025+ There's nothing Tim could find in the MS C or platform SDK libraries that
1026 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001027+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1028
1029So we use fgets for speed(!), despite that it's painful.
1030
1031MS realloc is also slow.
1032
Tim Petersf29b64d2001-01-15 06:33:19 +00001033Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1034have):
1035 Linux a wash
1036 Solaris a wash
1037 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001038
Tim Petersf29b64d2001-01-15 06:33:19 +00001039CAUTION: The C std isn't clear about this: in those cases where fgets
1040writes something into the buffer, can it write into any position beyond the
1041required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1042known on which it does; and it would be a strange way to code fgets. Still,
1043getline_via_fgets may not work correctly if it does. The std test
1044test_bufio.py should fail if platform fgets() routinely writes beyond the
1045trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001046**************************************************************************/
1047
Tim Petersf29b64d2001-01-15 06:33:19 +00001048/* Use this routine if told to, or by default on non-get_unlocked()
1049 * platforms unless told not to. Yikes! Let's spell that out:
1050 * On a platform with getc_unlocked():
1051 * By default, use getc_unlocked().
1052 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1053 * On a platform without getc_unlocked():
1054 * By default, use fgets().
1055 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1056 */
1057#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1058#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001059#endif
1060
Tim Petersf29b64d2001-01-15 06:33:19 +00001061#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1062#undef USE_FGETS_IN_GETLINE
1063#endif
1064
1065#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001066static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001067getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001068{
Tim Peters15b83852001-01-08 00:53:12 +00001069/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001070 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1071 * to fill this much of the buffer with a known value in order to figure out
1072 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1073 * than "most" lines, we waste time filling unused buffer slots. 100 is
1074 * surely adequate for most peoples' email archives, chewing over source code,
1075 * etc -- "regular old text files".
1076 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1077 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1078 * cautions about boosting that. 300 was chosen because the worst real-life
1079 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1080 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001081 */
Tim Peters142297a2001-01-15 10:36:56 +00001082#define INITBUFSIZE 100
1083#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001084 char* p; /* temp */
1085 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001086 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001087 char* pvfree; /* address of next free slot */
1088 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001089 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1090 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001091 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001092 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001093
Tim Peters15b83852001-01-08 00:53:12 +00001094 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001095 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001096 */
Tim Peters142297a2001-01-15 10:36:56 +00001097 total_v_size = INITBUFSIZE; /* start small and pray */
1098 pvfree = buf;
1099 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001100 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters142297a2001-01-15 10:36:56 +00001101 pvend = buf + total_v_size;
1102 nfree = pvend - pvfree;
1103 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001104 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1105 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001106 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001107
Tim Peters142297a2001-01-15 10:36:56 +00001108 if (p == NULL) {
1109 clearerr(fp);
1110 if (PyErr_CheckSignals())
1111 return NULL;
1112 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001113 return v;
1114 }
Tim Peters142297a2001-01-15 10:36:56 +00001115 /* fgets read *something* */
1116 p = memchr(pvfree, '\n', nfree);
1117 if (p != NULL) {
1118 /* Did the \n come from fgets or from us?
1119 * Since fgets stops at the first \n, and then writes
1120 * \0, if it's from fgets a \0 must be next. But if
1121 * that's so, it could not have come from us, since
1122 * the \n's we filled the buffer with have only more
1123 * \n's to the right.
1124 */
1125 if (p+1 < pvend && *(p+1) == '\0') {
1126 /* It's from fgets: we win! In particular,
1127 * we haven't done any mallocs yet, and can
1128 * build the final result on the first try.
1129 */
1130 ++p; /* include \n from fgets */
1131 }
1132 else {
1133 /* Must be from us: fgets didn't fill the
1134 * buffer and didn't find a newline, so it
1135 * must be the last and newline-free line of
1136 * the file.
1137 */
1138 assert(p > pvfree && *(p-1) == '\0');
1139 --p; /* don't include \0 from fgets */
1140 }
1141 v = PyString_FromStringAndSize(buf, p - buf);
1142 return v;
1143 }
1144 /* yuck: fgets overwrote all the newlines, i.e. the entire
1145 * buffer. So this line isn't over yet, or maybe it is but
1146 * we're exactly at EOF. If we haven't already, try using the
1147 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001148 */
Tim Peters142297a2001-01-15 10:36:56 +00001149 assert(*(pvend-1) == '\0');
1150 if (pvfree == buf) {
1151 pvfree = pvend - 1; /* overwrite trailing null */
1152 total_v_size = MAXBUFSIZE;
1153 }
1154 else
1155 break;
Tim Peters86821b22001-01-07 21:19:34 +00001156 }
Tim Peters142297a2001-01-15 10:36:56 +00001157
1158 /* The stack buffer isn't big enough; malloc a string object and read
1159 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001160 */
Tim Petersddea2082002-03-23 10:03:50 +00001161 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001162 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001163 if (v == NULL)
1164 return v;
1165 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001166 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1167 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001168
1169 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001170 * after setting p one beyond the end of the line. The code here is
1171 * very much like the code above, except reads into v's buffer; see
1172 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001173 */
1174 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001175 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001176 pvend = BUF(v) + total_v_size;
1177 nfree = pvend - pvfree;
1178 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001179 assert(nfree < INT_MAX);
1180 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001181 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001182
1183 if (p == NULL) {
1184 clearerr(fp);
1185 if (PyErr_CheckSignals()) {
1186 Py_DECREF(v);
1187 return NULL;
1188 }
1189 p = pvfree;
1190 break;
1191 }
Tim Peters86821b22001-01-07 21:19:34 +00001192 p = memchr(pvfree, '\n', nfree);
1193 if (p != NULL) {
1194 if (p+1 < pvend && *(p+1) == '\0') {
1195 /* \n came from fgets */
1196 ++p;
1197 break;
1198 }
1199 /* \n came from us; last line of file, no newline */
1200 assert(p > pvfree && *(p-1) == '\0');
1201 --p;
1202 break;
1203 }
1204 /* expand buffer and try again */
1205 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001206 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001207 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001208 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001209 /* check for overflow */
1210 if (total_v_size <= prev_v_size ||
1211 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001212 PyErr_SetString(PyExc_OverflowError,
1213 "line is longer than a Python string can hold");
1214 Py_DECREF(v);
1215 return NULL;
1216 }
1217 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1218 return NULL;
1219 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001220 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001221 }
1222 if (BUF(v) + total_v_size != p)
1223 _PyString_Resize(&v, p - BUF(v));
1224 return v;
1225#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001226#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001227}
Tim Petersf29b64d2001-01-15 06:33:19 +00001228#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001229
Guido van Rossum0bd24411991-04-04 15:21:57 +00001230/* Internal routine to get a line.
1231 Size argument interpretation:
1232 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001233 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001234*/
1235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001236static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001237get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001238{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001239 FILE *fp = f->f_fp;
1240 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001241 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001242 size_t total_v_size; /* total # of slots in buffer */
1243 size_t used_v_size; /* # used slots in buffer */
1244 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001245 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001246 int newlinetypes = f->f_newlinetypes;
1247 int skipnextlf = f->f_skipnextlf;
1248 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001249
Jack Jansen7b8c7542002-04-14 20:12:41 +00001250#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001251 if (n <= 0 && !univ_newline )
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001252 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001253#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001254 total_v_size = n > 0 ? n : 100;
1255 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001256 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001257 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001258 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001259 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001260
Guido van Rossumce5ba841991-03-06 13:06:18 +00001261 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001262 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001263 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001264 if (univ_newline) {
1265 c = 'x'; /* Shut up gcc warning */
1266 while ( buf != end && (c = GETC(fp)) != EOF ) {
1267 if (skipnextlf ) {
1268 skipnextlf = 0;
1269 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001270 /* Seeing a \n here with
1271 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001272 * saw a \r before.
1273 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001274 newlinetypes |= NEWLINE_CRLF;
1275 c = GETC(fp);
1276 if (c == EOF) break;
1277 } else {
1278 newlinetypes |= NEWLINE_CR;
1279 }
1280 }
1281 if (c == '\r') {
1282 skipnextlf = 1;
1283 c = '\n';
1284 } else if ( c == '\n')
1285 newlinetypes |= NEWLINE_LF;
1286 *buf++ = c;
1287 if (c == '\n') break;
1288 }
1289 if ( c == EOF && skipnextlf )
1290 newlinetypes |= NEWLINE_CR;
1291 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001292 while ((c = GETC(fp)) != EOF &&
1293 (*buf++ = c) != '\n' &&
1294 buf != end)
1295 ;
1296 FUNLOCKFILE(fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001297 FILE_END_ALLOW_THREADS(f)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001298 f->f_newlinetypes = newlinetypes;
1299 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001300 if (c == '\n')
1301 break;
1302 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001303 if (ferror(fp)) {
1304 PyErr_SetFromErrno(PyExc_IOError);
1305 clearerr(fp);
1306 Py_DECREF(v);
1307 return NULL;
1308 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001309 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001310 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001311 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001312 return NULL;
1313 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001314 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001315 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001316 /* Must be because buf == end */
1317 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001318 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001319 used_v_size = total_v_size;
1320 increment = total_v_size >> 2; /* mild exponential growth */
1321 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001322 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001323 PyErr_SetString(PyExc_OverflowError,
1324 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001325 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001326 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001327 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001328 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001329 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001330 buf = BUF(v) + used_v_size;
1331 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001332 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001333
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001334 used_v_size = buf - BUF(v);
1335 if (used_v_size != total_v_size)
1336 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001337 return v;
1338}
1339
Guido van Rossum0bd24411991-04-04 15:21:57 +00001340/* External C interface */
1341
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001342PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001343PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001344{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001345 PyObject *result;
1346
Guido van Rossum3165fe61992-09-25 21:59:05 +00001347 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001348 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001349 return NULL;
1350 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001351
1352 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001353 PyFileObject *fo = (PyFileObject *)f;
1354 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001355 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001356 /* refuse to mix with f.next() */
1357 if (fo->f_buf != NULL &&
1358 (fo->f_bufend - fo->f_bufptr) > 0 &&
1359 fo->f_buf[0] != '\0')
1360 return err_iterbuffered();
1361 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001362 }
1363 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001364 PyObject *reader;
1365 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001366
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001367 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001368 if (reader == NULL)
1369 return NULL;
1370 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001371 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001372 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001374 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001375 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001376 return NULL;
1377 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001378 result = PyEval_CallObject(reader, args);
1379 Py_DECREF(reader);
1380 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001381 if (result != NULL && !PyString_Check(result) &&
1382 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001383 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001384 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001385 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001386 "object.readline() returned non-string");
1387 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001388 }
1389
1390 if (n < 0 && result != NULL && PyString_Check(result)) {
1391 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001392 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001393 if (len == 0) {
1394 Py_DECREF(result);
1395 result = NULL;
1396 PyErr_SetString(PyExc_EOFError,
1397 "EOF when reading a line");
1398 }
1399 else if (s[len-1] == '\n') {
1400 if (result->ob_refcnt == 1)
1401 _PyString_Resize(&result, len-1);
1402 else {
1403 PyObject *v;
1404 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001405 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001406 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001407 }
1408 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001409 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001410#ifdef Py_USING_UNICODE
1411 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1412 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001413 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001414 if (len == 0) {
1415 Py_DECREF(result);
1416 result = NULL;
1417 PyErr_SetString(PyExc_EOFError,
1418 "EOF when reading a line");
1419 }
1420 else if (s[len-1] == '\n') {
1421 if (result->ob_refcnt == 1)
1422 PyUnicode_Resize(&result, len-1);
1423 else {
1424 PyObject *v;
1425 v = PyUnicode_FromUnicode(s, len-1);
1426 Py_DECREF(result);
1427 result = v;
1428 }
1429 }
1430 }
1431#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001432 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001433}
1434
1435/* Python method */
1436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001437static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001438file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001439{
Guido van Rossum789a1611997-05-10 22:33:55 +00001440 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001441
Guido van Rossumd7297e61992-07-06 14:19:26 +00001442 if (f->f_fp == NULL)
1443 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001444 /* refuse to mix with f.next() */
1445 if (f->f_buf != NULL &&
1446 (f->f_bufend - f->f_bufptr) > 0 &&
1447 f->f_buf[0] != '\0')
1448 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001449 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001450 return NULL;
1451 if (n == 0)
1452 return PyString_FromString("");
1453 if (n < 0)
1454 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001455 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001456}
1457
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001458static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001459file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001460{
Guido van Rossum789a1611997-05-10 22:33:55 +00001461 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001462 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001463 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001464 char small_buffer[SMALLCHUNK];
1465 char *buffer = small_buffer;
1466 size_t buffersize = SMALLCHUNK;
1467 PyObject *big_buffer = NULL;
1468 size_t nfilled = 0;
1469 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001470 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001471 char *p, *q, *end;
1472 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001473 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001474
Guido van Rossumd7297e61992-07-06 14:19:26 +00001475 if (f->f_fp == NULL)
1476 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001477 /* refuse to mix with f.next() */
1478 if (f->f_buf != NULL &&
1479 (f->f_bufend - f->f_bufptr) > 0 &&
1480 f->f_buf[0] != '\0')
1481 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001482 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001483 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001485 return NULL;
1486 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001487 if (shortread)
1488 nread = 0;
1489 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001490 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001491 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001492 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001493 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001494 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001495 shortread = (nread < buffersize-nfilled);
1496 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001497 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001498 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001499 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001500 break;
1501 PyErr_SetFromErrno(PyExc_IOError);
1502 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001503 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001504 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001505 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001506 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001507 if (p == NULL) {
1508 /* Need a larger buffer to fit this line */
1509 nfilled += nread;
1510 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001511 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001512 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001513 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001514 goto error;
1515 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001516 if (big_buffer == NULL) {
1517 /* Create the big buffer */
1518 big_buffer = PyString_FromStringAndSize(
1519 NULL, buffersize);
1520 if (big_buffer == NULL)
1521 goto error;
1522 buffer = PyString_AS_STRING(big_buffer);
1523 memcpy(buffer, small_buffer, nfilled);
1524 }
1525 else {
1526 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001527 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1528 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001529 buffer = PyString_AS_STRING(big_buffer);
1530 }
1531 continue;
1532 }
1533 end = buffer+nfilled+nread;
1534 q = buffer;
1535 do {
1536 /* Process complete lines */
1537 p++;
1538 line = PyString_FromStringAndSize(q, p-q);
1539 if (line == NULL)
1540 goto error;
1541 err = PyList_Append(list, line);
1542 Py_DECREF(line);
1543 if (err != 0)
1544 goto error;
1545 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001546 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001547 } while (p != NULL);
1548 /* Move the remaining incomplete line to the start */
1549 nfilled = end-q;
1550 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001551 if (sizehint > 0)
1552 if (totalread >= (size_t)sizehint)
1553 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001554 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001555 if (nfilled != 0) {
1556 /* Partial last line */
1557 line = PyString_FromStringAndSize(buffer, nfilled);
1558 if (line == NULL)
1559 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001560 if (sizehint > 0) {
1561 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001562 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001563 if (rest == NULL) {
1564 Py_DECREF(line);
1565 goto error;
1566 }
1567 PyString_Concat(&line, rest);
1568 Py_DECREF(rest);
1569 if (line == NULL)
1570 goto error;
1571 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001572 err = PyList_Append(list, line);
1573 Py_DECREF(line);
1574 if (err != 0)
1575 goto error;
1576 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001577
1578cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001579 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001580 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001581
1582error:
1583 Py_CLEAR(list);
1584 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001585}
1586
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001587static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001588file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001589{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001590 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001591 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001592 if (f->f_fp == NULL)
1593 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001594 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001595 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001596 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001597 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001598 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001599 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001600 FILE_END_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001601 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001602 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001603 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001604 return NULL;
1605 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001606 Py_INCREF(Py_None);
1607 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001608}
1609
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001610static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001611file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001612{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001613#define CHUNKSIZE 1000
1614 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001615 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001616 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001617 int index, islist;
1618 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001619
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001620 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001621 if (f->f_fp == NULL)
1622 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001623
1624 result = NULL;
1625 list = NULL;
1626 islist = PyList_Check(seq);
1627 if (islist)
1628 it = NULL;
1629 else {
1630 it = PyObject_GetIter(seq);
1631 if (it == NULL) {
1632 PyErr_SetString(PyExc_TypeError,
1633 "writelines() requires an iterable argument");
1634 return NULL;
1635 }
1636 /* From here on, fail by going to error, to reclaim "it". */
1637 list = PyList_New(CHUNKSIZE);
1638 if (list == NULL)
1639 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001640 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001641
1642 /* Strategy: slurp CHUNKSIZE lines into a private list,
1643 checking that they are all strings, then write that list
1644 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001645 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001646 if (islist) {
1647 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001648 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001649 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001650 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001651 j = PyList_GET_SIZE(list);
1652 }
1653 else {
1654 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001655 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001656 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001657 if (PyErr_Occurred())
1658 goto error;
1659 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001660 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001661 PyList_SetItem(list, j, line);
1662 }
1663 }
1664 if (j == 0)
1665 break;
1666
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001667 /* Check that all entries are indeed strings. If not,
1668 apply the same rules as for file.write() and
1669 convert the results to strings. This is slow, but
1670 seems to be the only way since all conversion APIs
1671 could potentially execute Python code. */
1672 for (i = 0; i < j; i++) {
1673 PyObject *v = PyList_GET_ITEM(list, i);
1674 if (!PyString_Check(v)) {
1675 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001676 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001677 PyObject_AsReadBuffer(v,
1678 (const void**)&buffer,
1679 &len)) ||
1680 PyObject_AsCharBuffer(v,
1681 &buffer,
1682 &len))) {
1683 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001684 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001685 goto error;
1686 }
1687 line = PyString_FromStringAndSize(buffer,
1688 len);
1689 if (line == NULL)
1690 goto error;
1691 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001692 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001693 }
1694 }
1695
1696 /* Since we are releasing the global lock, the
1697 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001698 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001699 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001700 errno = 0;
1701 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001702 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001703 len = PyString_GET_SIZE(line);
1704 nwritten = fwrite(PyString_AS_STRING(line),
1705 1, len, f->f_fp);
1706 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001707 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001708 PyErr_SetFromErrno(PyExc_IOError);
1709 clearerr(f->f_fp);
1710 goto error;
1711 }
1712 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001713 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001714
1715 if (j < CHUNKSIZE)
1716 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001717 }
1718
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001719 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001720 result = Py_None;
1721 error:
1722 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001723 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001724 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001725#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001726}
1727
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001728static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001729file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001730{
1731 if (f->f_fp == NULL)
1732 return err_closed();
1733 Py_INCREF(f);
1734 return (PyObject *)f;
1735}
1736
Georg Brandl98b40ad2006-06-08 14:50:21 +00001737static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001738file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001739{
Georg Brandlad61bc82008-02-23 15:11:18 +00001740 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001741 if (!ret)
1742 /* If error occurred, pass through */
1743 return NULL;
1744 Py_DECREF(ret);
1745 /* We cannot return the result of close since a true
1746 * value will be interpreted as "yes, swallow the
1747 * exception if one was raised inside the with block". */
1748 Py_RETURN_NONE;
1749}
1750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001751PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001752"readline([size]) -> next line from the file, as a string.\n"
1753"\n"
1754"Retain newline. A non-negative size argument limits the maximum\n"
1755"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001756"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001758PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001759"read([size]) -> read at most size bytes, returned as a string.\n"
1760"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001761"If the size argument is negative or omitted, read until EOF is reached.\n"
1762"Notice that when in non-blocking mode, less data than what was requested\n"
1763"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001765PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001766"write(str) -> None. Write string str to file.\n"
1767"\n"
1768"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001769"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001771PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001772"fileno() -> integer \"file descriptor\".\n"
1773"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001774"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001776PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001777"seek(offset[, whence]) -> None. Move to new file position.\n"
1778"\n"
1779"Argument offset is a byte count. Optional argument whence defaults to\n"
1780"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1781"(move relative to current position, positive or negative), and 2 (move\n"
1782"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001783"seeking beyond the end of a file). If the file is opened in text mode,\n"
1784"only offsets returned by tell() are legal. Use of other offsets causes\n"
1785"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001786"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001787"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001788
Guido van Rossumd7047b31995-01-02 19:07:15 +00001789#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001790PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001791"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1792"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001793"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001794#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001796PyDoc_STRVAR(tell_doc,
1797"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001799PyDoc_STRVAR(readinto_doc,
1800"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001802PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001803"readlines([size]) -> list of strings, each a line from the file.\n"
1804"\n"
1805"Call readline() repeatedly and return a list of the lines so read.\n"
1806"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001807"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001809PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001810"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001811"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001812"For backward compatibility. File objects now include the performance\n"
1813"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001814
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001815PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001816"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001817"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001818"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001819"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001820
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001821PyDoc_STRVAR(flush_doc,
1822"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001824PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001825"close() -> None or (perhaps) an integer. Close the file.\n"
1826"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001827"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001828"further I/O operations. close() may be called more than once without\n"
1829"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001830"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001832PyDoc_STRVAR(isatty_doc,
1833"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001834
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001835PyDoc_STRVAR(enter_doc,
1836 "__enter__() -> self.");
1837
Georg Brandl98b40ad2006-06-08 14:50:21 +00001838PyDoc_STRVAR(exit_doc,
1839 "__exit__(*excinfo) -> None. Closes the file.");
1840
Tim Petersefc3a3a2001-09-20 07:55:22 +00001841static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001842 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1843 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1844 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1845 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1846 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001847#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001848 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001849#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001850 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1851 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1852 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001853 {"xreadlines",(PyCFunction)file_self, METH_NOARGS, xreadlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001854 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1855 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1856 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1857 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001858 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00001859 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001860 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001861};
1862
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001863#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001864
Guido van Rossum6f799372001-09-20 20:46:19 +00001865static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00001866 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001867 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001868 {"name", T_OBJECT, OFF(f_name), RO,
1869 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001870 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1871 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001872 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001873 {NULL} /* Sentinel */
1874};
1875
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001878{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001879 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001880}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001881static PyObject *
1882get_newlines(PyFileObject *f, void *closure)
1883{
1884 switch (f->f_newlinetypes) {
1885 case NEWLINE_UNKNOWN:
1886 Py_INCREF(Py_None);
1887 return Py_None;
1888 case NEWLINE_CR:
1889 return PyString_FromString("\r");
1890 case NEWLINE_LF:
1891 return PyString_FromString("\n");
1892 case NEWLINE_CR|NEWLINE_LF:
1893 return Py_BuildValue("(ss)", "\r", "\n");
1894 case NEWLINE_CRLF:
1895 return PyString_FromString("\r\n");
1896 case NEWLINE_CR|NEWLINE_CRLF:
1897 return Py_BuildValue("(ss)", "\r", "\r\n");
1898 case NEWLINE_LF|NEWLINE_CRLF:
1899 return Py_BuildValue("(ss)", "\n", "\r\n");
1900 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1901 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1902 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001903 PyErr_Format(PyExc_SystemError,
1904 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001905 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001906 return NULL;
1907 }
1908}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001909
Georg Brandl65bb42d2008-03-21 20:38:24 +00001910static PyObject *
1911get_softspace(PyFileObject *f, void *closure)
1912{
1913 if (Py_Py3kWarningFlag &&
1914 PyErr_Warn(PyExc_DeprecationWarning,
1915 "file.softspace not supported in 3.x") < 0)
1916 return NULL;
1917 return PyInt_FromLong(f->f_softspace);
1918}
1919
1920static int
1921set_softspace(PyFileObject *f, PyObject *value)
1922{
1923 int new;
1924 if (Py_Py3kWarningFlag &&
1925 PyErr_Warn(PyExc_DeprecationWarning,
1926 "file.softspace not supported in 3.x") < 0)
1927 return -1;
1928
1929 if (value == NULL) {
1930 PyErr_SetString(PyExc_TypeError,
1931 "can't delete softspace attribute");
1932 return -1;
1933 }
1934
1935 new = PyInt_AsLong(value);
1936 if (new == -1 && PyErr_Occurred())
1937 return -1;
1938 f->f_softspace = new;
1939 return 0;
1940}
1941
Guido van Rossum32d34c82001-09-20 21:45:26 +00001942static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001943 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001944 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001945 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00001946 {"softspace", (getter)get_softspace, (setter)set_softspace,
1947 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 {0},
1949};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001950
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001951static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001952drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001953{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001954 if (f->f_buf != NULL) {
1955 PyMem_Free(f->f_buf);
1956 f->f_buf = NULL;
1957 }
Guido van Rossum65967252001-04-21 13:20:18 +00001958}
1959
Tim Petersf1827cf2003-09-07 03:30:18 +00001960/* Make sure that file has a readahead buffer with at least one byte
1961 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00001962 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001963static int
1964readahead(PyFileObject *f, int bufsize)
1965{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001966 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001967
1968 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001969 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001970 return 0;
1971 else
1972 drop_readahead(f);
1973 }
Anthony Baxter377be112006-04-11 06:54:30 +00001974 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00001975 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001976 return -1;
1977 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001978 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001979 errno = 0;
1980 chunksize = Py_UniversalNewlineFread(
1981 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001982 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001983 if (chunksize == 0) {
1984 if (ferror(f->f_fp)) {
1985 PyErr_SetFromErrno(PyExc_IOError);
1986 clearerr(f->f_fp);
1987 drop_readahead(f);
1988 return -1;
1989 }
1990 }
1991 f->f_bufptr = f->f_buf;
1992 f->f_bufend = f->f_buf + chunksize;
1993 return 0;
1994}
1995
1996/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001997 uninitialized bytes followed by the remainder of the line. Don't be
1998 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001999 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2000
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002001static PyStringObject *
2002readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2003{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002004 PyStringObject* s;
2005 char *bufptr;
2006 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002007 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002008
2009 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002010 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002011 return NULL;
2012
2013 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002014 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002015 return (PyStringObject *)
2016 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002017 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002018 if (bufptr != NULL) {
2019 bufptr++; /* Count the '\n' */
2020 len = bufptr - f->f_bufptr;
2021 s = (PyStringObject *)
2022 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002023 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002024 return NULL;
2025 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2026 f->f_bufptr = bufptr;
2027 if (bufptr == f->f_bufend)
2028 drop_readahead(f);
2029 } else {
2030 bufptr = f->f_bufptr;
2031 buf = f->f_buf;
2032 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002033 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002034 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002035 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002036 if (s == NULL) {
2037 PyMem_Free(buf);
2038 return NULL;
2039 }
2040 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2041 PyMem_Free(buf);
2042 }
2043 return s;
2044}
2045
2046/* A larger buffer size may actually decrease performance. */
2047#define READAHEAD_BUFSIZE 8192
2048
2049static PyObject *
2050file_iternext(PyFileObject *f)
2051{
2052 PyStringObject* l;
2053
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002054 if (f->f_fp == NULL)
2055 return err_closed();
2056
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002057 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2058 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2059 Py_XDECREF(l);
2060 return NULL;
2061 }
2062 return (PyObject *)l;
2063}
2064
2065
Tim Peters59c9a642001-09-13 05:38:56 +00002066static PyObject *
2067file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2068{
Tim Peters44410012001-09-14 03:26:08 +00002069 PyObject *self;
2070 static PyObject *not_yet_string;
2071
2072 assert(type != NULL && type->tp_alloc != NULL);
2073
2074 if (not_yet_string == NULL) {
Christian Heimesd7e1b2b2008-01-28 02:07:53 +00002075 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002076 if (not_yet_string == NULL)
2077 return NULL;
2078 }
2079
2080 self = type->tp_alloc(type, 0);
2081 if (self != NULL) {
2082 /* Always fill in the name and mode, so that nobody else
2083 needs to special-case NULLs there. */
2084 Py_INCREF(not_yet_string);
2085 ((PyFileObject *)self)->f_name = not_yet_string;
2086 Py_INCREF(not_yet_string);
2087 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002088 Py_INCREF(Py_None);
2089 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002090 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002091 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002092 }
2093 return self;
2094}
2095
2096static int
2097file_init(PyObject *self, PyObject *args, PyObject *kwds)
2098{
2099 PyFileObject *foself = (PyFileObject *)self;
2100 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002101 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002102 char *name = NULL;
2103 char *mode = "r";
2104 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002105 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00002106
2107 assert(PyFile_Check(self));
2108 if (foself->f_fp != NULL) {
2109 /* Have to close the existing file first. */
2110 PyObject *closeresult = file_close(foself);
2111 if (closeresult == NULL)
2112 return -1;
2113 Py_DECREF(closeresult);
2114 }
Tim Peters59c9a642001-09-13 05:38:56 +00002115
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002116#ifdef Py_WIN_WIDE_FILENAMES
2117 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2118 PyObject *po;
2119 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2120 kwlist, &po, &mode, &bufsize)) {
2121 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002122 if (fill_file_fields(foself, NULL, po, mode,
2123 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002124 goto Error;
2125 } else {
2126 /* Drop the argument parsing error as narrow
2127 strings are also valid. */
2128 PyErr_Clear();
2129 }
2130 }
2131#endif
2132
2133 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002134 PyObject *o_name;
2135
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002136 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2137 Py_FileSystemDefaultEncoding,
2138 &name,
2139 &mode, &bufsize))
2140 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002141
2142 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002143 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2144 kwlist, &o_name, &mode,
2145 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002146 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002147
2148 if (fill_file_fields(foself, NULL, o_name, mode,
2149 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002150 goto Error;
2151 }
Tim Peters44410012001-09-14 03:26:08 +00002152 if (open_the_file(foself, name, mode) == NULL)
2153 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002154 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002155 PyFile_SetBufSize(self, bufsize);
2156 goto Done;
2157
2158Error:
2159 ret = -1;
2160 /* fall through */
2161Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002162 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002163 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002164}
2165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002166PyDoc_VAR(file_doc) =
2167PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002168"file(name[, mode[, buffering]]) -> file object\n"
2169"\n"
2170"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2171"writing or appending. The file will be created if it doesn't exist\n"
2172"when opened for writing or appending; it will be truncated when\n"
2173"opened for writing. Add a 'b' to the mode for binary files.\n"
2174"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2175"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002176"buffered, and larger numbers specify the buffer size. The preferred way\n"
2177"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002178)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002179PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002180"Add a 'U' to mode to open the file for input with universal newline\n"
2181"support. Any line ending in the input file will be seen as a '\\n'\n"
2182"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2183"the value for this attribute is one of None (no newline read yet),\n"
2184"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2185"\n"
2186"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002187);
Tim Peters59c9a642001-09-13 05:38:56 +00002188
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002189PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002190 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002191 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002193 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002194 (destructor)file_dealloc, /* tp_dealloc */
2195 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196 0, /* tp_getattr */
2197 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002198 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002200 0, /* tp_as_number */
2201 0, /* tp_as_sequence */
2202 0, /* tp_as_mapping */
2203 0, /* tp_hash */
2204 0, /* tp_call */
2205 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002207 /* softspace is writable: we must supply tp_setattro */
2208 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002209 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002210 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002211 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 0, /* tp_traverse */
2213 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002214 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002215 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002216 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002217 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218 file_methods, /* tp_methods */
2219 file_memberlist, /* tp_members */
2220 file_getsetlist, /* tp_getset */
2221 0, /* tp_base */
2222 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002223 0, /* tp_descr_get */
2224 0, /* tp_descr_set */
2225 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002226 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002227 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002228 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002229 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002230};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002231
2232/* Interface for the 'soft space' between print items. */
2233
2234int
Fred Drakefd99de62000-07-09 05:02:18 +00002235PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002236{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002237 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002238 if (f == NULL) {
2239 /* Do nothing */
2240 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241 else if (PyFile_Check(f)) {
2242 oldflag = ((PyFileObject *)f)->f_softspace;
2243 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002244 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002245 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002246 PyObject *v;
2247 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002248 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002250 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002251 if (PyInt_Check(v))
2252 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002253 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002254 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002255 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002256 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002257 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002259 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2261 PyErr_Clear();
2262 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002263 }
2264 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002265 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002266}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002267
2268/* Interfaces to write objects/strings to file-like objects */
2269
2270int
Fred Drakefd99de62000-07-09 05:02:18 +00002271PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002272{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002273 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002274 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002276 return -1;
2277 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002278 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002279 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002280#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002281 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002282 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002283#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002284 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002285 err_closed();
2286 return -1;
2287 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002288#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002289 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002290 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002291 char *cenc = PyString_AS_STRING(enc);
2292 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2293 if (value == NULL)
2294 return -1;
2295 } else {
2296 value = v;
2297 Py_INCREF(value);
2298 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002299 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002300 Py_DECREF(value);
2301 return result;
2302#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002303 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002304#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002305 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002306 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002307 if (writer == NULL)
2308 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002309 if (flags & Py_PRINT_RAW) {
2310 if (PyUnicode_Check(v)) {
2311 value = v;
2312 Py_INCREF(value);
2313 } else
2314 value = PyObject_Str(v);
2315 }
2316 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002317 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002318 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002319 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002320 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002321 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002322 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002323 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324 Py_DECREF(value);
2325 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002326 return -1;
2327 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002328 result = PyEval_CallObject(writer, args);
2329 Py_DECREF(args);
2330 Py_DECREF(value);
2331 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002332 if (result == NULL)
2333 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002334 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002335 return 0;
2336}
2337
Guido van Rossum27a60b11997-05-22 22:25:11 +00002338int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002339PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002340{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002341
Guido van Rossum3165fe61992-09-25 21:59:05 +00002342 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002343 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002344 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002345 PyErr_SetString(PyExc_SystemError,
2346 "null file for PyFile_WriteString");
2347 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002348 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002349 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002350 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002351 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002352 if (fp == NULL) {
2353 err_closed();
2354 return -1;
2355 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002356 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002357 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002358 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002359 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002360 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002361 else if (!PyErr_Occurred()) {
2362 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002363 int err;
2364 if (v == NULL)
2365 return -1;
2366 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2367 Py_DECREF(v);
2368 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002369 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002370 else
2371 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002372}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002373
2374/* Try to get a file-descriptor from a Python object. If the object
2375 is an integer or long integer, its value is returned. If not, the
2376 object's fileno() method is called if it exists; the method must return
2377 an integer or long integer, which is returned as the file descriptor value.
2378 -1 is returned on failure.
2379*/
2380
2381int PyObject_AsFileDescriptor(PyObject *o)
2382{
2383 int fd;
2384 PyObject *meth;
2385
2386 if (PyInt_Check(o)) {
2387 fd = PyInt_AsLong(o);
2388 }
2389 else if (PyLong_Check(o)) {
2390 fd = PyLong_AsLong(o);
2391 }
2392 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2393 {
2394 PyObject *fno = PyEval_CallObject(meth, NULL);
2395 Py_DECREF(meth);
2396 if (fno == NULL)
2397 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002398
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002399 if (PyInt_Check(fno)) {
2400 fd = PyInt_AsLong(fno);
2401 Py_DECREF(fno);
2402 }
2403 else if (PyLong_Check(fno)) {
2404 fd = PyLong_AsLong(fno);
2405 Py_DECREF(fno);
2406 }
2407 else {
2408 PyErr_SetString(PyExc_TypeError,
2409 "fileno() returned a non-integer");
2410 Py_DECREF(fno);
2411 return -1;
2412 }
2413 }
2414 else {
2415 PyErr_SetString(PyExc_TypeError,
2416 "argument must be an int, or have a fileno() method.");
2417 return -1;
2418 }
2419
2420 if (fd < 0) {
2421 PyErr_Format(PyExc_ValueError,
2422 "file descriptor cannot be a negative integer (%i)",
2423 fd);
2424 return -1;
2425 }
2426 return fd;
2427}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002428
Jack Jansen7b8c7542002-04-14 20:12:41 +00002429/* From here on we need access to the real fgets and fread */
2430#undef fgets
2431#undef fread
2432
2433/*
2434** Py_UniversalNewlineFgets is an fgets variation that understands
2435** all of \r, \n and \r\n conventions.
2436** The stream should be opened in binary mode.
2437** If fobj is NULL the routine always does newline conversion, and
2438** it may peek one char ahead to gobble the second char in \r\n.
2439** If fobj is non-NULL it must be a PyFileObject. In this case there
2440** is no readahead but in stead a flag is used to skip a following
2441** \n on the next read. Also, if the file is open in binary mode
2442** the whole conversion is skipped. Finally, the routine keeps track of
2443** the different types of newlines seen.
2444** Note that we need no error handling: fgets() treats error and eof
2445** identically.
2446*/
2447char *
2448Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2449{
2450 char *p = buf;
2451 int c;
2452 int newlinetypes = 0;
2453 int skipnextlf = 0;
2454 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002455
Jack Jansen7b8c7542002-04-14 20:12:41 +00002456 if (fobj) {
2457 if (!PyFile_Check(fobj)) {
2458 errno = ENXIO; /* What can you do... */
2459 return NULL;
2460 }
2461 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2462 if ( !univ_newline )
2463 return fgets(buf, n, stream);
2464 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2465 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2466 }
2467 FLOCKFILE(stream);
2468 c = 'x'; /* Shut up gcc warning */
2469 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2470 if (skipnextlf ) {
2471 skipnextlf = 0;
2472 if (c == '\n') {
2473 /* Seeing a \n here with skipnextlf true
2474 ** means we saw a \r before.
2475 */
2476 newlinetypes |= NEWLINE_CRLF;
2477 c = GETC(stream);
2478 if (c == EOF) break;
2479 } else {
2480 /*
2481 ** Note that c == EOF also brings us here,
2482 ** so we're okay if the last char in the file
2483 ** is a CR.
2484 */
2485 newlinetypes |= NEWLINE_CR;
2486 }
2487 }
2488 if (c == '\r') {
2489 /* A \r is translated into a \n, and we skip
2490 ** an adjacent \n, if any. We don't set the
2491 ** newlinetypes flag until we've seen the next char.
2492 */
2493 skipnextlf = 1;
2494 c = '\n';
2495 } else if ( c == '\n') {
2496 newlinetypes |= NEWLINE_LF;
2497 }
2498 *p++ = c;
2499 if (c == '\n') break;
2500 }
2501 if ( c == EOF && skipnextlf )
2502 newlinetypes |= NEWLINE_CR;
2503 FUNLOCKFILE(stream);
2504 *p = '\0';
2505 if (fobj) {
2506 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2507 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2508 } else if ( skipnextlf ) {
2509 /* If we have no file object we cannot save the
2510 ** skipnextlf flag. We have to readahead, which
2511 ** will cause a pause if we're reading from an
2512 ** interactive stream, but that is very unlikely
2513 ** unless we're doing something silly like
2514 ** execfile("/dev/tty").
2515 */
2516 c = GETC(stream);
2517 if ( c != '\n' )
2518 ungetc(c, stream);
2519 }
2520 if (p == buf)
2521 return NULL;
2522 return buf;
2523}
2524
2525/*
2526** Py_UniversalNewlineFread is an fread variation that understands
2527** all of \r, \n and \r\n conventions.
2528** The stream should be opened in binary mode.
2529** fobj must be a PyFileObject. In this case there
2530** is no readahead but in stead a flag is used to skip a following
2531** \n on the next read. Also, if the file is open in binary mode
2532** the whole conversion is skipped. Finally, the routine keeps track of
2533** the different types of newlines seen.
2534*/
2535size_t
Tim Peters058b1412002-04-21 07:29:14 +00002536Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002537 FILE *stream, PyObject *fobj)
2538{
Tim Peters058b1412002-04-21 07:29:14 +00002539 char *dst = buf;
2540 PyFileObject *f = (PyFileObject *)fobj;
2541 int newlinetypes, skipnextlf;
2542
2543 assert(buf != NULL);
2544 assert(stream != NULL);
2545
Jack Jansen7b8c7542002-04-14 20:12:41 +00002546 if (!fobj || !PyFile_Check(fobj)) {
2547 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002548 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002549 }
Tim Peters058b1412002-04-21 07:29:14 +00002550 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002551 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002552 newlinetypes = f->f_newlinetypes;
2553 skipnextlf = f->f_skipnextlf;
2554 /* Invariant: n is the number of bytes remaining to be filled
2555 * in the buffer.
2556 */
2557 while (n) {
2558 size_t nread;
2559 int shortread;
2560 char *src = dst;
2561
2562 nread = fread(dst, 1, n, stream);
2563 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002564 if (nread == 0)
2565 break;
2566
Tim Peterse1682a82002-04-21 18:15:20 +00002567 n -= nread; /* assuming 1 byte out for each in; will adjust */
2568 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002569 while (nread--) {
2570 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002571 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002572 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002573 *dst++ = '\n';
2574 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002575 }
2576 else if (skipnextlf && c == '\n') {
2577 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002578 skipnextlf = 0;
2579 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002580 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002581 }
2582 else {
2583 /* Normal char to be stored in buffer. Also
2584 * update the newlinetypes flag if either this
2585 * is an LF or the previous char was a CR.
2586 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002587 if (c == '\n')
2588 newlinetypes |= NEWLINE_LF;
2589 else if (skipnextlf)
2590 newlinetypes |= NEWLINE_CR;
2591 *dst++ = c;
2592 skipnextlf = 0;
2593 }
2594 }
Tim Peters058b1412002-04-21 07:29:14 +00002595 if (shortread) {
2596 /* If this is EOF, update type flags. */
2597 if (skipnextlf && feof(stream))
2598 newlinetypes |= NEWLINE_CR;
2599 break;
2600 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002601 }
Tim Peters058b1412002-04-21 07:29:14 +00002602 f->f_newlinetypes = newlinetypes;
2603 f->f_skipnextlf = skipnextlf;
2604 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002605}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002606
2607#ifdef __cplusplus
2608}
2609#endif