blob: a8e95a269756373e931bf1aa4ee86671e97fba24 [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));
Gregory P. Smith99a3dce2008-06-10 17:42:36 +0000456 str = PyString_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;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001010 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001011
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001012 if (f->f_fp == NULL)
1013 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001014 /* refuse to mix with f.next() */
1015 if (f->f_buf != NULL &&
1016 (f->f_bufend - f->f_bufptr) > 0 &&
1017 f->f_buf[0] != '\0')
1018 return err_iterbuffered();
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001019 if (!PyArg_ParseTuple(args, "w*", &pbuf))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001020 return NULL;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001021 ptr = pbuf.buf;
1022 ntodo = pbuf.len;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001023 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001024 while (ntodo > 0) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001025 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001026 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +00001027 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001028 (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001029 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001030 if (nnow == 0) {
1031 if (!ferror(f->f_fp))
1032 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001033 PyErr_SetFromErrno(PyExc_IOError);
1034 clearerr(f->f_fp);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001035 PyBuffer_Release(&pbuf);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001036 return NULL;
1037 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001038 ndone += nnow;
1039 ntodo -= nnow;
1040 }
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001041 PyBuffer_Release(&pbuf);
Neal Norwitz076d1e02006-08-21 18:20:10 +00001042 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001043}
1044
Tim Peters86821b22001-01-07 21:19:34 +00001045/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001046Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001047
1048Under MSVC 6:
1049
Tim Peters1c733232001-01-08 04:02:07 +00001050+ MS threadsafe getc is very slow (multiple layers of function calls before+
1051 after each character, to lock+unlock the stream).
1052+ The stream-locking functions are MS-internal -- can't access them from user
1053 code.
1054+ There's nothing Tim could find in the MS C or platform SDK libraries that
1055 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001056+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1057
1058So we use fgets for speed(!), despite that it's painful.
1059
1060MS realloc is also slow.
1061
Tim Petersf29b64d2001-01-15 06:33:19 +00001062Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1063have):
1064 Linux a wash
1065 Solaris a wash
1066 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001067
Tim Petersf29b64d2001-01-15 06:33:19 +00001068CAUTION: The C std isn't clear about this: in those cases where fgets
1069writes something into the buffer, can it write into any position beyond the
1070required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1071known on which it does; and it would be a strange way to code fgets. Still,
1072getline_via_fgets may not work correctly if it does. The std test
1073test_bufio.py should fail if platform fgets() routinely writes beyond the
1074trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001075**************************************************************************/
1076
Tim Petersf29b64d2001-01-15 06:33:19 +00001077/* Use this routine if told to, or by default on non-get_unlocked()
1078 * platforms unless told not to. Yikes! Let's spell that out:
1079 * On a platform with getc_unlocked():
1080 * By default, use getc_unlocked().
1081 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1082 * On a platform without getc_unlocked():
1083 * By default, use fgets().
1084 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1085 */
1086#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1087#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001088#endif
1089
Tim Petersf29b64d2001-01-15 06:33:19 +00001090#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1091#undef USE_FGETS_IN_GETLINE
1092#endif
1093
1094#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001095static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001096getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001097{
Tim Peters15b83852001-01-08 00:53:12 +00001098/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001099 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1100 * to fill this much of the buffer with a known value in order to figure out
1101 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1102 * than "most" lines, we waste time filling unused buffer slots. 100 is
1103 * surely adequate for most peoples' email archives, chewing over source code,
1104 * etc -- "regular old text files".
1105 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1106 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1107 * cautions about boosting that. 300 was chosen because the worst real-life
1108 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1109 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001110 */
Tim Peters142297a2001-01-15 10:36:56 +00001111#define INITBUFSIZE 100
1112#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001113 char* p; /* temp */
1114 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001115 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001116 char* pvfree; /* address of next free slot */
1117 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001118 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1119 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001120 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001121 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001122
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001123 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001124 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001125 */
Tim Peters142297a2001-01-15 10:36:56 +00001126 total_v_size = INITBUFSIZE; /* start small and pray */
1127 pvfree = buf;
1128 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001129 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters142297a2001-01-15 10:36:56 +00001130 pvend = buf + total_v_size;
1131 nfree = pvend - pvfree;
1132 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001133 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1134 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001135 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001136
Tim Peters142297a2001-01-15 10:36:56 +00001137 if (p == NULL) {
1138 clearerr(fp);
1139 if (PyErr_CheckSignals())
1140 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001141 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001142 return v;
1143 }
Tim Peters142297a2001-01-15 10:36:56 +00001144 /* fgets read *something* */
1145 p = memchr(pvfree, '\n', nfree);
1146 if (p != NULL) {
1147 /* Did the \n come from fgets or from us?
1148 * Since fgets stops at the first \n, and then writes
1149 * \0, if it's from fgets a \0 must be next. But if
1150 * that's so, it could not have come from us, since
1151 * the \n's we filled the buffer with have only more
1152 * \n's to the right.
1153 */
1154 if (p+1 < pvend && *(p+1) == '\0') {
1155 /* It's from fgets: we win! In particular,
1156 * we haven't done any mallocs yet, and can
1157 * build the final result on the first try.
1158 */
1159 ++p; /* include \n from fgets */
1160 }
1161 else {
1162 /* Must be from us: fgets didn't fill the
1163 * buffer and didn't find a newline, so it
1164 * must be the last and newline-free line of
1165 * the file.
1166 */
1167 assert(p > pvfree && *(p-1) == '\0');
1168 --p; /* don't include \0 from fgets */
1169 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001170 v = PyString_FromStringAndSize(buf, p - buf);
Tim Peters142297a2001-01-15 10:36:56 +00001171 return v;
1172 }
1173 /* yuck: fgets overwrote all the newlines, i.e. the entire
1174 * buffer. So this line isn't over yet, or maybe it is but
1175 * we're exactly at EOF. If we haven't already, try using the
1176 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001177 */
Tim Peters142297a2001-01-15 10:36:56 +00001178 assert(*(pvend-1) == '\0');
1179 if (pvfree == buf) {
1180 pvfree = pvend - 1; /* overwrite trailing null */
1181 total_v_size = MAXBUFSIZE;
1182 }
1183 else
1184 break;
Tim Peters86821b22001-01-07 21:19:34 +00001185 }
Tim Peters142297a2001-01-15 10:36:56 +00001186
1187 /* The stack buffer isn't big enough; malloc a string object and read
1188 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001189 */
Tim Petersddea2082002-03-23 10:03:50 +00001190 total_v_size = MAXBUFSIZE << 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001191 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001192 if (v == NULL)
1193 return v;
1194 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001195 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1196 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001197
1198 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001199 * after setting p one beyond the end of the line. The code here is
1200 * very much like the code above, except reads into v's buffer; see
1201 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001202 */
1203 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001204 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001205 pvend = BUF(v) + total_v_size;
1206 nfree = pvend - pvfree;
1207 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001208 assert(nfree < INT_MAX);
1209 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001210 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001211
1212 if (p == NULL) {
1213 clearerr(fp);
1214 if (PyErr_CheckSignals()) {
1215 Py_DECREF(v);
1216 return NULL;
1217 }
1218 p = pvfree;
1219 break;
1220 }
Tim Peters86821b22001-01-07 21:19:34 +00001221 p = memchr(pvfree, '\n', nfree);
1222 if (p != NULL) {
1223 if (p+1 < pvend && *(p+1) == '\0') {
1224 /* \n came from fgets */
1225 ++p;
1226 break;
1227 }
1228 /* \n came from us; last line of file, no newline */
1229 assert(p > pvfree && *(p-1) == '\0');
1230 --p;
1231 break;
1232 }
1233 /* expand buffer and try again */
1234 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001235 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001236 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001237 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001238 /* check for overflow */
1239 if (total_v_size <= prev_v_size ||
1240 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001241 PyErr_SetString(PyExc_OverflowError,
1242 "line is longer than a Python string can hold");
1243 Py_DECREF(v);
1244 return NULL;
1245 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001246 if (_PyString_Resize(&v, (int)total_v_size) < 0)
Tim Peters86821b22001-01-07 21:19:34 +00001247 return NULL;
1248 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001249 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001250 }
1251 if (BUF(v) + total_v_size != p)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001252 _PyString_Resize(&v, p - BUF(v));
Tim Peters86821b22001-01-07 21:19:34 +00001253 return v;
1254#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001255#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001256}
Tim Petersf29b64d2001-01-15 06:33:19 +00001257#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001258
Guido van Rossum0bd24411991-04-04 15:21:57 +00001259/* Internal routine to get a line.
1260 Size argument interpretation:
1261 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001262 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001263*/
1264
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001266get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001267{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001268 FILE *fp = f->f_fp;
1269 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001270 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001271 size_t total_v_size; /* total # of slots in buffer */
1272 size_t used_v_size; /* # used slots in buffer */
1273 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001274 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001275 int newlinetypes = f->f_newlinetypes;
1276 int skipnextlf = f->f_skipnextlf;
1277 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001278
Jack Jansen7b8c7542002-04-14 20:12:41 +00001279#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001280 if (n <= 0 && !univ_newline )
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001281 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001282#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001283 total_v_size = n > 0 ? n : 100;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001284 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001285 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001286 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001287 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001288 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001289
Guido van Rossumce5ba841991-03-06 13:06:18 +00001290 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001291 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001292 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001293 if (univ_newline) {
1294 c = 'x'; /* Shut up gcc warning */
1295 while ( buf != end && (c = GETC(fp)) != EOF ) {
1296 if (skipnextlf ) {
1297 skipnextlf = 0;
1298 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001299 /* Seeing a \n here with
1300 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001301 * saw a \r before.
1302 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001303 newlinetypes |= NEWLINE_CRLF;
1304 c = GETC(fp);
1305 if (c == EOF) break;
1306 } else {
1307 newlinetypes |= NEWLINE_CR;
1308 }
1309 }
1310 if (c == '\r') {
1311 skipnextlf = 1;
1312 c = '\n';
1313 } else if ( c == '\n')
1314 newlinetypes |= NEWLINE_LF;
1315 *buf++ = c;
1316 if (c == '\n') break;
1317 }
1318 if ( c == EOF && skipnextlf )
1319 newlinetypes |= NEWLINE_CR;
1320 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001321 while ((c = GETC(fp)) != EOF &&
1322 (*buf++ = c) != '\n' &&
1323 buf != end)
1324 ;
1325 FUNLOCKFILE(fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001326 FILE_END_ALLOW_THREADS(f)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001327 f->f_newlinetypes = newlinetypes;
1328 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001329 if (c == '\n')
1330 break;
1331 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001332 if (ferror(fp)) {
1333 PyErr_SetFromErrno(PyExc_IOError);
1334 clearerr(fp);
1335 Py_DECREF(v);
1336 return NULL;
1337 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001338 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001339 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001340 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001341 return NULL;
1342 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001343 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001344 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001345 /* Must be because buf == end */
1346 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001347 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001348 used_v_size = total_v_size;
1349 increment = total_v_size >> 2; /* mild exponential growth */
1350 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001351 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001352 PyErr_SetString(PyExc_OverflowError,
1353 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001354 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001355 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001356 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001357 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001358 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001359 buf = BUF(v) + used_v_size;
1360 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001361 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001362
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001363 used_v_size = buf - BUF(v);
1364 if (used_v_size != total_v_size)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001365 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001366 return v;
1367}
1368
Guido van Rossum0bd24411991-04-04 15:21:57 +00001369/* External C interface */
1370
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001371PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001372PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001373{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001374 PyObject *result;
1375
Guido van Rossum3165fe61992-09-25 21:59:05 +00001376 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001377 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001378 return NULL;
1379 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001380
1381 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001382 PyFileObject *fo = (PyFileObject *)f;
1383 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001384 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001385 /* refuse to mix with f.next() */
1386 if (fo->f_buf != NULL &&
1387 (fo->f_bufend - fo->f_bufptr) > 0 &&
1388 fo->f_buf[0] != '\0')
1389 return err_iterbuffered();
1390 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001391 }
1392 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001393 PyObject *reader;
1394 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001395
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001396 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001397 if (reader == NULL)
1398 return NULL;
1399 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001400 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001401 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001402 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001403 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001404 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001405 return NULL;
1406 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001407 result = PyEval_CallObject(reader, args);
1408 Py_DECREF(reader);
1409 Py_DECREF(args);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001410 if (result != NULL && !PyString_Check(result) &&
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001411 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001412 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001413 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001414 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001415 "object.readline() returned non-string");
1416 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001417 }
1418
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001419 if (n < 0 && result != NULL && PyString_Check(result)) {
1420 char *s = PyString_AS_STRING(result);
1421 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001422 if (len == 0) {
1423 Py_DECREF(result);
1424 result = NULL;
1425 PyErr_SetString(PyExc_EOFError,
1426 "EOF when reading a line");
1427 }
1428 else if (s[len-1] == '\n') {
1429 if (result->ob_refcnt == 1)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001430 _PyString_Resize(&result, len-1);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001431 else {
1432 PyObject *v;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001433 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001434 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001435 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001436 }
1437 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001438 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001439#ifdef Py_USING_UNICODE
1440 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1441 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001442 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001443 if (len == 0) {
1444 Py_DECREF(result);
1445 result = NULL;
1446 PyErr_SetString(PyExc_EOFError,
1447 "EOF when reading a line");
1448 }
1449 else if (s[len-1] == '\n') {
1450 if (result->ob_refcnt == 1)
1451 PyUnicode_Resize(&result, len-1);
1452 else {
1453 PyObject *v;
1454 v = PyUnicode_FromUnicode(s, len-1);
1455 Py_DECREF(result);
1456 result = v;
1457 }
1458 }
1459 }
1460#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001461 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001462}
1463
1464/* Python method */
1465
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001466static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001467file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001468{
Guido van Rossum789a1611997-05-10 22:33:55 +00001469 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001470
Guido van Rossumd7297e61992-07-06 14:19:26 +00001471 if (f->f_fp == NULL)
1472 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001473 /* refuse to mix with f.next() */
1474 if (f->f_buf != NULL &&
1475 (f->f_bufend - f->f_bufptr) > 0 &&
1476 f->f_buf[0] != '\0')
1477 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001478 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001479 return NULL;
1480 if (n == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001481 return PyString_FromString("");
Guido van Rossum789a1611997-05-10 22:33:55 +00001482 if (n < 0)
1483 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001484 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001485}
1486
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001487static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001488file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001489{
Guido van Rossum789a1611997-05-10 22:33:55 +00001490 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001491 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001492 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001493 char small_buffer[SMALLCHUNK];
1494 char *buffer = small_buffer;
1495 size_t buffersize = SMALLCHUNK;
1496 PyObject *big_buffer = NULL;
1497 size_t nfilled = 0;
1498 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001499 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001500 char *p, *q, *end;
1501 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001502 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001503
Guido van Rossumd7297e61992-07-06 14:19:26 +00001504 if (f->f_fp == NULL)
1505 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001506 /* refuse to mix with f.next() */
1507 if (f->f_buf != NULL &&
1508 (f->f_bufend - f->f_bufptr) > 0 &&
1509 f->f_buf[0] != '\0')
1510 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001511 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001512 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001513 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001514 return NULL;
1515 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001516 if (shortread)
1517 nread = 0;
1518 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001519 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001520 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001521 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001522 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001523 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001524 shortread = (nread < buffersize-nfilled);
1525 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001526 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001527 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001528 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001529 break;
1530 PyErr_SetFromErrno(PyExc_IOError);
1531 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001532 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001533 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001534 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001535 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001536 if (p == NULL) {
1537 /* Need a larger buffer to fit this line */
1538 nfilled += nread;
1539 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001540 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001541 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001542 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001543 goto error;
1544 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001545 if (big_buffer == NULL) {
1546 /* Create the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001547 big_buffer = PyString_FromStringAndSize(
Guido van Rossum6263d541997-05-10 22:07:25 +00001548 NULL, buffersize);
1549 if (big_buffer == NULL)
1550 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001551 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001552 memcpy(buffer, small_buffer, nfilled);
1553 }
1554 else {
1555 /* Grow the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001556 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
Jack Jansen7b8c7542002-04-14 20:12:41 +00001557 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001558 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001559 }
1560 continue;
1561 }
1562 end = buffer+nfilled+nread;
1563 q = buffer;
1564 do {
1565 /* Process complete lines */
1566 p++;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001567 line = PyString_FromStringAndSize(q, p-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001568 if (line == NULL)
1569 goto error;
1570 err = PyList_Append(list, line);
1571 Py_DECREF(line);
1572 if (err != 0)
1573 goto error;
1574 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001575 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001576 } while (p != NULL);
1577 /* Move the remaining incomplete line to the start */
1578 nfilled = end-q;
1579 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001580 if (sizehint > 0)
1581 if (totalread >= (size_t)sizehint)
1582 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001583 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001584 if (nfilled != 0) {
1585 /* Partial last line */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001586 line = PyString_FromStringAndSize(buffer, nfilled);
Guido van Rossum6263d541997-05-10 22:07:25 +00001587 if (line == NULL)
1588 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001589 if (sizehint > 0) {
1590 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001591 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001592 if (rest == NULL) {
1593 Py_DECREF(line);
1594 goto error;
1595 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001596 PyString_Concat(&line, rest);
Guido van Rossum789a1611997-05-10 22:33:55 +00001597 Py_DECREF(rest);
1598 if (line == NULL)
1599 goto error;
1600 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001601 err = PyList_Append(list, line);
1602 Py_DECREF(line);
1603 if (err != 0)
1604 goto error;
1605 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001606
1607cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001608 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001609 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001610
1611error:
1612 Py_CLEAR(list);
1613 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001614}
1615
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001616static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001617file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001618{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001619 Py_buffer pbuf;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001620 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001621 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001622 if (f->f_fp == NULL)
1623 return err_closed();
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001624 if (f->f_binary) {
1625 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1626 return NULL;
1627 s = pbuf.buf;
1628 n = pbuf.len;
1629 } else
1630 if (!PyArg_ParseTuple(args, "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001631 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001632 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001633 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001634 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001635 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001636 FILE_END_ALLOW_THREADS(f)
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001637 if (f->f_binary)
1638 PyBuffer_Release(&pbuf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001639 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001640 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001641 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001642 return NULL;
1643 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001644 Py_INCREF(Py_None);
1645 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001646}
1647
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001648static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001649file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001650{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001651#define CHUNKSIZE 1000
1652 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001653 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001654 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001655 int index, islist;
1656 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001657
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001658 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001659 if (f->f_fp == NULL)
1660 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001661
1662 result = NULL;
1663 list = NULL;
1664 islist = PyList_Check(seq);
1665 if (islist)
1666 it = NULL;
1667 else {
1668 it = PyObject_GetIter(seq);
1669 if (it == NULL) {
1670 PyErr_SetString(PyExc_TypeError,
1671 "writelines() requires an iterable argument");
1672 return NULL;
1673 }
1674 /* From here on, fail by going to error, to reclaim "it". */
1675 list = PyList_New(CHUNKSIZE);
1676 if (list == NULL)
1677 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001678 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001679
1680 /* Strategy: slurp CHUNKSIZE lines into a private list,
1681 checking that they are all strings, then write that list
1682 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001683 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001684 if (islist) {
1685 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001686 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001687 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001688 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001689 j = PyList_GET_SIZE(list);
1690 }
1691 else {
1692 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001693 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001694 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001695 if (PyErr_Occurred())
1696 goto error;
1697 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001698 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001699 PyList_SetItem(list, j, line);
1700 }
1701 }
1702 if (j == 0)
1703 break;
1704
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001705 /* Check that all entries are indeed strings. If not,
1706 apply the same rules as for file.write() and
1707 convert the results to strings. This is slow, but
1708 seems to be the only way since all conversion APIs
1709 could potentially execute Python code. */
1710 for (i = 0; i < j; i++) {
1711 PyObject *v = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001712 if (!PyString_Check(v)) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001713 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001714 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001715 PyObject_AsReadBuffer(v,
1716 (const void**)&buffer,
1717 &len)) ||
1718 PyObject_AsCharBuffer(v,
1719 &buffer,
1720 &len))) {
1721 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001722 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001723 goto error;
1724 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001725 line = PyString_FromStringAndSize(buffer,
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001726 len);
1727 if (line == NULL)
1728 goto error;
1729 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001730 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001731 }
1732 }
1733
1734 /* Since we are releasing the global lock, the
1735 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001736 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001737 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001738 errno = 0;
1739 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001740 line = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001741 len = PyString_GET_SIZE(line);
1742 nwritten = fwrite(PyString_AS_STRING(line),
Guido van Rossumee70ad12000-03-13 16:27:06 +00001743 1, len, f->f_fp);
1744 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001745 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001746 PyErr_SetFromErrno(PyExc_IOError);
1747 clearerr(f->f_fp);
1748 goto error;
1749 }
1750 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001751 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001752
1753 if (j < CHUNKSIZE)
1754 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001755 }
1756
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001757 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001758 result = Py_None;
1759 error:
1760 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001761 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001762 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001763#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001764}
1765
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001766static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001767file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001768{
1769 if (f->f_fp == NULL)
1770 return err_closed();
1771 Py_INCREF(f);
1772 return (PyObject *)f;
1773}
1774
Georg Brandl98b40ad2006-06-08 14:50:21 +00001775static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001776file_xreadlines(PyFileObject *f)
1777{
1778 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1779 "try 'for line in f' instead", 1) < 0)
1780 return NULL;
1781 return file_self(f);
1782}
1783
1784static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001785file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001786{
Georg Brandlad61bc82008-02-23 15:11:18 +00001787 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001788 if (!ret)
1789 /* If error occurred, pass through */
1790 return NULL;
1791 Py_DECREF(ret);
1792 /* We cannot return the result of close since a true
1793 * value will be interpreted as "yes, swallow the
1794 * exception if one was raised inside the with block". */
1795 Py_RETURN_NONE;
1796}
1797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001798PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001799"readline([size]) -> next line from the file, as a string.\n"
1800"\n"
1801"Retain newline. A non-negative size argument limits the maximum\n"
1802"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001803"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001805PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001806"read([size]) -> read at most size bytes, returned as a string.\n"
1807"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001808"If the size argument is negative or omitted, read until EOF is reached.\n"
1809"Notice that when in non-blocking mode, less data than what was requested\n"
1810"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001812PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001813"write(str) -> None. Write string str to file.\n"
1814"\n"
1815"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001816"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001818PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001819"fileno() -> integer \"file descriptor\".\n"
1820"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001821"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001822
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001823PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001824"seek(offset[, whence]) -> None. Move to new file position.\n"
1825"\n"
1826"Argument offset is a byte count. Optional argument whence defaults to\n"
1827"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1828"(move relative to current position, positive or negative), and 2 (move\n"
1829"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001830"seeking beyond the end of a file). If the file is opened in text mode,\n"
1831"only offsets returned by tell() are legal. Use of other offsets causes\n"
1832"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001833"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001834"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001835
Guido van Rossumd7047b31995-01-02 19:07:15 +00001836#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001837PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001838"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1839"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001840"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001841#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001843PyDoc_STRVAR(tell_doc,
1844"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001845
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001846PyDoc_STRVAR(readinto_doc,
1847"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001849PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001850"readlines([size]) -> list of strings, each a line from the file.\n"
1851"\n"
1852"Call readline() repeatedly and return a list of the lines so read.\n"
1853"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001854"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001856PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001857"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001858"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001859"For backward compatibility. File objects now include the performance\n"
1860"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001862PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001863"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001864"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001865"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001866"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001868PyDoc_STRVAR(flush_doc,
1869"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001870
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001871PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001872"close() -> None or (perhaps) an integer. Close the file.\n"
1873"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001874"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001875"further I/O operations. close() may be called more than once without\n"
1876"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001877"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001879PyDoc_STRVAR(isatty_doc,
1880"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001881
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001882PyDoc_STRVAR(enter_doc,
1883 "__enter__() -> self.");
1884
Georg Brandl98b40ad2006-06-08 14:50:21 +00001885PyDoc_STRVAR(exit_doc,
1886 "__exit__(*excinfo) -> None. Closes the file.");
1887
Tim Petersefc3a3a2001-09-20 07:55:22 +00001888static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001889 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1890 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1891 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1892 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1893 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001894#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001895 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001896#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001897 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1898 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
Georg Brandla9916b52008-05-17 22:11:54 +00001899 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
1900 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
1901 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001902 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1903 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1904 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001905 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00001906 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001907 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001908};
1909
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001910#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001911
Guido van Rossum6f799372001-09-20 20:46:19 +00001912static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00001913 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001914 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001915 {"name", T_OBJECT, OFF(f_name), RO,
1916 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001917 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1918 "file encoding"},
Martin v. Löwis99815892008-06-01 07:20:46 +00001919 {"errors", T_OBJECT, OFF(f_errors), RO,
1920 "Unicode error handler"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001921 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001922 {NULL} /* Sentinel */
1923};
1924
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001925static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001927{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001928 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001929}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001930static PyObject *
1931get_newlines(PyFileObject *f, void *closure)
1932{
1933 switch (f->f_newlinetypes) {
1934 case NEWLINE_UNKNOWN:
1935 Py_INCREF(Py_None);
1936 return Py_None;
1937 case NEWLINE_CR:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001938 return PyString_FromString("\r");
Jack Jansen7b8c7542002-04-14 20:12:41 +00001939 case NEWLINE_LF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001940 return PyString_FromString("\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00001941 case NEWLINE_CR|NEWLINE_LF:
1942 return Py_BuildValue("(ss)", "\r", "\n");
1943 case NEWLINE_CRLF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001944 return PyString_FromString("\r\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00001945 case NEWLINE_CR|NEWLINE_CRLF:
1946 return Py_BuildValue("(ss)", "\r", "\r\n");
1947 case NEWLINE_LF|NEWLINE_CRLF:
1948 return Py_BuildValue("(ss)", "\n", "\r\n");
1949 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1950 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1951 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001952 PyErr_Format(PyExc_SystemError,
1953 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001954 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001955 return NULL;
1956 }
1957}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001958
Georg Brandl65bb42d2008-03-21 20:38:24 +00001959static PyObject *
1960get_softspace(PyFileObject *f, void *closure)
1961{
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00001962 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00001963 return NULL;
1964 return PyInt_FromLong(f->f_softspace);
1965}
1966
1967static int
1968set_softspace(PyFileObject *f, PyObject *value)
1969{
1970 int new;
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00001971 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00001972 return -1;
1973
1974 if (value == NULL) {
1975 PyErr_SetString(PyExc_TypeError,
1976 "can't delete softspace attribute");
1977 return -1;
1978 }
1979
1980 new = PyInt_AsLong(value);
1981 if (new == -1 && PyErr_Occurred())
1982 return -1;
1983 f->f_softspace = new;
1984 return 0;
1985}
1986
Guido van Rossum32d34c82001-09-20 21:45:26 +00001987static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001988 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001989 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001990 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00001991 {"softspace", (getter)get_softspace, (setter)set_softspace,
1992 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993 {0},
1994};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001995
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001996static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001997drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001998{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001999 if (f->f_buf != NULL) {
2000 PyMem_Free(f->f_buf);
2001 f->f_buf = NULL;
2002 }
Guido van Rossum65967252001-04-21 13:20:18 +00002003}
2004
Tim Petersf1827cf2003-09-07 03:30:18 +00002005/* Make sure that file has a readahead buffer with at least one byte
2006 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002007 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002008static int
2009readahead(PyFileObject *f, int bufsize)
2010{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002011 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002012
2013 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00002014 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002015 return 0;
2016 else
2017 drop_readahead(f);
2018 }
Anthony Baxter377be112006-04-11 06:54:30 +00002019 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00002020 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002021 return -1;
2022 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002023 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002024 errno = 0;
2025 chunksize = Py_UniversalNewlineFread(
2026 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002027 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002028 if (chunksize == 0) {
2029 if (ferror(f->f_fp)) {
2030 PyErr_SetFromErrno(PyExc_IOError);
2031 clearerr(f->f_fp);
2032 drop_readahead(f);
2033 return -1;
2034 }
2035 }
2036 f->f_bufptr = f->f_buf;
2037 f->f_bufend = f->f_buf + chunksize;
2038 return 0;
2039}
2040
2041/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002042 uninitialized bytes followed by the remainder of the line. Don't be
2043 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002044 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2045
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002046static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002047readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2048{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002049 PyStringObject* s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002050 char *bufptr;
2051 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002052 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002053
2054 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002055 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002056 return NULL;
2057
2058 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002059 if (len == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002060 return (PyStringObject *)
2061 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002062 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002063 if (bufptr != NULL) {
2064 bufptr++; /* Count the '\n' */
2065 len = bufptr - f->f_bufptr;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002066 s = (PyStringObject *)
2067 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002068 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002069 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002070 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002071 f->f_bufptr = bufptr;
2072 if (bufptr == f->f_bufend)
2073 drop_readahead(f);
2074 } else {
2075 bufptr = f->f_bufptr;
2076 buf = f->f_buf;
2077 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002078 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002079 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002080 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002081 if (s == NULL) {
2082 PyMem_Free(buf);
2083 return NULL;
2084 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002085 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002086 PyMem_Free(buf);
2087 }
2088 return s;
2089}
2090
2091/* A larger buffer size may actually decrease performance. */
2092#define READAHEAD_BUFSIZE 8192
2093
2094static PyObject *
2095file_iternext(PyFileObject *f)
2096{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002097 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002098
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002099 if (f->f_fp == NULL)
2100 return err_closed();
2101
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002102 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002103 if (l == NULL || PyString_GET_SIZE(l) == 0) {
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002104 Py_XDECREF(l);
2105 return NULL;
2106 }
2107 return (PyObject *)l;
2108}
2109
2110
Tim Peters59c9a642001-09-13 05:38:56 +00002111static PyObject *
2112file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2113{
Tim Peters44410012001-09-14 03:26:08 +00002114 PyObject *self;
2115 static PyObject *not_yet_string;
2116
2117 assert(type != NULL && type->tp_alloc != NULL);
2118
2119 if (not_yet_string == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002120 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002121 if (not_yet_string == NULL)
2122 return NULL;
2123 }
2124
2125 self = type->tp_alloc(type, 0);
2126 if (self != NULL) {
2127 /* Always fill in the name and mode, so that nobody else
2128 needs to special-case NULLs there. */
2129 Py_INCREF(not_yet_string);
2130 ((PyFileObject *)self)->f_name = not_yet_string;
2131 Py_INCREF(not_yet_string);
2132 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002133 Py_INCREF(Py_None);
2134 ((PyFileObject *)self)->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +00002135 Py_INCREF(Py_None);
2136 ((PyFileObject *)self)->f_errors = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002137 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002138 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002139 }
2140 return self;
2141}
2142
2143static int
2144file_init(PyObject *self, PyObject *args, PyObject *kwds)
2145{
2146 PyFileObject *foself = (PyFileObject *)self;
2147 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002148 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002149 char *name = NULL;
2150 char *mode = "r";
2151 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002152 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00002153
2154 assert(PyFile_Check(self));
2155 if (foself->f_fp != NULL) {
2156 /* Have to close the existing file first. */
2157 PyObject *closeresult = file_close(foself);
2158 if (closeresult == NULL)
2159 return -1;
2160 Py_DECREF(closeresult);
2161 }
Tim Peters59c9a642001-09-13 05:38:56 +00002162
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002163#ifdef Py_WIN_WIDE_FILENAMES
2164 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2165 PyObject *po;
2166 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2167 kwlist, &po, &mode, &bufsize)) {
2168 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002169 if (fill_file_fields(foself, NULL, po, mode,
2170 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002171 goto Error;
2172 } else {
2173 /* Drop the argument parsing error as narrow
2174 strings are also valid. */
2175 PyErr_Clear();
2176 }
2177 }
2178#endif
2179
2180 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002181 PyObject *o_name;
2182
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002183 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2184 Py_FileSystemDefaultEncoding,
2185 &name,
2186 &mode, &bufsize))
2187 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002188
2189 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002190 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2191 kwlist, &o_name, &mode,
2192 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002193 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002194
2195 if (fill_file_fields(foself, NULL, o_name, mode,
2196 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002197 goto Error;
2198 }
Tim Peters44410012001-09-14 03:26:08 +00002199 if (open_the_file(foself, name, mode) == NULL)
2200 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002201 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002202 PyFile_SetBufSize(self, bufsize);
2203 goto Done;
2204
2205Error:
2206 ret = -1;
2207 /* fall through */
2208Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002209 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002210 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002211}
2212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002213PyDoc_VAR(file_doc) =
2214PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002215"file(name[, mode[, buffering]]) -> file object\n"
2216"\n"
2217"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2218"writing or appending. The file will be created if it doesn't exist\n"
2219"when opened for writing or appending; it will be truncated when\n"
2220"opened for writing. Add a 'b' to the mode for binary files.\n"
2221"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2222"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002223"buffered, and larger numbers specify the buffer size. The preferred way\n"
2224"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002225)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002226PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002227"Add a 'U' to mode to open the file for input with universal newline\n"
2228"support. Any line ending in the input file will be seen as a '\\n'\n"
2229"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2230"the value for this attribute is one of None (no newline read yet),\n"
2231"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2232"\n"
2233"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002234);
Tim Peters59c9a642001-09-13 05:38:56 +00002235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002236PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002237 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002238 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002239 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002240 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002241 (destructor)file_dealloc, /* tp_dealloc */
2242 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002243 0, /* tp_getattr */
2244 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002245 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002247 0, /* tp_as_number */
2248 0, /* tp_as_sequence */
2249 0, /* tp_as_mapping */
2250 0, /* tp_hash */
2251 0, /* tp_call */
2252 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002254 /* softspace is writable: we must supply tp_setattro */
2255 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002256 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002257 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002258 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259 0, /* tp_traverse */
2260 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002261 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002262 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002263 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002264 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002265 file_methods, /* tp_methods */
2266 file_memberlist, /* tp_members */
2267 file_getsetlist, /* tp_getset */
2268 0, /* tp_base */
2269 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002270 0, /* tp_descr_get */
2271 0, /* tp_descr_set */
2272 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002273 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002274 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002275 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002276 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002277};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002278
2279/* Interface for the 'soft space' between print items. */
2280
2281int
Fred Drakefd99de62000-07-09 05:02:18 +00002282PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002283{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002284 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002285 if (f == NULL) {
2286 /* Do nothing */
2287 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002288 else if (PyFile_Check(f)) {
2289 oldflag = ((PyFileObject *)f)->f_softspace;
2290 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002291 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002292 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002293 PyObject *v;
2294 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002295 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002296 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002297 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002298 if (PyInt_Check(v))
2299 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002300 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002301 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002302 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002303 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002304 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002305 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002306 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002307 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2308 PyErr_Clear();
2309 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002310 }
2311 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002312 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002313}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002314
2315/* Interfaces to write objects/strings to file-like objects */
2316
2317int
Fred Drakefd99de62000-07-09 05:02:18 +00002318PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002319{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002320 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002321 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002323 return -1;
2324 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002325 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002326 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002327#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002328 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002329 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002330#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002331 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002332 err_closed();
2333 return -1;
2334 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002335#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002336 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002337 PyUnicode_Check(v) && enc != Py_None) {
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002338 char *cenc = PyString_AS_STRING(enc);
Martin v. Löwis99815892008-06-01 07:20:46 +00002339 char *errors = fobj->f_errors == Py_None ?
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002340 "strict" : PyString_AS_STRING(fobj->f_errors);
Martin v. Löwis99815892008-06-01 07:20:46 +00002341 value = PyUnicode_AsEncodedString(v, cenc, errors);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002342 if (value == NULL)
2343 return -1;
2344 } else {
2345 value = v;
2346 Py_INCREF(value);
2347 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002348 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002349 Py_DECREF(value);
2350 return result;
2351#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002352 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002353#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002354 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002355 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002356 if (writer == NULL)
2357 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002358 if (flags & Py_PRINT_RAW) {
2359 if (PyUnicode_Check(v)) {
2360 value = v;
2361 Py_INCREF(value);
2362 } else
2363 value = PyObject_Str(v);
2364 }
2365 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002366 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002367 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002368 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002369 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002370 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002371 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002372 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002373 Py_DECREF(value);
2374 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002375 return -1;
2376 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002377 result = PyEval_CallObject(writer, args);
2378 Py_DECREF(args);
2379 Py_DECREF(value);
2380 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002381 if (result == NULL)
2382 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002383 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002384 return 0;
2385}
2386
Guido van Rossum27a60b11997-05-22 22:25:11 +00002387int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002388PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002389{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002390
Guido van Rossum3165fe61992-09-25 21:59:05 +00002391 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002392 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002393 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002394 PyErr_SetString(PyExc_SystemError,
2395 "null file for PyFile_WriteString");
2396 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002397 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002398 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002399 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002400 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002401 if (fp == NULL) {
2402 err_closed();
2403 return -1;
2404 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002405 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002406 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002407 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002408 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002409 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002410 else if (!PyErr_Occurred()) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002411 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002412 int err;
2413 if (v == NULL)
2414 return -1;
2415 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2416 Py_DECREF(v);
2417 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002418 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002419 else
2420 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002421}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002422
2423/* Try to get a file-descriptor from a Python object. If the object
2424 is an integer or long integer, its value is returned. If not, the
2425 object's fileno() method is called if it exists; the method must return
2426 an integer or long integer, which is returned as the file descriptor value.
2427 -1 is returned on failure.
2428*/
2429
2430int PyObject_AsFileDescriptor(PyObject *o)
2431{
2432 int fd;
2433 PyObject *meth;
2434
2435 if (PyInt_Check(o)) {
2436 fd = PyInt_AsLong(o);
2437 }
2438 else if (PyLong_Check(o)) {
2439 fd = PyLong_AsLong(o);
2440 }
2441 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2442 {
2443 PyObject *fno = PyEval_CallObject(meth, NULL);
2444 Py_DECREF(meth);
2445 if (fno == NULL)
2446 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002447
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002448 if (PyInt_Check(fno)) {
2449 fd = PyInt_AsLong(fno);
2450 Py_DECREF(fno);
2451 }
2452 else if (PyLong_Check(fno)) {
2453 fd = PyLong_AsLong(fno);
2454 Py_DECREF(fno);
2455 }
2456 else {
2457 PyErr_SetString(PyExc_TypeError,
2458 "fileno() returned a non-integer");
2459 Py_DECREF(fno);
2460 return -1;
2461 }
2462 }
2463 else {
2464 PyErr_SetString(PyExc_TypeError,
2465 "argument must be an int, or have a fileno() method.");
2466 return -1;
2467 }
2468
2469 if (fd < 0) {
2470 PyErr_Format(PyExc_ValueError,
2471 "file descriptor cannot be a negative integer (%i)",
2472 fd);
2473 return -1;
2474 }
2475 return fd;
2476}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002477
Jack Jansen7b8c7542002-04-14 20:12:41 +00002478/* From here on we need access to the real fgets and fread */
2479#undef fgets
2480#undef fread
2481
2482/*
2483** Py_UniversalNewlineFgets is an fgets variation that understands
2484** all of \r, \n and \r\n conventions.
2485** The stream should be opened in binary mode.
2486** If fobj is NULL the routine always does newline conversion, and
2487** it may peek one char ahead to gobble the second char in \r\n.
2488** If fobj is non-NULL it must be a PyFileObject. In this case there
2489** is no readahead but in stead a flag is used to skip a following
2490** \n on the next read. Also, if the file is open in binary mode
2491** the whole conversion is skipped. Finally, the routine keeps track of
2492** the different types of newlines seen.
2493** Note that we need no error handling: fgets() treats error and eof
2494** identically.
2495*/
2496char *
2497Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2498{
2499 char *p = buf;
2500 int c;
2501 int newlinetypes = 0;
2502 int skipnextlf = 0;
2503 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002504
Jack Jansen7b8c7542002-04-14 20:12:41 +00002505 if (fobj) {
2506 if (!PyFile_Check(fobj)) {
2507 errno = ENXIO; /* What can you do... */
2508 return NULL;
2509 }
2510 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2511 if ( !univ_newline )
2512 return fgets(buf, n, stream);
2513 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2514 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2515 }
2516 FLOCKFILE(stream);
2517 c = 'x'; /* Shut up gcc warning */
2518 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2519 if (skipnextlf ) {
2520 skipnextlf = 0;
2521 if (c == '\n') {
2522 /* Seeing a \n here with skipnextlf true
2523 ** means we saw a \r before.
2524 */
2525 newlinetypes |= NEWLINE_CRLF;
2526 c = GETC(stream);
2527 if (c == EOF) break;
2528 } else {
2529 /*
2530 ** Note that c == EOF also brings us here,
2531 ** so we're okay if the last char in the file
2532 ** is a CR.
2533 */
2534 newlinetypes |= NEWLINE_CR;
2535 }
2536 }
2537 if (c == '\r') {
2538 /* A \r is translated into a \n, and we skip
2539 ** an adjacent \n, if any. We don't set the
2540 ** newlinetypes flag until we've seen the next char.
2541 */
2542 skipnextlf = 1;
2543 c = '\n';
2544 } else if ( c == '\n') {
2545 newlinetypes |= NEWLINE_LF;
2546 }
2547 *p++ = c;
2548 if (c == '\n') break;
2549 }
2550 if ( c == EOF && skipnextlf )
2551 newlinetypes |= NEWLINE_CR;
2552 FUNLOCKFILE(stream);
2553 *p = '\0';
2554 if (fobj) {
2555 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2556 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2557 } else if ( skipnextlf ) {
2558 /* If we have no file object we cannot save the
2559 ** skipnextlf flag. We have to readahead, which
2560 ** will cause a pause if we're reading from an
2561 ** interactive stream, but that is very unlikely
2562 ** unless we're doing something silly like
2563 ** execfile("/dev/tty").
2564 */
2565 c = GETC(stream);
2566 if ( c != '\n' )
2567 ungetc(c, stream);
2568 }
2569 if (p == buf)
2570 return NULL;
2571 return buf;
2572}
2573
2574/*
2575** Py_UniversalNewlineFread is an fread variation that understands
2576** all of \r, \n and \r\n conventions.
2577** The stream should be opened in binary mode.
2578** fobj must be a PyFileObject. In this case there
2579** is no readahead but in stead a flag is used to skip a following
2580** \n on the next read. Also, if the file is open in binary mode
2581** the whole conversion is skipped. Finally, the routine keeps track of
2582** the different types of newlines seen.
2583*/
2584size_t
Tim Peters058b1412002-04-21 07:29:14 +00002585Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002586 FILE *stream, PyObject *fobj)
2587{
Tim Peters058b1412002-04-21 07:29:14 +00002588 char *dst = buf;
2589 PyFileObject *f = (PyFileObject *)fobj;
2590 int newlinetypes, skipnextlf;
2591
2592 assert(buf != NULL);
2593 assert(stream != NULL);
2594
Jack Jansen7b8c7542002-04-14 20:12:41 +00002595 if (!fobj || !PyFile_Check(fobj)) {
2596 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002597 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002598 }
Tim Peters058b1412002-04-21 07:29:14 +00002599 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002600 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002601 newlinetypes = f->f_newlinetypes;
2602 skipnextlf = f->f_skipnextlf;
2603 /* Invariant: n is the number of bytes remaining to be filled
2604 * in the buffer.
2605 */
2606 while (n) {
2607 size_t nread;
2608 int shortread;
2609 char *src = dst;
2610
2611 nread = fread(dst, 1, n, stream);
2612 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002613 if (nread == 0)
2614 break;
2615
Tim Peterse1682a82002-04-21 18:15:20 +00002616 n -= nread; /* assuming 1 byte out for each in; will adjust */
2617 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002618 while (nread--) {
2619 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002620 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002621 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002622 *dst++ = '\n';
2623 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002624 }
2625 else if (skipnextlf && c == '\n') {
2626 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002627 skipnextlf = 0;
2628 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002629 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002630 }
2631 else {
2632 /* Normal char to be stored in buffer. Also
2633 * update the newlinetypes flag if either this
2634 * is an LF or the previous char was a CR.
2635 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002636 if (c == '\n')
2637 newlinetypes |= NEWLINE_LF;
2638 else if (skipnextlf)
2639 newlinetypes |= NEWLINE_CR;
2640 *dst++ = c;
2641 skipnextlf = 0;
2642 }
2643 }
Tim Peters058b1412002-04-21 07:29:14 +00002644 if (shortread) {
2645 /* If this is EOF, update type flags. */
2646 if (skipnextlf && feof(stream))
2647 newlinetypes |= NEWLINE_CR;
2648 break;
2649 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002650 }
Tim Peters058b1412002-04-21 07:29:14 +00002651 f->f_newlinetypes = newlinetypes;
2652 f->f_skipnextlf = skipnextlf;
2653 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002654}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002655
2656#ifdef __cplusplus
2657}
2658#endif