blob: 8cc829bacd02d987739fc4fd9d8f2cea21189f9f [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
Gregory P. Smithdd96db62008-06-09 04:58:54 +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);
Martin v. Löwis99815892008-06-01 07:20:46 +0000158 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000159
Neal Norwitzb337bb52006-07-17 00:55:45 +0000160 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000161 f->f_name = name;
162
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000163 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000164
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000165 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000166 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000167 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000168 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000169 f->f_univ_newline = (strchr(mode, 'U') != NULL);
170 f->f_newlinetypes = NEWLINE_UNKNOWN;
171 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000172 Py_INCREF(Py_None);
173 f->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +0000174 Py_INCREF(Py_None);
175 f->f_errors = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000176
Neal Norwitzb337bb52006-07-17 00:55:45 +0000177 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000180 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000182}
183
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000184/* check for known incorrect mode strings - problem is, platforms are
185 free to accept any mode characters they like and are supposed to
186 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000187 universal newline support is expressly forbidden by PEP 278.
188 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000189 won't know what it is. Non-zero return signals an exception */
190int
191_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000192{
Georg Brandl7b90e162006-05-18 07:01:27 +0000193 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000194 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000195
Georg Brandl7b90e162006-05-18 07:01:27 +0000196 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000197 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000198 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000199 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000200
Georg Brandl7b90e162006-05-18 07:01:27 +0000201 upos = strchr(mode, 'U');
202 if (upos) {
203 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000204
Georg Brandl7b90e162006-05-18 07:01:27 +0000205 if (mode[0] == 'w' || mode[0] == 'a') {
206 PyErr_Format(PyExc_ValueError, "universal newline "
207 "mode can only be used with modes "
208 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000209 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000210 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000211
212 if (mode[0] != 'r') {
213 memmove(mode+1, mode, strlen(mode)+1);
214 mode[0] = 'r';
215 }
216
217 if (!strchr(mode, 'b')) {
218 memmove(mode+2, mode+1, strlen(mode));
219 mode[1] = 'b';
220 }
221 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
222 PyErr_Format(PyExc_ValueError, "mode string must begin with "
223 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000224 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000225 }
226
227 return 0;
228}
229
Tim Peters59c9a642001-09-13 05:38:56 +0000230static PyObject *
231open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232{
Georg Brandl7b90e162006-05-18 07:01:27 +0000233 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000234 assert(f != NULL);
235 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000236#ifdef MS_WINDOWS
237 /* windows ignores the passed name in order to support Unicode */
238 assert(f->f_name != NULL);
239#else
Tim Peters59c9a642001-09-13 05:38:56 +0000240 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000241#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000242 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000243 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000244
Georg Brandl7b90e162006-05-18 07:01:27 +0000245 /* probably need to replace 'U' by 'rb' */
246 newmode = PyMem_MALLOC(strlen(mode) + 3);
247 if (!newmode) {
248 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000249 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000250 }
251 strcpy(newmode, mode);
252
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000253 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000254 f = NULL;
255 goto cleanup;
256 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000257
Tim Peters8fa45672001-09-13 21:01:29 +0000258 /* rexec.py can't stop a user from getting the file() constructor --
259 all they have to do is get *any* file object f, and then do
260 type(f). Here we prevent them from doing damage with it. */
261 if (PyEval_GetRestricted()) {
262 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000263 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000264 f = NULL;
265 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000266 }
Tim Petersa27a1502001-11-09 20:59:14 +0000267 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000268
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000269#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000270 if (PyUnicode_Check(f->f_name)) {
271 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000272 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000273 if (f->f_name && wmode) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000274 FILE_BEGIN_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000275 /* PyUnicode_AS_UNICODE OK without thread
276 lock as it is a simple dereference. */
277 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
278 PyUnicode_AS_UNICODE(wmode));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000279 FILE_END_ALLOW_THREADS(f)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000280 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000281 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000282 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000283#endif
284 if (NULL == f->f_fp && NULL != name) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000285 FILE_BEGIN_ALLOW_THREADS(f)
Georg Brandl7b90e162006-05-18 07:01:27 +0000286 f->f_fp = fopen(name, newmode);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000287 FILE_END_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000288 }
289
Guido van Rossuma08095a1991-02-13 23:25:27 +0000290 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000291#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000292 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
293 * across all Windows flavors. When it sets EINVAL varies
294 * across Windows flavors, the exact conditions aren't
295 * documented, and the answer lies in the OS's implementation
296 * of Win32's CreateFile function (whose source is secret).
297 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000298 * Starting with Visual Studio .NET 2005, EINVAL is correctly
299 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000300 */
301 if (errno == 0) /* bad mode string */
302 errno = EINVAL;
303 else if (errno == EINVAL) /* unknown, but not a mode string */
304 errno = ENOENT;
305#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000306 /* EINVAL is returned when an invalid filename or
307 * an invalid mode is supplied. */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000308 if (errno == EINVAL)
Gregory P. Smith887290d2008-03-18 00:20:01 +0000309 PyErr_Format(PyExc_IOError,
310 "invalid filename: %s or mode: %s",
311 name, mode);
Jeremy Hylton41c83212001-11-09 16:17:24 +0000312 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000313 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000314 f = NULL;
315 }
Tim Peters2ea91112002-04-08 04:13:12 +0000316 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000317 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000318
319cleanup:
320 PyMem_FREE(newmode);
321
Tim Peters59c9a642001-09-13 05:38:56 +0000322 return (PyObject *)f;
323}
324
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000325static PyObject *
326close_the_file(PyFileObject *f)
327{
328 int sts = 0;
329 int (*local_close)(FILE *);
330 FILE *local_fp = f->f_fp;
331 if (local_fp != NULL) {
332 local_close = f->f_close;
333 if (local_close != NULL && f->unlocked_count > 0) {
334 if (f->ob_refcnt > 0) {
335 PyErr_SetString(PyExc_IOError,
336 "close() called during concurrent "
337 "operation on the same file object.");
338 } else {
339 /* This should not happen unless someone is
340 * carelessly playing with the PyFileObject
341 * struct fields and/or its associated FILE
342 * pointer. */
343 PyErr_SetString(PyExc_SystemError,
344 "PyFileObject locking error in "
345 "destructor (refcnt <= 0 at close).");
346 }
347 return NULL;
348 }
349 /* NULL out the FILE pointer before releasing the GIL, because
350 * it will not be valid anymore after the close() function is
351 * called. */
352 f->f_fp = NULL;
353 if (local_close != NULL) {
354 Py_BEGIN_ALLOW_THREADS
355 errno = 0;
356 sts = (*local_close)(local_fp);
357 Py_END_ALLOW_THREADS
358 if (sts == EOF)
359 return PyErr_SetFromErrno(PyExc_IOError);
360 if (sts != 0)
361 return PyInt_FromLong((long)sts);
362 }
363 }
364 Py_RETURN_NONE;
365}
366
Tim Peters59c9a642001-09-13 05:38:56 +0000367PyObject *
368PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
369{
Tim Peters44410012001-09-14 03:26:08 +0000370 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
371 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000372 if (f != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000373 PyObject *o_name = PyString_FromString(name);
Neal Norwitzb337bb52006-07-17 00:55:45 +0000374 if (o_name == NULL)
375 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000376 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000377 Py_DECREF(f);
378 f = NULL;
379 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000380 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000381 }
382 return (PyObject *) f;
383}
384
385PyObject *
386PyFile_FromString(char *name, char *mode)
387{
388 extern int fclose(FILE *);
389 PyFileObject *f;
390
391 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
392 if (f != NULL) {
393 if (open_the_file(f, name, mode) == NULL) {
394 Py_DECREF(f);
395 f = NULL;
396 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Guido van Rossumb6775db1994-08-01 11:34:53 +0000401void
Fred Drakefd99de62000-07-09 05:02:18 +0000402PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000403{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000404 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000405 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000406 int type;
407 switch (bufsize) {
408 case 0:
409 type = _IONBF;
410 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000411#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000412 case 1:
413 type = _IOLBF;
414 bufsize = BUFSIZ;
415 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000416#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000417 default:
418 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000419#ifndef HAVE_SETVBUF
420 bufsize = BUFSIZ;
421#endif
422 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000423 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000424 fflush(file->f_fp);
425 if (type == _IONBF) {
426 PyMem_Free(file->f_setbuf);
427 file->f_setbuf = NULL;
428 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000429 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
430 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000431 }
432#ifdef HAVE_SETVBUF
433 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000434#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000435 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000436#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000437 }
438}
439
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000440/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000441 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000442
443int
444PyFile_SetEncoding(PyObject *f, const char *enc)
445{
Martin v. Löwis99815892008-06-01 07:20:46 +0000446 return PyFile_SetEncodingAndErrors(f, enc, NULL);
447}
448
449int
450PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
451{
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000452 PyFileObject *file = (PyFileObject*)f;
Martin v. Löwis99815892008-06-01 07:20:46 +0000453 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000454
455 assert(PyFile_Check(f));
Martin v. Löwis99815892008-06-01 07:20:46 +0000456 str = PyBytes_FromString(enc);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000457 if (!str)
458 return 0;
Martin v. Löwis99815892008-06-01 07:20:46 +0000459 if (errors) {
460 oerrors = PyString_FromString(errors);
461 if (!oerrors) {
462 Py_DECREF(str);
463 return 0;
464 }
465 } else {
466 oerrors = Py_None;
467 Py_INCREF(Py_None);
468 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000469 Py_DECREF(file->f_encoding);
470 file->f_encoding = str;
Martin v. Löwis99815892008-06-01 07:20:46 +0000471 Py_DECREF(file->f_errors);
472 file->f_errors = oerrors;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000473 return 1;
474}
475
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000477err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000478{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000480 return NULL;
481}
482
Thomas Woutersc45251a2006-02-12 11:53:32 +0000483/* Refuse regular file I/O if there's data in the iteration-buffer.
484 * Mixing them would cause data to arrive out of order, as the read*
485 * methods don't use the iteration buffer. */
486static PyObject *
487err_iterbuffered(void)
488{
489 PyErr_SetString(PyExc_ValueError,
490 "Mixing iteration and read methods would lose data");
491 return NULL;
492}
493
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000494static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000495
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496/* Methods */
497
498static void
Fred Drakefd99de62000-07-09 05:02:18 +0000499file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000501 PyObject *ret;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000502 if (f->weakreflist != NULL)
503 PyObject_ClearWeakRefs((PyObject *) f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000504 ret = close_the_file(f);
505 if (!ret) {
506 PySys_WriteStderr("close failed in file object destructor:\n");
507 PyErr_Print();
508 }
509 else {
510 Py_DECREF(ret);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000511 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000512 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000513 Py_XDECREF(f->f_name);
514 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000515 Py_XDECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000516 Py_XDECREF(f->f_errors);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000517 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000518 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519}
520
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000521static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000522file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000524 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000525#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000526 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000527 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000528 const char *name_str = name ? PyString_AsString(name) : "?";
529 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000530 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000531 name_str,
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000532 PyString_AsString(f->f_mode),
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000533 f);
534 Py_XDECREF(name);
535 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000536#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000537 } else {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000538 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000539 f->f_fp == NULL ? "closed" : "open",
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000540 PyString_AsString(f->f_name),
541 PyString_AsString(f->f_mode),
Barry Warsaw7ce36942001-08-24 18:34:26 +0000542 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000543 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544}
545
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000546static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000547file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000549 PyObject *sts = close_the_file(f);
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000550 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000551 f->f_setbuf = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000552 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Trent Mickf29f47b2000-08-11 19:02:59 +0000555
Guido van Rossumb8552162001-09-05 14:58:11 +0000556/* Our very own off_t-like type, 64-bit if possible */
557#if !defined(HAVE_LARGEFILE_SUPPORT)
558typedef off_t Py_off_t;
559#elif SIZEOF_OFF_T >= 8
560typedef off_t Py_off_t;
561#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000562typedef fpos_t Py_off_t;
563#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000564#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000565#endif
566
567
Trent Mickf29f47b2000-08-11 19:02:59 +0000568/* a portable fseek() function
569 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000570static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000571_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000572{
Guido van Rossumb8552162001-09-05 14:58:11 +0000573#if !defined(HAVE_LARGEFILE_SUPPORT)
574 return fseek(fp, offset, whence);
575#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000576 return fseeko(fp, offset, whence);
577#elif defined(HAVE_FSEEK64)
578 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000579#elif defined(__BEOS__)
580 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000581#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000582 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
583 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000584 fpos_t pos;
585 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000586 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000587#ifdef MS_WINDOWS
588 fflush(fp);
589 if (_lseeki64(fileno(fp), 0, 2) == -1)
590 return -1;
591#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000592 if (fseek(fp, 0, SEEK_END) != 0)
593 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000594#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000595 /* fall through */
596 case SEEK_CUR:
597 if (fgetpos(fp, &pos) != 0)
598 return -1;
599 offset += pos;
600 break;
601 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000602 }
603 return fsetpos(fp, &offset);
604#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000605#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000606#endif
607}
608
609
610/* a portable ftell() function
611 Return -1 on failure with errno set appropriately, current file
612 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000613static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000614_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000615{
Guido van Rossumb8552162001-09-05 14:58:11 +0000616#if !defined(HAVE_LARGEFILE_SUPPORT)
617 return ftell(fp);
618#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
619 return ftello(fp);
620#elif defined(HAVE_FTELL64)
621 return ftell64(fp);
622#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000623 fpos_t pos;
624 if (fgetpos(fp, &pos) != 0)
625 return -1;
626 return pos;
627#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000628#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000629#endif
630}
631
632
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000634file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000635{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000636 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000637 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000638 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000639 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000640
Guido van Rossumd7297e61992-07-06 14:19:26 +0000641 if (f->f_fp == NULL)
642 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000643 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000644 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000645 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000646 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000647 off_index = PyNumber_Index(offobj);
648 if (!off_index) {
649 if (!PyFloat_Check(offobj))
650 return NULL;
651 /* Deprecated in 2.6 */
652 PyErr_Clear();
Benjamin Petersonf19a7b92008-04-27 18:40:21 +0000653 if (PyErr_WarnEx(PyExc_DeprecationWarning,
654 "integer argument expected, got float",
655 1) < 0)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000656 return NULL;
657 off_index = offobj;
658 Py_INCREF(offobj);
659 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000660#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000661 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000662#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000663 offset = PyLong_Check(off_index) ?
664 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000665#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000666 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000667 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000668 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000669
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000670 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000671 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000672 ret = _portable_fseek(f->f_fp, offset, whence);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000673 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000674
Guido van Rossumff4949e1992-08-05 19:58:53 +0000675 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000677 clearerr(f->f_fp);
678 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000679 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000680 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 Py_INCREF(Py_None);
682 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000683}
684
Trent Mickf29f47b2000-08-11 19:02:59 +0000685
Guido van Rossumd7047b31995-01-02 19:07:15 +0000686#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000688file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000689{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000690 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000691 PyObject *newsizeobj = NULL;
692 Py_off_t initialpos;
693 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000694
Guido van Rossumd7047b31995-01-02 19:07:15 +0000695 if (f->f_fp == NULL)
696 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000697 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000698 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000699
Tim Petersf1827cf2003-09-07 03:30:18 +0000700 /* Get current file position. If the file happens to be open for
701 * update and the last operation was an input operation, C doesn't
702 * define what the later fflush() will do, but we promise truncate()
703 * won't change the current position (and fflush() *does* change it
704 * then at least on Windows). The easiest thing is to capture
705 * current pos now and seek back to it at the end.
706 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000707 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000708 errno = 0;
709 initialpos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000710 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000711 if (initialpos == -1)
712 goto onioerror;
713
Tim Petersfb05db22002-03-11 00:24:00 +0000714 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000715 * specified value.
716 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000717 if (newsizeobj != NULL) {
718#if !defined(HAVE_LARGEFILE_SUPPORT)
719 newsize = PyInt_AsLong(newsizeobj);
720#else
721 newsize = PyLong_Check(newsizeobj) ?
722 PyLong_AsLongLong(newsizeobj) :
723 PyInt_AsLong(newsizeobj);
724#endif
725 if (PyErr_Occurred())
726 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000727 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000728 else /* default to current position */
729 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000730
Tim Petersf1827cf2003-09-07 03:30:18 +0000731 /* Flush the stream. We're mixing stream-level I/O with lower-level
732 * I/O, and a flush may be necessary to synch both platform views
733 * of the current file state.
734 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000735 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000736 errno = 0;
737 ret = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000738 FILE_END_ALLOW_THREADS(f)
Tim Petersfb05db22002-03-11 00:24:00 +0000739 if (ret != 0)
740 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000741
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000742#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000743 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000744 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000745 {
Tim Petersfb05db22002-03-11 00:24:00 +0000746 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000747
Tim Petersf1827cf2003-09-07 03:30:18 +0000748 /* Have to move current pos to desired endpoint on Windows. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000749 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000750 errno = 0;
751 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000752 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000753 if (ret)
754 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000755
Tim Peters8f01b682002-03-12 03:04:44 +0000756 /* Truncate. Note that this may grow the file! */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000757 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters8f01b682002-03-12 03:04:44 +0000758 errno = 0;
759 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000760 ret = hFile == (HANDLE)-1;
761 if (ret == 0) {
762 ret = SetEndOfFile(hFile) == 0;
763 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000764 errno = EACCES;
765 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000766 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000767 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000768 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000769 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000770#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000771 FILE_BEGIN_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000772 errno = 0;
773 ret = ftruncate(fileno(f->f_fp), newsize);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000774 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000775 if (ret != 0)
776 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000777#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000778
Tim Petersf1827cf2003-09-07 03:30:18 +0000779 /* Restore original file position. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000780 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000781 errno = 0;
782 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000783 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000784 if (ret)
785 goto onioerror;
786
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000787 Py_INCREF(Py_None);
788 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000789
790onioerror:
791 PyErr_SetFromErrno(PyExc_IOError);
792 clearerr(f->f_fp);
793 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000794}
795#endif /* HAVE_FTRUNCATE */
796
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000798file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000799{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000800 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000801
Guido van Rossumd7297e61992-07-06 14:19:26 +0000802 if (f->f_fp == NULL)
803 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000804 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000805 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000806 pos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000807 FILE_END_ALLOW_THREADS(f)
808
Trent Mickf29f47b2000-08-11 19:02:59 +0000809 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000810 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000811 clearerr(f->f_fp);
812 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000813 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000814 if (f->f_skipnextlf) {
815 int c;
816 c = GETC(f->f_fp);
817 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000818 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000819 pos++;
820 f->f_skipnextlf = 0;
821 } else if (c != EOF) ungetc(c, f->f_fp);
822 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000823#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000824 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000825#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000826 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000827#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000828}
829
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000830static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000831file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000832{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000833 if (f->f_fp == NULL)
834 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000836}
837
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000838static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000839file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000840{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000841 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000842
Guido van Rossumd7297e61992-07-06 14:19:26 +0000843 if (f->f_fp == NULL)
844 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000845 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000846 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000847 res = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000848 FILE_END_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000849 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000850 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000851 clearerr(f->f_fp);
852 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000853 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000854 Py_INCREF(Py_None);
855 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000856}
857
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000858static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000859file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000860{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000861 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000862 if (f->f_fp == NULL)
863 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000864 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000865 res = isatty((int)fileno(f->f_fp));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000866 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000867 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000868}
869
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000870
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000871#if BUFSIZ < 8192
872#define SMALLCHUNK 8192
873#else
874#define SMALLCHUNK BUFSIZ
875#endif
876
Guido van Rossum3c259041999-01-14 19:00:14 +0000877#if SIZEOF_INT < 4
878#define BIGCHUNK (512 * 32)
879#else
880#define BIGCHUNK (512 * 1024)
881#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000882
883static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000884new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000885{
886#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000887 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000888 struct stat st;
889 if (fstat(fileno(f->f_fp), &st) == 0) {
890 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000891 /* The following is not a bug: we really need to call lseek()
892 *and* ftell(). The reason is that some stdio libraries
893 mistakenly flush their buffer when ftell() is called and
894 the lseek() call it makes fails, thereby throwing away
895 data that cannot be recovered in any way. To avoid this,
896 we first test lseek(), and only call ftell() if lseek()
897 works. We can't use the lseek() value either, because we
898 need to take the amount of buffered data into account.
899 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000900 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000901 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000902 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000903 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000904 if (pos < 0)
905 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000906 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000907 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000908 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000909 }
910#endif
911 if (currentsize > SMALLCHUNK) {
912 /* Keep doubling until we reach BIGCHUNK;
913 then keep adding BIGCHUNK. */
914 if (currentsize <= BIGCHUNK)
915 return currentsize + currentsize;
916 else
917 return currentsize + BIGCHUNK;
918 }
919 return currentsize + SMALLCHUNK;
920}
921
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000922#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
923#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
924#else
925#ifdef EWOULDBLOCK
926#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
927#else
928#ifdef EAGAIN
929#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
930#else
931#define BLOCKED_ERRNO(x) 0
932#endif
933#endif
934#endif
935
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000936static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000937file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000938{
Guido van Rossum789a1611997-05-10 22:33:55 +0000939 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000940 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000942
Guido van Rossumd7297e61992-07-06 14:19:26 +0000943 if (f->f_fp == NULL)
944 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000945 /* refuse to mix with f.next() */
946 if (f->f_buf != NULL &&
947 (f->f_bufend - f->f_bufptr) > 0 &&
948 f->f_buf[0] != '\0')
949 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000950 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000951 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000952 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000953 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000954 else
955 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +0000956 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000957 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000958 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000959 return NULL;
960 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000961 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000962 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000963 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000964 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000965 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000966 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +0000967 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000968 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000969 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000970 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +0000971 if (chunksize == 0) {
972 if (!ferror(f->f_fp))
973 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000974 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000975 /* When in non-blocking mode, data shouldn't
976 * be discarded if a blocking signal was
977 * received. That will also happen if
978 * chunksize != 0, but bytesread < buffersize. */
979 if (bytesread > 0 && BLOCKED_ERRNO(errno))
980 break;
981 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000982 Py_DECREF(v);
983 return NULL;
984 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000985 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000986 if (bytesread < buffersize) {
987 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000988 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000989 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000990 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000991 buffersize = new_buffersize(f, buffersize);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000992 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000993 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000994 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000995 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000996 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000997 }
998 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000999 if (bytesread != buffersize)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001000 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001001 return v;
1002}
1003
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001004static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001005file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001006{
1007 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001008 Py_ssize_t ntodo;
1009 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +00001010
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001011 if (f->f_fp == NULL)
1012 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001013 /* refuse to mix with f.next() */
1014 if (f->f_buf != NULL &&
1015 (f->f_bufend - f->f_bufptr) > 0 &&
1016 f->f_buf[0] != '\0')
1017 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +00001018 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001019 return NULL;
1020 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001021 while (ntodo > 0) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001022 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001023 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +00001024 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001025 (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001026 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001027 if (nnow == 0) {
1028 if (!ferror(f->f_fp))
1029 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001030 PyErr_SetFromErrno(PyExc_IOError);
1031 clearerr(f->f_fp);
1032 return NULL;
1033 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001034 ndone += nnow;
1035 ntodo -= nnow;
1036 }
Neal Norwitz076d1e02006-08-21 18:20:10 +00001037 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001038}
1039
Tim Peters86821b22001-01-07 21:19:34 +00001040/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001041Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001042
1043Under MSVC 6:
1044
Tim Peters1c733232001-01-08 04:02:07 +00001045+ MS threadsafe getc is very slow (multiple layers of function calls before+
1046 after each character, to lock+unlock the stream).
1047+ The stream-locking functions are MS-internal -- can't access them from user
1048 code.
1049+ There's nothing Tim could find in the MS C or platform SDK libraries that
1050 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001051+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1052
1053So we use fgets for speed(!), despite that it's painful.
1054
1055MS realloc is also slow.
1056
Tim Petersf29b64d2001-01-15 06:33:19 +00001057Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1058have):
1059 Linux a wash
1060 Solaris a wash
1061 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001062
Tim Petersf29b64d2001-01-15 06:33:19 +00001063CAUTION: The C std isn't clear about this: in those cases where fgets
1064writes something into the buffer, can it write into any position beyond the
1065required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1066known on which it does; and it would be a strange way to code fgets. Still,
1067getline_via_fgets may not work correctly if it does. The std test
1068test_bufio.py should fail if platform fgets() routinely writes beyond the
1069trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001070**************************************************************************/
1071
Tim Petersf29b64d2001-01-15 06:33:19 +00001072/* Use this routine if told to, or by default on non-get_unlocked()
1073 * platforms unless told not to. Yikes! Let's spell that out:
1074 * On a platform with getc_unlocked():
1075 * By default, use getc_unlocked().
1076 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1077 * On a platform without getc_unlocked():
1078 * By default, use fgets().
1079 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1080 */
1081#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1082#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001083#endif
1084
Tim Petersf29b64d2001-01-15 06:33:19 +00001085#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1086#undef USE_FGETS_IN_GETLINE
1087#endif
1088
1089#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001090static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001091getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001092{
Tim Peters15b83852001-01-08 00:53:12 +00001093/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001094 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1095 * to fill this much of the buffer with a known value in order to figure out
1096 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1097 * than "most" lines, we waste time filling unused buffer slots. 100 is
1098 * surely adequate for most peoples' email archives, chewing over source code,
1099 * etc -- "regular old text files".
1100 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1101 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1102 * cautions about boosting that. 300 was chosen because the worst real-life
1103 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1104 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001105 */
Tim Peters142297a2001-01-15 10:36:56 +00001106#define INITBUFSIZE 100
1107#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001108 char* p; /* temp */
1109 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001110 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001111 char* pvfree; /* address of next free slot */
1112 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001113 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1114 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001115 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001116 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001117
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001118 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001119 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001120 */
Tim Peters142297a2001-01-15 10:36:56 +00001121 total_v_size = INITBUFSIZE; /* start small and pray */
1122 pvfree = buf;
1123 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001124 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters142297a2001-01-15 10:36:56 +00001125 pvend = buf + total_v_size;
1126 nfree = pvend - pvfree;
1127 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001128 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1129 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001130 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001131
Tim Peters142297a2001-01-15 10:36:56 +00001132 if (p == NULL) {
1133 clearerr(fp);
1134 if (PyErr_CheckSignals())
1135 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001136 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001137 return v;
1138 }
Tim Peters142297a2001-01-15 10:36:56 +00001139 /* fgets read *something* */
1140 p = memchr(pvfree, '\n', nfree);
1141 if (p != NULL) {
1142 /* Did the \n come from fgets or from us?
1143 * Since fgets stops at the first \n, and then writes
1144 * \0, if it's from fgets a \0 must be next. But if
1145 * that's so, it could not have come from us, since
1146 * the \n's we filled the buffer with have only more
1147 * \n's to the right.
1148 */
1149 if (p+1 < pvend && *(p+1) == '\0') {
1150 /* It's from fgets: we win! In particular,
1151 * we haven't done any mallocs yet, and can
1152 * build the final result on the first try.
1153 */
1154 ++p; /* include \n from fgets */
1155 }
1156 else {
1157 /* Must be from us: fgets didn't fill the
1158 * buffer and didn't find a newline, so it
1159 * must be the last and newline-free line of
1160 * the file.
1161 */
1162 assert(p > pvfree && *(p-1) == '\0');
1163 --p; /* don't include \0 from fgets */
1164 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001165 v = PyString_FromStringAndSize(buf, p - buf);
Tim Peters142297a2001-01-15 10:36:56 +00001166 return v;
1167 }
1168 /* yuck: fgets overwrote all the newlines, i.e. the entire
1169 * buffer. So this line isn't over yet, or maybe it is but
1170 * we're exactly at EOF. If we haven't already, try using the
1171 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001172 */
Tim Peters142297a2001-01-15 10:36:56 +00001173 assert(*(pvend-1) == '\0');
1174 if (pvfree == buf) {
1175 pvfree = pvend - 1; /* overwrite trailing null */
1176 total_v_size = MAXBUFSIZE;
1177 }
1178 else
1179 break;
Tim Peters86821b22001-01-07 21:19:34 +00001180 }
Tim Peters142297a2001-01-15 10:36:56 +00001181
1182 /* The stack buffer isn't big enough; malloc a string object and read
1183 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001184 */
Tim Petersddea2082002-03-23 10:03:50 +00001185 total_v_size = MAXBUFSIZE << 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001186 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001187 if (v == NULL)
1188 return v;
1189 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001190 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1191 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001192
1193 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001194 * after setting p one beyond the end of the line. The code here is
1195 * very much like the code above, except reads into v's buffer; see
1196 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001197 */
1198 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001199 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001200 pvend = BUF(v) + total_v_size;
1201 nfree = pvend - pvfree;
1202 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001203 assert(nfree < INT_MAX);
1204 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001205 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001206
1207 if (p == NULL) {
1208 clearerr(fp);
1209 if (PyErr_CheckSignals()) {
1210 Py_DECREF(v);
1211 return NULL;
1212 }
1213 p = pvfree;
1214 break;
1215 }
Tim Peters86821b22001-01-07 21:19:34 +00001216 p = memchr(pvfree, '\n', nfree);
1217 if (p != NULL) {
1218 if (p+1 < pvend && *(p+1) == '\0') {
1219 /* \n came from fgets */
1220 ++p;
1221 break;
1222 }
1223 /* \n came from us; last line of file, no newline */
1224 assert(p > pvfree && *(p-1) == '\0');
1225 --p;
1226 break;
1227 }
1228 /* expand buffer and try again */
1229 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001230 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001231 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001232 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001233 /* check for overflow */
1234 if (total_v_size <= prev_v_size ||
1235 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001236 PyErr_SetString(PyExc_OverflowError,
1237 "line is longer than a Python string can hold");
1238 Py_DECREF(v);
1239 return NULL;
1240 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001241 if (_PyString_Resize(&v, (int)total_v_size) < 0)
Tim Peters86821b22001-01-07 21:19:34 +00001242 return NULL;
1243 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001244 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001245 }
1246 if (BUF(v) + total_v_size != p)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001247 _PyString_Resize(&v, p - BUF(v));
Tim Peters86821b22001-01-07 21:19:34 +00001248 return v;
1249#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001250#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001251}
Tim Petersf29b64d2001-01-15 06:33:19 +00001252#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001253
Guido van Rossum0bd24411991-04-04 15:21:57 +00001254/* Internal routine to get a line.
1255 Size argument interpretation:
1256 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001257 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001258*/
1259
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001260static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001261get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001262{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001263 FILE *fp = f->f_fp;
1264 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001265 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001266 size_t total_v_size; /* total # of slots in buffer */
1267 size_t used_v_size; /* # used slots in buffer */
1268 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001269 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001270 int newlinetypes = f->f_newlinetypes;
1271 int skipnextlf = f->f_skipnextlf;
1272 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001273
Jack Jansen7b8c7542002-04-14 20:12:41 +00001274#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001275 if (n <= 0 && !univ_newline )
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001276 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001277#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001278 total_v_size = n > 0 ? n : 100;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001279 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001280 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001281 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001282 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001283 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001284
Guido van Rossumce5ba841991-03-06 13:06:18 +00001285 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001286 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001287 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001288 if (univ_newline) {
1289 c = 'x'; /* Shut up gcc warning */
1290 while ( buf != end && (c = GETC(fp)) != EOF ) {
1291 if (skipnextlf ) {
1292 skipnextlf = 0;
1293 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001294 /* Seeing a \n here with
1295 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001296 * saw a \r before.
1297 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001298 newlinetypes |= NEWLINE_CRLF;
1299 c = GETC(fp);
1300 if (c == EOF) break;
1301 } else {
1302 newlinetypes |= NEWLINE_CR;
1303 }
1304 }
1305 if (c == '\r') {
1306 skipnextlf = 1;
1307 c = '\n';
1308 } else if ( c == '\n')
1309 newlinetypes |= NEWLINE_LF;
1310 *buf++ = c;
1311 if (c == '\n') break;
1312 }
1313 if ( c == EOF && skipnextlf )
1314 newlinetypes |= NEWLINE_CR;
1315 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001316 while ((c = GETC(fp)) != EOF &&
1317 (*buf++ = c) != '\n' &&
1318 buf != end)
1319 ;
1320 FUNLOCKFILE(fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001321 FILE_END_ALLOW_THREADS(f)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001322 f->f_newlinetypes = newlinetypes;
1323 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001324 if (c == '\n')
1325 break;
1326 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001327 if (ferror(fp)) {
1328 PyErr_SetFromErrno(PyExc_IOError);
1329 clearerr(fp);
1330 Py_DECREF(v);
1331 return NULL;
1332 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001333 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001334 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001335 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001336 return NULL;
1337 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001338 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001339 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001340 /* Must be because buf == end */
1341 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001342 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001343 used_v_size = total_v_size;
1344 increment = total_v_size >> 2; /* mild exponential growth */
1345 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001346 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001347 PyErr_SetString(PyExc_OverflowError,
1348 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001349 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001350 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001351 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001352 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001353 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001354 buf = BUF(v) + used_v_size;
1355 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001356 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001357
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001358 used_v_size = buf - BUF(v);
1359 if (used_v_size != total_v_size)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001360 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001361 return v;
1362}
1363
Guido van Rossum0bd24411991-04-04 15:21:57 +00001364/* External C interface */
1365
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001366PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001367PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001368{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001369 PyObject *result;
1370
Guido van Rossum3165fe61992-09-25 21:59:05 +00001371 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001373 return NULL;
1374 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001375
1376 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001377 PyFileObject *fo = (PyFileObject *)f;
1378 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001379 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001380 /* refuse to mix with f.next() */
1381 if (fo->f_buf != NULL &&
1382 (fo->f_bufend - fo->f_bufptr) > 0 &&
1383 fo->f_buf[0] != '\0')
1384 return err_iterbuffered();
1385 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001386 }
1387 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388 PyObject *reader;
1389 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001390
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001391 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001392 if (reader == NULL)
1393 return NULL;
1394 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001395 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001396 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001397 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001398 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001399 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001400 return NULL;
1401 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001402 result = PyEval_CallObject(reader, args);
1403 Py_DECREF(reader);
1404 Py_DECREF(args);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001405 if (result != NULL && !PyString_Check(result) &&
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001406 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001407 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001408 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001409 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001410 "object.readline() returned non-string");
1411 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001412 }
1413
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001414 if (n < 0 && result != NULL && PyString_Check(result)) {
1415 char *s = PyString_AS_STRING(result);
1416 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001417 if (len == 0) {
1418 Py_DECREF(result);
1419 result = NULL;
1420 PyErr_SetString(PyExc_EOFError,
1421 "EOF when reading a line");
1422 }
1423 else if (s[len-1] == '\n') {
1424 if (result->ob_refcnt == 1)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001425 _PyString_Resize(&result, len-1);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001426 else {
1427 PyObject *v;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001428 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001430 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001431 }
1432 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001433 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001434#ifdef Py_USING_UNICODE
1435 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1436 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001437 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001438 if (len == 0) {
1439 Py_DECREF(result);
1440 result = NULL;
1441 PyErr_SetString(PyExc_EOFError,
1442 "EOF when reading a line");
1443 }
1444 else if (s[len-1] == '\n') {
1445 if (result->ob_refcnt == 1)
1446 PyUnicode_Resize(&result, len-1);
1447 else {
1448 PyObject *v;
1449 v = PyUnicode_FromUnicode(s, len-1);
1450 Py_DECREF(result);
1451 result = v;
1452 }
1453 }
1454 }
1455#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001456 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001457}
1458
1459/* Python method */
1460
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001461static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001462file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001463{
Guido van Rossum789a1611997-05-10 22:33:55 +00001464 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001465
Guido van Rossumd7297e61992-07-06 14:19:26 +00001466 if (f->f_fp == NULL)
1467 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001468 /* refuse to mix with f.next() */
1469 if (f->f_buf != NULL &&
1470 (f->f_bufend - f->f_bufptr) > 0 &&
1471 f->f_buf[0] != '\0')
1472 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001473 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001474 return NULL;
1475 if (n == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001476 return PyString_FromString("");
Guido van Rossum789a1611997-05-10 22:33:55 +00001477 if (n < 0)
1478 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001479 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001480}
1481
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001482static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001483file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001484{
Guido van Rossum789a1611997-05-10 22:33:55 +00001485 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001486 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001487 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001488 char small_buffer[SMALLCHUNK];
1489 char *buffer = small_buffer;
1490 size_t buffersize = SMALLCHUNK;
1491 PyObject *big_buffer = NULL;
1492 size_t nfilled = 0;
1493 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001494 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001495 char *p, *q, *end;
1496 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001497 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001498
Guido van Rossumd7297e61992-07-06 14:19:26 +00001499 if (f->f_fp == NULL)
1500 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001501 /* refuse to mix with f.next() */
1502 if (f->f_buf != NULL &&
1503 (f->f_bufend - f->f_bufptr) > 0 &&
1504 f->f_buf[0] != '\0')
1505 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001506 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001507 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001508 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001509 return NULL;
1510 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001511 if (shortread)
1512 nread = 0;
1513 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001514 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001515 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001516 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001517 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001518 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001519 shortread = (nread < buffersize-nfilled);
1520 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001521 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001522 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001523 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001524 break;
1525 PyErr_SetFromErrno(PyExc_IOError);
1526 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001527 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001528 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001529 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001530 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001531 if (p == NULL) {
1532 /* Need a larger buffer to fit this line */
1533 nfilled += nread;
1534 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001535 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001536 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001537 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001538 goto error;
1539 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001540 if (big_buffer == NULL) {
1541 /* Create the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001542 big_buffer = PyString_FromStringAndSize(
Guido van Rossum6263d541997-05-10 22:07:25 +00001543 NULL, buffersize);
1544 if (big_buffer == NULL)
1545 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001546 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001547 memcpy(buffer, small_buffer, nfilled);
1548 }
1549 else {
1550 /* Grow the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001551 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
Jack Jansen7b8c7542002-04-14 20:12:41 +00001552 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001553 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001554 }
1555 continue;
1556 }
1557 end = buffer+nfilled+nread;
1558 q = buffer;
1559 do {
1560 /* Process complete lines */
1561 p++;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001562 line = PyString_FromStringAndSize(q, p-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001563 if (line == NULL)
1564 goto error;
1565 err = PyList_Append(list, line);
1566 Py_DECREF(line);
1567 if (err != 0)
1568 goto error;
1569 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001570 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001571 } while (p != NULL);
1572 /* Move the remaining incomplete line to the start */
1573 nfilled = end-q;
1574 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001575 if (sizehint > 0)
1576 if (totalread >= (size_t)sizehint)
1577 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001578 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001579 if (nfilled != 0) {
1580 /* Partial last line */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001581 line = PyString_FromStringAndSize(buffer, nfilled);
Guido van Rossum6263d541997-05-10 22:07:25 +00001582 if (line == NULL)
1583 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001584 if (sizehint > 0) {
1585 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001586 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001587 if (rest == NULL) {
1588 Py_DECREF(line);
1589 goto error;
1590 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001591 PyString_Concat(&line, rest);
Guido van Rossum789a1611997-05-10 22:33:55 +00001592 Py_DECREF(rest);
1593 if (line == NULL)
1594 goto error;
1595 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001596 err = PyList_Append(list, line);
1597 Py_DECREF(line);
1598 if (err != 0)
1599 goto error;
1600 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001601
1602cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001603 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001604 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001605
1606error:
1607 Py_CLEAR(list);
1608 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001609}
1610
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001611static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001612file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001613{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001614 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001615 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001616 if (f->f_fp == NULL)
1617 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001618 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001619 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001620 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001621 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001622 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001623 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001624 FILE_END_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001625 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001626 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001627 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001628 return NULL;
1629 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001630 Py_INCREF(Py_None);
1631 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001632}
1633
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001634static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001635file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001636{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001637#define CHUNKSIZE 1000
1638 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001639 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001640 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001641 int index, islist;
1642 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001643
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001644 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001645 if (f->f_fp == NULL)
1646 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001647
1648 result = NULL;
1649 list = NULL;
1650 islist = PyList_Check(seq);
1651 if (islist)
1652 it = NULL;
1653 else {
1654 it = PyObject_GetIter(seq);
1655 if (it == NULL) {
1656 PyErr_SetString(PyExc_TypeError,
1657 "writelines() requires an iterable argument");
1658 return NULL;
1659 }
1660 /* From here on, fail by going to error, to reclaim "it". */
1661 list = PyList_New(CHUNKSIZE);
1662 if (list == NULL)
1663 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001664 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001665
1666 /* Strategy: slurp CHUNKSIZE lines into a private list,
1667 checking that they are all strings, then write that list
1668 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001669 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001670 if (islist) {
1671 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001672 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001673 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001674 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001675 j = PyList_GET_SIZE(list);
1676 }
1677 else {
1678 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001679 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001680 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001681 if (PyErr_Occurred())
1682 goto error;
1683 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001684 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001685 PyList_SetItem(list, j, line);
1686 }
1687 }
1688 if (j == 0)
1689 break;
1690
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001691 /* Check that all entries are indeed strings. If not,
1692 apply the same rules as for file.write() and
1693 convert the results to strings. This is slow, but
1694 seems to be the only way since all conversion APIs
1695 could potentially execute Python code. */
1696 for (i = 0; i < j; i++) {
1697 PyObject *v = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001698 if (!PyString_Check(v)) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001699 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001700 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001701 PyObject_AsReadBuffer(v,
1702 (const void**)&buffer,
1703 &len)) ||
1704 PyObject_AsCharBuffer(v,
1705 &buffer,
1706 &len))) {
1707 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001708 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001709 goto error;
1710 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001711 line = PyString_FromStringAndSize(buffer,
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001712 len);
1713 if (line == NULL)
1714 goto error;
1715 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001716 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001717 }
1718 }
1719
1720 /* Since we are releasing the global lock, the
1721 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001722 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001723 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001724 errno = 0;
1725 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001726 line = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001727 len = PyString_GET_SIZE(line);
1728 nwritten = fwrite(PyString_AS_STRING(line),
Guido van Rossumee70ad12000-03-13 16:27:06 +00001729 1, len, f->f_fp);
1730 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001731 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001732 PyErr_SetFromErrno(PyExc_IOError);
1733 clearerr(f->f_fp);
1734 goto error;
1735 }
1736 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001737 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001738
1739 if (j < CHUNKSIZE)
1740 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001741 }
1742
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001743 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001744 result = Py_None;
1745 error:
1746 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001747 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001748 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001749#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001750}
1751
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001752static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001753file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001754{
1755 if (f->f_fp == NULL)
1756 return err_closed();
1757 Py_INCREF(f);
1758 return (PyObject *)f;
1759}
1760
Georg Brandl98b40ad2006-06-08 14:50:21 +00001761static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001762file_xreadlines(PyFileObject *f)
1763{
1764 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1765 "try 'for line in f' instead", 1) < 0)
1766 return NULL;
1767 return file_self(f);
1768}
1769
1770static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001771file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001772{
Georg Brandlad61bc82008-02-23 15:11:18 +00001773 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001774 if (!ret)
1775 /* If error occurred, pass through */
1776 return NULL;
1777 Py_DECREF(ret);
1778 /* We cannot return the result of close since a true
1779 * value will be interpreted as "yes, swallow the
1780 * exception if one was raised inside the with block". */
1781 Py_RETURN_NONE;
1782}
1783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001784PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001785"readline([size]) -> next line from the file, as a string.\n"
1786"\n"
1787"Retain newline. A non-negative size argument limits the maximum\n"
1788"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001789"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001791PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001792"read([size]) -> read at most size bytes, returned as a string.\n"
1793"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001794"If the size argument is negative or omitted, read until EOF is reached.\n"
1795"Notice that when in non-blocking mode, less data than what was requested\n"
1796"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001798PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001799"write(str) -> None. Write string str to file.\n"
1800"\n"
1801"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001802"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001803
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001804PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001805"fileno() -> integer \"file descriptor\".\n"
1806"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001807"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001809PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001810"seek(offset[, whence]) -> None. Move to new file position.\n"
1811"\n"
1812"Argument offset is a byte count. Optional argument whence defaults to\n"
1813"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1814"(move relative to current position, positive or negative), and 2 (move\n"
1815"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001816"seeking beyond the end of a file). If the file is opened in text mode,\n"
1817"only offsets returned by tell() are legal. Use of other offsets causes\n"
1818"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001819"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001820"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001821
Guido van Rossumd7047b31995-01-02 19:07:15 +00001822#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001823PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001824"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1825"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001826"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001827#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001829PyDoc_STRVAR(tell_doc,
1830"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001832PyDoc_STRVAR(readinto_doc,
1833"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001834
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001835PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001836"readlines([size]) -> list of strings, each a line from the file.\n"
1837"\n"
1838"Call readline() repeatedly and return a list of the lines so read.\n"
1839"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001840"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001842PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001843"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001844"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001845"For backward compatibility. File objects now include the performance\n"
1846"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001848PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001849"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001850"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001851"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001852"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001854PyDoc_STRVAR(flush_doc,
1855"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001857PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001858"close() -> None or (perhaps) an integer. Close the file.\n"
1859"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001860"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001861"further I/O operations. close() may be called more than once without\n"
1862"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001863"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001864
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001865PyDoc_STRVAR(isatty_doc,
1866"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001867
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001868PyDoc_STRVAR(enter_doc,
1869 "__enter__() -> self.");
1870
Georg Brandl98b40ad2006-06-08 14:50:21 +00001871PyDoc_STRVAR(exit_doc,
1872 "__exit__(*excinfo) -> None. Closes the file.");
1873
Tim Petersefc3a3a2001-09-20 07:55:22 +00001874static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001875 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1876 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1877 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1878 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1879 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001880#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001881 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001882#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001883 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1884 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
Georg Brandla9916b52008-05-17 22:11:54 +00001885 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
1886 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
1887 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001888 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1889 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1890 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001891 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00001892 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001893 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001894};
1895
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001896#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001897
Guido van Rossum6f799372001-09-20 20:46:19 +00001898static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00001899 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001900 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001901 {"name", T_OBJECT, OFF(f_name), RO,
1902 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001903 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1904 "file encoding"},
Martin v. Löwis99815892008-06-01 07:20:46 +00001905 {"errors", T_OBJECT, OFF(f_errors), RO,
1906 "Unicode error handler"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001907 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001908 {NULL} /* Sentinel */
1909};
1910
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001913{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001914 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001915}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001916static PyObject *
1917get_newlines(PyFileObject *f, void *closure)
1918{
1919 switch (f->f_newlinetypes) {
1920 case NEWLINE_UNKNOWN:
1921 Py_INCREF(Py_None);
1922 return Py_None;
1923 case NEWLINE_CR:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001924 return PyString_FromString("\r");
Jack Jansen7b8c7542002-04-14 20:12:41 +00001925 case NEWLINE_LF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001926 return PyString_FromString("\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00001927 case NEWLINE_CR|NEWLINE_LF:
1928 return Py_BuildValue("(ss)", "\r", "\n");
1929 case NEWLINE_CRLF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001930 return PyString_FromString("\r\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00001931 case NEWLINE_CR|NEWLINE_CRLF:
1932 return Py_BuildValue("(ss)", "\r", "\r\n");
1933 case NEWLINE_LF|NEWLINE_CRLF:
1934 return Py_BuildValue("(ss)", "\n", "\r\n");
1935 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1936 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1937 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001938 PyErr_Format(PyExc_SystemError,
1939 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001940 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001941 return NULL;
1942 }
1943}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001944
Georg Brandl65bb42d2008-03-21 20:38:24 +00001945static PyObject *
1946get_softspace(PyFileObject *f, void *closure)
1947{
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00001948 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00001949 return NULL;
1950 return PyInt_FromLong(f->f_softspace);
1951}
1952
1953static int
1954set_softspace(PyFileObject *f, PyObject *value)
1955{
1956 int new;
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00001957 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00001958 return -1;
1959
1960 if (value == NULL) {
1961 PyErr_SetString(PyExc_TypeError,
1962 "can't delete softspace attribute");
1963 return -1;
1964 }
1965
1966 new = PyInt_AsLong(value);
1967 if (new == -1 && PyErr_Occurred())
1968 return -1;
1969 f->f_softspace = new;
1970 return 0;
1971}
1972
Guido van Rossum32d34c82001-09-20 21:45:26 +00001973static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001974 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001975 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001976 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00001977 {"softspace", (getter)get_softspace, (setter)set_softspace,
1978 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979 {0},
1980};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001981
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001982static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001983drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001984{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001985 if (f->f_buf != NULL) {
1986 PyMem_Free(f->f_buf);
1987 f->f_buf = NULL;
1988 }
Guido van Rossum65967252001-04-21 13:20:18 +00001989}
1990
Tim Petersf1827cf2003-09-07 03:30:18 +00001991/* Make sure that file has a readahead buffer with at least one byte
1992 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00001993 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001994static int
1995readahead(PyFileObject *f, int bufsize)
1996{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001998
1999 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00002000 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002001 return 0;
2002 else
2003 drop_readahead(f);
2004 }
Anthony Baxter377be112006-04-11 06:54:30 +00002005 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00002006 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002007 return -1;
2008 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002009 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002010 errno = 0;
2011 chunksize = Py_UniversalNewlineFread(
2012 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002013 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002014 if (chunksize == 0) {
2015 if (ferror(f->f_fp)) {
2016 PyErr_SetFromErrno(PyExc_IOError);
2017 clearerr(f->f_fp);
2018 drop_readahead(f);
2019 return -1;
2020 }
2021 }
2022 f->f_bufptr = f->f_buf;
2023 f->f_bufend = f->f_buf + chunksize;
2024 return 0;
2025}
2026
2027/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002028 uninitialized bytes followed by the remainder of the line. Don't be
2029 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002030 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2031
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002032static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002033readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2034{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002035 PyStringObject* s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002036 char *bufptr;
2037 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002038 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002039
2040 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002041 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002042 return NULL;
2043
2044 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002045 if (len == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002046 return (PyStringObject *)
2047 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002048 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002049 if (bufptr != NULL) {
2050 bufptr++; /* Count the '\n' */
2051 len = bufptr - f->f_bufptr;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002052 s = (PyStringObject *)
2053 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002054 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002055 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002056 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002057 f->f_bufptr = bufptr;
2058 if (bufptr == f->f_bufend)
2059 drop_readahead(f);
2060 } else {
2061 bufptr = f->f_bufptr;
2062 buf = f->f_buf;
2063 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002064 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002065 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002066 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002067 if (s == NULL) {
2068 PyMem_Free(buf);
2069 return NULL;
2070 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002071 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002072 PyMem_Free(buf);
2073 }
2074 return s;
2075}
2076
2077/* A larger buffer size may actually decrease performance. */
2078#define READAHEAD_BUFSIZE 8192
2079
2080static PyObject *
2081file_iternext(PyFileObject *f)
2082{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002083 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002084
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002085 if (f->f_fp == NULL)
2086 return err_closed();
2087
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002088 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002089 if (l == NULL || PyString_GET_SIZE(l) == 0) {
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002090 Py_XDECREF(l);
2091 return NULL;
2092 }
2093 return (PyObject *)l;
2094}
2095
2096
Tim Peters59c9a642001-09-13 05:38:56 +00002097static PyObject *
2098file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2099{
Tim Peters44410012001-09-14 03:26:08 +00002100 PyObject *self;
2101 static PyObject *not_yet_string;
2102
2103 assert(type != NULL && type->tp_alloc != NULL);
2104
2105 if (not_yet_string == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002106 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002107 if (not_yet_string == NULL)
2108 return NULL;
2109 }
2110
2111 self = type->tp_alloc(type, 0);
2112 if (self != NULL) {
2113 /* Always fill in the name and mode, so that nobody else
2114 needs to special-case NULLs there. */
2115 Py_INCREF(not_yet_string);
2116 ((PyFileObject *)self)->f_name = not_yet_string;
2117 Py_INCREF(not_yet_string);
2118 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002119 Py_INCREF(Py_None);
2120 ((PyFileObject *)self)->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +00002121 Py_INCREF(Py_None);
2122 ((PyFileObject *)self)->f_errors = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002123 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002124 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002125 }
2126 return self;
2127}
2128
2129static int
2130file_init(PyObject *self, PyObject *args, PyObject *kwds)
2131{
2132 PyFileObject *foself = (PyFileObject *)self;
2133 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002134 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002135 char *name = NULL;
2136 char *mode = "r";
2137 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002138 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00002139
2140 assert(PyFile_Check(self));
2141 if (foself->f_fp != NULL) {
2142 /* Have to close the existing file first. */
2143 PyObject *closeresult = file_close(foself);
2144 if (closeresult == NULL)
2145 return -1;
2146 Py_DECREF(closeresult);
2147 }
Tim Peters59c9a642001-09-13 05:38:56 +00002148
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002149#ifdef Py_WIN_WIDE_FILENAMES
2150 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2151 PyObject *po;
2152 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2153 kwlist, &po, &mode, &bufsize)) {
2154 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002155 if (fill_file_fields(foself, NULL, po, mode,
2156 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002157 goto Error;
2158 } else {
2159 /* Drop the argument parsing error as narrow
2160 strings are also valid. */
2161 PyErr_Clear();
2162 }
2163 }
2164#endif
2165
2166 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002167 PyObject *o_name;
2168
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002169 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2170 Py_FileSystemDefaultEncoding,
2171 &name,
2172 &mode, &bufsize))
2173 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002174
2175 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002176 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2177 kwlist, &o_name, &mode,
2178 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002179 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002180
2181 if (fill_file_fields(foself, NULL, o_name, mode,
2182 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002183 goto Error;
2184 }
Tim Peters44410012001-09-14 03:26:08 +00002185 if (open_the_file(foself, name, mode) == NULL)
2186 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002187 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002188 PyFile_SetBufSize(self, bufsize);
2189 goto Done;
2190
2191Error:
2192 ret = -1;
2193 /* fall through */
2194Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002195 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002196 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002197}
2198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002199PyDoc_VAR(file_doc) =
2200PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002201"file(name[, mode[, buffering]]) -> file object\n"
2202"\n"
2203"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2204"writing or appending. The file will be created if it doesn't exist\n"
2205"when opened for writing or appending; it will be truncated when\n"
2206"opened for writing. Add a 'b' to the mode for binary files.\n"
2207"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2208"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002209"buffered, and larger numbers specify the buffer size. The preferred way\n"
2210"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002211)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002212PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002213"Add a 'U' to mode to open the file for input with universal newline\n"
2214"support. Any line ending in the input file will be seen as a '\\n'\n"
2215"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2216"the value for this attribute is one of None (no newline read yet),\n"
2217"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2218"\n"
2219"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002220);
Tim Peters59c9a642001-09-13 05:38:56 +00002221
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002222PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002223 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002224 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002225 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002226 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002227 (destructor)file_dealloc, /* tp_dealloc */
2228 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229 0, /* tp_getattr */
2230 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002231 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002233 0, /* tp_as_number */
2234 0, /* tp_as_sequence */
2235 0, /* tp_as_mapping */
2236 0, /* tp_hash */
2237 0, /* tp_call */
2238 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002240 /* softspace is writable: we must supply tp_setattro */
2241 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002242 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002243 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002244 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245 0, /* tp_traverse */
2246 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002247 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002248 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002249 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002250 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251 file_methods, /* tp_methods */
2252 file_memberlist, /* tp_members */
2253 file_getsetlist, /* tp_getset */
2254 0, /* tp_base */
2255 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002256 0, /* tp_descr_get */
2257 0, /* tp_descr_set */
2258 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002259 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002260 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002261 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002262 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002263};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002264
2265/* Interface for the 'soft space' between print items. */
2266
2267int
Fred Drakefd99de62000-07-09 05:02:18 +00002268PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002269{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002270 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002271 if (f == NULL) {
2272 /* Do nothing */
2273 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002274 else if (PyFile_Check(f)) {
2275 oldflag = ((PyFileObject *)f)->f_softspace;
2276 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002277 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002278 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279 PyObject *v;
2280 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002281 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002282 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002283 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002284 if (PyInt_Check(v))
2285 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002286 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002287 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002288 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002289 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002290 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002291 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002292 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002293 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2294 PyErr_Clear();
2295 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002296 }
2297 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002298 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002299}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002300
2301/* Interfaces to write objects/strings to file-like objects */
2302
2303int
Fred Drakefd99de62000-07-09 05:02:18 +00002304PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002305{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002306 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002307 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002308 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002309 return -1;
2310 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002311 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002312 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002313#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002314 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002315 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002316#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002317 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002318 err_closed();
2319 return -1;
2320 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002321#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002322 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002323 PyUnicode_Check(v) && enc != Py_None) {
Christian Heimes593daf52008-05-26 12:51:38 +00002324 char *cenc = PyBytes_AS_STRING(enc);
Martin v. Löwis99815892008-06-01 07:20:46 +00002325 char *errors = fobj->f_errors == Py_None ?
2326 "strict" : PyBytes_AS_STRING(fobj->f_errors);
2327 value = PyUnicode_AsEncodedString(v, cenc, errors);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002328 if (value == NULL)
2329 return -1;
2330 } else {
2331 value = v;
2332 Py_INCREF(value);
2333 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002334 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002335 Py_DECREF(value);
2336 return result;
2337#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002338 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002339#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002340 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002341 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002342 if (writer == NULL)
2343 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002344 if (flags & Py_PRINT_RAW) {
2345 if (PyUnicode_Check(v)) {
2346 value = v;
2347 Py_INCREF(value);
2348 } else
2349 value = PyObject_Str(v);
2350 }
2351 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002352 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002353 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002354 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002355 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002356 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002357 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002358 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002359 Py_DECREF(value);
2360 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002361 return -1;
2362 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002363 result = PyEval_CallObject(writer, args);
2364 Py_DECREF(args);
2365 Py_DECREF(value);
2366 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002367 if (result == NULL)
2368 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002369 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002370 return 0;
2371}
2372
Guido van Rossum27a60b11997-05-22 22:25:11 +00002373int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002374PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002375{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002376
Guido van Rossum3165fe61992-09-25 21:59:05 +00002377 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002378 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002379 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002380 PyErr_SetString(PyExc_SystemError,
2381 "null file for PyFile_WriteString");
2382 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002383 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002384 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002385 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002386 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002387 if (fp == NULL) {
2388 err_closed();
2389 return -1;
2390 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002391 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002392 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002393 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002394 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002395 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002396 else if (!PyErr_Occurred()) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002397 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002398 int err;
2399 if (v == NULL)
2400 return -1;
2401 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2402 Py_DECREF(v);
2403 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002404 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002405 else
2406 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002407}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002408
2409/* Try to get a file-descriptor from a Python object. If the object
2410 is an integer or long integer, its value is returned. If not, the
2411 object's fileno() method is called if it exists; the method must return
2412 an integer or long integer, which is returned as the file descriptor value.
2413 -1 is returned on failure.
2414*/
2415
2416int PyObject_AsFileDescriptor(PyObject *o)
2417{
2418 int fd;
2419 PyObject *meth;
2420
2421 if (PyInt_Check(o)) {
2422 fd = PyInt_AsLong(o);
2423 }
2424 else if (PyLong_Check(o)) {
2425 fd = PyLong_AsLong(o);
2426 }
2427 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2428 {
2429 PyObject *fno = PyEval_CallObject(meth, NULL);
2430 Py_DECREF(meth);
2431 if (fno == NULL)
2432 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002433
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002434 if (PyInt_Check(fno)) {
2435 fd = PyInt_AsLong(fno);
2436 Py_DECREF(fno);
2437 }
2438 else if (PyLong_Check(fno)) {
2439 fd = PyLong_AsLong(fno);
2440 Py_DECREF(fno);
2441 }
2442 else {
2443 PyErr_SetString(PyExc_TypeError,
2444 "fileno() returned a non-integer");
2445 Py_DECREF(fno);
2446 return -1;
2447 }
2448 }
2449 else {
2450 PyErr_SetString(PyExc_TypeError,
2451 "argument must be an int, or have a fileno() method.");
2452 return -1;
2453 }
2454
2455 if (fd < 0) {
2456 PyErr_Format(PyExc_ValueError,
2457 "file descriptor cannot be a negative integer (%i)",
2458 fd);
2459 return -1;
2460 }
2461 return fd;
2462}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002463
Jack Jansen7b8c7542002-04-14 20:12:41 +00002464/* From here on we need access to the real fgets and fread */
2465#undef fgets
2466#undef fread
2467
2468/*
2469** Py_UniversalNewlineFgets is an fgets variation that understands
2470** all of \r, \n and \r\n conventions.
2471** The stream should be opened in binary mode.
2472** If fobj is NULL the routine always does newline conversion, and
2473** it may peek one char ahead to gobble the second char in \r\n.
2474** If fobj is non-NULL it must be a PyFileObject. In this case there
2475** is no readahead but in stead a flag is used to skip a following
2476** \n on the next read. Also, if the file is open in binary mode
2477** the whole conversion is skipped. Finally, the routine keeps track of
2478** the different types of newlines seen.
2479** Note that we need no error handling: fgets() treats error and eof
2480** identically.
2481*/
2482char *
2483Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2484{
2485 char *p = buf;
2486 int c;
2487 int newlinetypes = 0;
2488 int skipnextlf = 0;
2489 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002490
Jack Jansen7b8c7542002-04-14 20:12:41 +00002491 if (fobj) {
2492 if (!PyFile_Check(fobj)) {
2493 errno = ENXIO; /* What can you do... */
2494 return NULL;
2495 }
2496 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2497 if ( !univ_newline )
2498 return fgets(buf, n, stream);
2499 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2500 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2501 }
2502 FLOCKFILE(stream);
2503 c = 'x'; /* Shut up gcc warning */
2504 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2505 if (skipnextlf ) {
2506 skipnextlf = 0;
2507 if (c == '\n') {
2508 /* Seeing a \n here with skipnextlf true
2509 ** means we saw a \r before.
2510 */
2511 newlinetypes |= NEWLINE_CRLF;
2512 c = GETC(stream);
2513 if (c == EOF) break;
2514 } else {
2515 /*
2516 ** Note that c == EOF also brings us here,
2517 ** so we're okay if the last char in the file
2518 ** is a CR.
2519 */
2520 newlinetypes |= NEWLINE_CR;
2521 }
2522 }
2523 if (c == '\r') {
2524 /* A \r is translated into a \n, and we skip
2525 ** an adjacent \n, if any. We don't set the
2526 ** newlinetypes flag until we've seen the next char.
2527 */
2528 skipnextlf = 1;
2529 c = '\n';
2530 } else if ( c == '\n') {
2531 newlinetypes |= NEWLINE_LF;
2532 }
2533 *p++ = c;
2534 if (c == '\n') break;
2535 }
2536 if ( c == EOF && skipnextlf )
2537 newlinetypes |= NEWLINE_CR;
2538 FUNLOCKFILE(stream);
2539 *p = '\0';
2540 if (fobj) {
2541 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2542 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2543 } else if ( skipnextlf ) {
2544 /* If we have no file object we cannot save the
2545 ** skipnextlf flag. We have to readahead, which
2546 ** will cause a pause if we're reading from an
2547 ** interactive stream, but that is very unlikely
2548 ** unless we're doing something silly like
2549 ** execfile("/dev/tty").
2550 */
2551 c = GETC(stream);
2552 if ( c != '\n' )
2553 ungetc(c, stream);
2554 }
2555 if (p == buf)
2556 return NULL;
2557 return buf;
2558}
2559
2560/*
2561** Py_UniversalNewlineFread is an fread variation that understands
2562** all of \r, \n and \r\n conventions.
2563** The stream should be opened in binary mode.
2564** fobj must be a PyFileObject. In this case there
2565** is no readahead but in stead a flag is used to skip a following
2566** \n on the next read. Also, if the file is open in binary mode
2567** the whole conversion is skipped. Finally, the routine keeps track of
2568** the different types of newlines seen.
2569*/
2570size_t
Tim Peters058b1412002-04-21 07:29:14 +00002571Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002572 FILE *stream, PyObject *fobj)
2573{
Tim Peters058b1412002-04-21 07:29:14 +00002574 char *dst = buf;
2575 PyFileObject *f = (PyFileObject *)fobj;
2576 int newlinetypes, skipnextlf;
2577
2578 assert(buf != NULL);
2579 assert(stream != NULL);
2580
Jack Jansen7b8c7542002-04-14 20:12:41 +00002581 if (!fobj || !PyFile_Check(fobj)) {
2582 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002583 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002584 }
Tim Peters058b1412002-04-21 07:29:14 +00002585 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002586 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002587 newlinetypes = f->f_newlinetypes;
2588 skipnextlf = f->f_skipnextlf;
2589 /* Invariant: n is the number of bytes remaining to be filled
2590 * in the buffer.
2591 */
2592 while (n) {
2593 size_t nread;
2594 int shortread;
2595 char *src = dst;
2596
2597 nread = fread(dst, 1, n, stream);
2598 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002599 if (nread == 0)
2600 break;
2601
Tim Peterse1682a82002-04-21 18:15:20 +00002602 n -= nread; /* assuming 1 byte out for each in; will adjust */
2603 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002604 while (nread--) {
2605 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002606 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002607 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002608 *dst++ = '\n';
2609 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002610 }
2611 else if (skipnextlf && c == '\n') {
2612 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002613 skipnextlf = 0;
2614 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002615 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002616 }
2617 else {
2618 /* Normal char to be stored in buffer. Also
2619 * update the newlinetypes flag if either this
2620 * is an LF or the previous char was a CR.
2621 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002622 if (c == '\n')
2623 newlinetypes |= NEWLINE_LF;
2624 else if (skipnextlf)
2625 newlinetypes |= NEWLINE_CR;
2626 *dst++ = c;
2627 skipnextlf = 0;
2628 }
2629 }
Tim Peters058b1412002-04-21 07:29:14 +00002630 if (shortread) {
2631 /* If this is EOF, update type flags. */
2632 if (skipnextlf && feof(stream))
2633 newlinetypes |= NEWLINE_CR;
2634 break;
2635 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002636 }
Tim Peters058b1412002-04-21 07:29:14 +00002637 f->f_newlinetypes = newlinetypes;
2638 f->f_skipnextlf = skipnextlf;
2639 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002640}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002641
2642#ifdef __cplusplus
2643}
2644#endif