blob: 4f8c46b0de3f6957a8cc3a178c69c38a80c78f6f [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Mark Hammondc2e85bd2002-10-03 05:10:39 +000019#ifdef _MSC_VER
20/* Need GetVersion to see if on NT so safe to use _wfopen */
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#endif /* _MSC_VER */
24
Andrew MacIntyrec4874392002-02-26 11:36:35 +000025#if defined(PYOS_OS2) && defined(PYCC_GCC)
26#include <io.h>
27#endif
28
Guido van Rossumc0b618a1997-05-02 03:12:38 +000029#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000030
Guido van Rossumff7e83d1999-08-27 20:39:37 +000031#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000032#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000033#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Jack Jansen7b8c7542002-04-14 20:12:41 +000035#ifdef HAVE_GETC_UNLOCKED
36#define GETC(f) getc_unlocked(f)
37#define FLOCKFILE(f) flockfile(f)
38#define FUNLOCKFILE(f) funlockfile(f)
39#else
40#define GETC(f) getc(f)
41#define FLOCKFILE(f)
42#define FUNLOCKFILE(f)
43#endif
44
Jack Jansen7b8c7542002-04-14 20:12:41 +000045/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000050
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000051/*
52 * These macros release the GIL while preventing the f_close() function being
53 * called in the interval between them. For that purpose, a running total of
54 * the number of currently running unlocked code sections is kept in
55 * the unlocked_count field of the PyFileObject. The close() method raises
56 * an IOError if that field is non-zero. See issue #815646, #595601.
57 */
58
59#define FILE_BEGIN_ALLOW_THREADS(fobj) \
60{ \
61 fobj->unlocked_count++; \
62 Py_BEGIN_ALLOW_THREADS
63
64#define FILE_END_ALLOW_THREADS(fobj) \
65 Py_END_ALLOW_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0); \
68}
69
70#define FILE_ABORT_ALLOW_THREADS(fobj) \
71 Py_BLOCK_THREADS \
72 fobj->unlocked_count--; \
73 assert(fobj->unlocked_count >= 0);
74
Anthony Baxterac6bd462006-04-13 02:06:09 +000075#ifdef __cplusplus
76extern "C" {
77#endif
78
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000080PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000081{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000082 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000084 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086}
87
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000088void PyFile_IncUseCount(PyFileObject *fobj)
89{
90 fobj->unlocked_count++;
91}
92
93void PyFile_DecUseCount(PyFileObject *fobj)
94{
95 fobj->unlocked_count--;
96 assert(fobj->unlocked_count >= 0);
97}
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000100PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000103 return NULL;
104 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000106}
107
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000108/* This is a safe wrapper around PyObject_Print to print to the FILE
109 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
110 about PyFileObject. */
111static int
112file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
113{
114 int result;
115 PyFile_IncUseCount(f);
116 result = PyObject_Print(op, f->f_fp, flags);
117 PyFile_DecUseCount(f);
118 return result;
119}
120
Neil Schemenauered19b882002-03-23 02:06:50 +0000121/* On Unix, fopen will succeed for directories.
122 In Python, there should be no file objects referring to
123 directories, so we need a check. */
124
125static PyFileObject*
126dircheck(PyFileObject* f)
127{
128#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
129 struct stat buf;
130 if (f->f_fp == NULL)
131 return f;
132 if (fstat(fileno(f->f_fp), &buf) == 0 &&
133 S_ISDIR(buf.st_mode)) {
Neil Schemenauered19b882002-03-23 02:06:50 +0000134 char *msg = strerror(EISDIR);
Tim Petersf1827cf2003-09-07 03:30:18 +0000135 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +0000136 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +0000137 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000138 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000139 return NULL;
140 }
141#endif
142 return f;
143}
144
Tim Peters59c9a642001-09-13 05:38:56 +0000145
146static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000147fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
148 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000150 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000151 assert(f != NULL);
152 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000153 assert(f->f_fp == NULL);
154
155 Py_DECREF(f->f_name);
156 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000157 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000158
Neal Norwitzb337bb52006-07-17 00:55:45 +0000159 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000160 f->f_name = name;
161
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000163
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000164 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000165 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000166 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000167 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000168 f->f_univ_newline = (strchr(mode, 'U') != NULL);
169 f->f_newlinetypes = NEWLINE_UNKNOWN;
170 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000171 Py_INCREF(Py_None);
172 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000173
Neal Norwitzb337bb52006-07-17 00:55:45 +0000174 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000177 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179}
180
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000181/* check for known incorrect mode strings - problem is, platforms are
182 free to accept any mode characters they like and are supposed to
183 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000184 universal newline support is expressly forbidden by PEP 278.
185 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000186 won't know what it is. Non-zero return signals an exception */
187int
188_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000189{
Georg Brandl7b90e162006-05-18 07:01:27 +0000190 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000191 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000192
Georg Brandl7b90e162006-05-18 07:01:27 +0000193 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000194 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000195 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000196 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000197
Georg Brandl7b90e162006-05-18 07:01:27 +0000198 upos = strchr(mode, 'U');
199 if (upos) {
200 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000201
Georg Brandl7b90e162006-05-18 07:01:27 +0000202 if (mode[0] == 'w' || mode[0] == 'a') {
203 PyErr_Format(PyExc_ValueError, "universal newline "
204 "mode can only be used with modes "
205 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000206 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000207 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000208
209 if (mode[0] != 'r') {
210 memmove(mode+1, mode, strlen(mode)+1);
211 mode[0] = 'r';
212 }
213
214 if (!strchr(mode, 'b')) {
215 memmove(mode+2, mode+1, strlen(mode));
216 mode[1] = 'b';
217 }
218 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
219 PyErr_Format(PyExc_ValueError, "mode string must begin with "
220 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000221 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000222 }
223
224 return 0;
225}
226
Tim Peters59c9a642001-09-13 05:38:56 +0000227static PyObject *
228open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Georg Brandl7b90e162006-05-18 07:01:27 +0000230 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000231 assert(f != NULL);
232 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000233#ifdef MS_WINDOWS
234 /* windows ignores the passed name in order to support Unicode */
235 assert(f->f_name != NULL);
236#else
Tim Peters59c9a642001-09-13 05:38:56 +0000237 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000238#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000239 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000240 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000241
Georg Brandl7b90e162006-05-18 07:01:27 +0000242 /* probably need to replace 'U' by 'rb' */
243 newmode = PyMem_MALLOC(strlen(mode) + 3);
244 if (!newmode) {
245 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000246 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000247 }
248 strcpy(newmode, mode);
249
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000250 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000251 f = NULL;
252 goto cleanup;
253 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000254
Tim Peters8fa45672001-09-13 21:01:29 +0000255 /* rexec.py can't stop a user from getting the file() constructor --
256 all they have to do is get *any* file object f, and then do
257 type(f). Here we prevent them from doing damage with it. */
258 if (PyEval_GetRestricted()) {
259 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000260 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000261 f = NULL;
262 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000263 }
Tim Petersa27a1502001-11-09 20:59:14 +0000264 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000265
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000266#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000267 if (PyUnicode_Check(f->f_name)) {
268 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000269 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000270 if (f->f_name && wmode) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000271 FILE_BEGIN_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000272 /* PyUnicode_AS_UNICODE OK without thread
273 lock as it is a simple dereference. */
274 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
275 PyUnicode_AS_UNICODE(wmode));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000276 FILE_END_ALLOW_THREADS(f)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000277 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000278 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000279 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000280#endif
281 if (NULL == f->f_fp && NULL != name) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000282 FILE_BEGIN_ALLOW_THREADS(f)
Georg Brandl7b90e162006-05-18 07:01:27 +0000283 f->f_fp = fopen(name, newmode);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000284 FILE_END_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000285 }
286
Guido van Rossuma08095a1991-02-13 23:25:27 +0000287 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000288#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000289 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
290 * across all Windows flavors. When it sets EINVAL varies
291 * across Windows flavors, the exact conditions aren't
292 * documented, and the answer lies in the OS's implementation
293 * of Win32's CreateFile function (whose source is secret).
294 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000295 * Starting with Visual Studio .NET 2005, EINVAL is correctly
296 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000297 */
298 if (errno == 0) /* bad mode string */
299 errno = EINVAL;
300 else if (errno == EINVAL) /* unknown, but not a mode string */
301 errno = ENOENT;
302#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000303 /* EINVAL is returned when an invalid filename or
304 * an invalid mode is supplied. */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000305 if (errno == EINVAL)
Gregory P. Smith887290d2008-03-18 00:20:01 +0000306 PyErr_Format(PyExc_IOError,
307 "invalid filename: %s or mode: %s",
308 name, mode);
Jeremy Hylton41c83212001-11-09 16:17:24 +0000309 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000310 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000311 f = NULL;
312 }
Tim Peters2ea91112002-04-08 04:13:12 +0000313 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000314 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000315
316cleanup:
317 PyMem_FREE(newmode);
318
Tim Peters59c9a642001-09-13 05:38:56 +0000319 return (PyObject *)f;
320}
321
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000322static PyObject *
323close_the_file(PyFileObject *f)
324{
325 int sts = 0;
326 int (*local_close)(FILE *);
327 FILE *local_fp = f->f_fp;
328 if (local_fp != NULL) {
329 local_close = f->f_close;
330 if (local_close != NULL && f->unlocked_count > 0) {
331 if (f->ob_refcnt > 0) {
332 PyErr_SetString(PyExc_IOError,
333 "close() called during concurrent "
334 "operation on the same file object.");
335 } else {
336 /* This should not happen unless someone is
337 * carelessly playing with the PyFileObject
338 * struct fields and/or its associated FILE
339 * pointer. */
340 PyErr_SetString(PyExc_SystemError,
341 "PyFileObject locking error in "
342 "destructor (refcnt <= 0 at close).");
343 }
344 return NULL;
345 }
346 /* NULL out the FILE pointer before releasing the GIL, because
347 * it will not be valid anymore after the close() function is
348 * called. */
349 f->f_fp = NULL;
350 if (local_close != NULL) {
351 Py_BEGIN_ALLOW_THREADS
352 errno = 0;
353 sts = (*local_close)(local_fp);
354 Py_END_ALLOW_THREADS
355 if (sts == EOF)
356 return PyErr_SetFromErrno(PyExc_IOError);
357 if (sts != 0)
358 return PyInt_FromLong((long)sts);
359 }
360 }
361 Py_RETURN_NONE;
362}
363
Tim Peters59c9a642001-09-13 05:38:56 +0000364PyObject *
365PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
366{
Tim Peters44410012001-09-14 03:26:08 +0000367 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
368 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000369 if (f != NULL) {
Neal Norwitzb337bb52006-07-17 00:55:45 +0000370 PyObject *o_name = PyString_FromString(name);
371 if (o_name == NULL)
372 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000373 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000374 Py_DECREF(f);
375 f = NULL;
376 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000377 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000378 }
379 return (PyObject *) f;
380}
381
382PyObject *
383PyFile_FromString(char *name, char *mode)
384{
385 extern int fclose(FILE *);
386 PyFileObject *f;
387
388 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
389 if (f != NULL) {
390 if (open_the_file(f, name, mode) == NULL) {
391 Py_DECREF(f);
392 f = NULL;
393 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Guido van Rossumb6775db1994-08-01 11:34:53 +0000398void
Fred Drakefd99de62000-07-09 05:02:18 +0000399PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000400{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000401 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000402 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000403 int type;
404 switch (bufsize) {
405 case 0:
406 type = _IONBF;
407 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000408#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000409 case 1:
410 type = _IOLBF;
411 bufsize = BUFSIZ;
412 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000413#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000414 default:
415 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000416#ifndef HAVE_SETVBUF
417 bufsize = BUFSIZ;
418#endif
419 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000420 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000421 fflush(file->f_fp);
422 if (type == _IONBF) {
423 PyMem_Free(file->f_setbuf);
424 file->f_setbuf = NULL;
425 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000426 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
427 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000428 }
429#ifdef HAVE_SETVBUF
430 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000431#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000432 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000433#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000434 }
435}
436
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000437/* Set the encoding used to output Unicode strings.
438 Returh 1 on success, 0 on failure. */
439
440int
441PyFile_SetEncoding(PyObject *f, const char *enc)
442{
443 PyFileObject *file = (PyFileObject*)f;
444 PyObject *str = PyString_FromString(enc);
Thomas Woutersafea5292007-01-23 13:42:00 +0000445
446 assert(PyFile_Check(f));
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000447 if (!str)
448 return 0;
449 Py_DECREF(file->f_encoding);
450 file->f_encoding = str;
451 return 1;
452}
453
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000455err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000456{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000458 return NULL;
459}
460
Thomas Woutersc45251a2006-02-12 11:53:32 +0000461/* Refuse regular file I/O if there's data in the iteration-buffer.
462 * Mixing them would cause data to arrive out of order, as the read*
463 * methods don't use the iteration buffer. */
464static PyObject *
465err_iterbuffered(void)
466{
467 PyErr_SetString(PyExc_ValueError,
468 "Mixing iteration and read methods would lose data");
469 return NULL;
470}
471
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000472static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000473
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474/* Methods */
475
476static void
Fred Drakefd99de62000-07-09 05:02:18 +0000477file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000478{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000479 PyObject *ret;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000480 if (f->weakreflist != NULL)
481 PyObject_ClearWeakRefs((PyObject *) f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000482 ret = close_the_file(f);
483 if (!ret) {
484 PySys_WriteStderr("close failed in file object destructor:\n");
485 PyErr_Print();
486 }
487 else {
488 Py_DECREF(ret);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000489 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000490 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000491 Py_XDECREF(f->f_name);
492 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000493 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000494 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000495 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496}
497
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000499file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000501 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000502#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000503 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000504 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
505 const char *name_str = name ? PyString_AsString(name) : "?";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000506 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
507 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000508 name_str,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000509 PyString_AsString(f->f_mode),
510 f);
511 Py_XDECREF(name);
512 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000513#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000514 } else {
515 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000516 f->f_fp == NULL ? "closed" : "open",
517 PyString_AsString(f->f_name),
518 PyString_AsString(f->f_mode),
519 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000520 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521}
522
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000524file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000526 PyObject *sts = close_the_file(f);
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000527 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000528 f->f_setbuf = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000529 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530}
531
Trent Mickf29f47b2000-08-11 19:02:59 +0000532
Guido van Rossumb8552162001-09-05 14:58:11 +0000533/* Our very own off_t-like type, 64-bit if possible */
534#if !defined(HAVE_LARGEFILE_SUPPORT)
535typedef off_t Py_off_t;
536#elif SIZEOF_OFF_T >= 8
537typedef off_t Py_off_t;
538#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000539typedef fpos_t Py_off_t;
540#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000541#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000542#endif
543
544
Trent Mickf29f47b2000-08-11 19:02:59 +0000545/* a portable fseek() function
546 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000547static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000548_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000549{
Guido van Rossumb8552162001-09-05 14:58:11 +0000550#if !defined(HAVE_LARGEFILE_SUPPORT)
551 return fseek(fp, offset, whence);
552#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000553 return fseeko(fp, offset, whence);
554#elif defined(HAVE_FSEEK64)
555 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000556#elif defined(__BEOS__)
557 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000558#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000559 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
560 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000561 fpos_t pos;
562 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000563 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000564#ifdef MS_WINDOWS
565 fflush(fp);
566 if (_lseeki64(fileno(fp), 0, 2) == -1)
567 return -1;
568#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000569 if (fseek(fp, 0, SEEK_END) != 0)
570 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000571#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000572 /* fall through */
573 case SEEK_CUR:
574 if (fgetpos(fp, &pos) != 0)
575 return -1;
576 offset += pos;
577 break;
578 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000579 }
580 return fsetpos(fp, &offset);
581#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000582#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000583#endif
584}
585
586
587/* a portable ftell() function
588 Return -1 on failure with errno set appropriately, current file
589 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000590static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000591_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000592{
Guido van Rossumb8552162001-09-05 14:58:11 +0000593#if !defined(HAVE_LARGEFILE_SUPPORT)
594 return ftell(fp);
595#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
596 return ftello(fp);
597#elif defined(HAVE_FTELL64)
598 return ftell64(fp);
599#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000600 fpos_t pos;
601 if (fgetpos(fp, &pos) != 0)
602 return -1;
603 return pos;
604#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000605#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000606#endif
607}
608
609
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000611file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000612{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000613 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000614 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000615 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000616 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000617
Guido van Rossumd7297e61992-07-06 14:19:26 +0000618 if (f->f_fp == NULL)
619 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000620 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000621 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000622 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000623 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000624 off_index = PyNumber_Index(offobj);
625 if (!off_index) {
626 if (!PyFloat_Check(offobj))
627 return NULL;
628 /* Deprecated in 2.6 */
629 PyErr_Clear();
Benjamin Petersonf19a7b92008-04-27 18:40:21 +0000630 if (PyErr_WarnEx(PyExc_DeprecationWarning,
631 "integer argument expected, got float",
632 1) < 0)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000633 return NULL;
634 off_index = offobj;
635 Py_INCREF(offobj);
636 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000637#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000638 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000639#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000640 offset = PyLong_Check(off_index) ?
641 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000642#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000643 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000644 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000645 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000646
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000647 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000648 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000649 ret = _portable_fseek(f->f_fp, offset, whence);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000650 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000651
Guido van Rossumff4949e1992-08-05 19:58:53 +0000652 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000654 clearerr(f->f_fp);
655 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000656 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000657 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000658 Py_INCREF(Py_None);
659 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000660}
661
Trent Mickf29f47b2000-08-11 19:02:59 +0000662
Guido van Rossumd7047b31995-01-02 19:07:15 +0000663#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000664static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000665file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000666{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000667 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000668 PyObject *newsizeobj = NULL;
669 Py_off_t initialpos;
670 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000671
Guido van Rossumd7047b31995-01-02 19:07:15 +0000672 if (f->f_fp == NULL)
673 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000674 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000675 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000676
Tim Petersf1827cf2003-09-07 03:30:18 +0000677 /* Get current file position. If the file happens to be open for
678 * update and the last operation was an input operation, C doesn't
679 * define what the later fflush() will do, but we promise truncate()
680 * won't change the current position (and fflush() *does* change it
681 * then at least on Windows). The easiest thing is to capture
682 * current pos now and seek back to it at the end.
683 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000684 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000685 errno = 0;
686 initialpos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000687 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000688 if (initialpos == -1)
689 goto onioerror;
690
Tim Petersfb05db22002-03-11 00:24:00 +0000691 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000692 * specified value.
693 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000694 if (newsizeobj != NULL) {
695#if !defined(HAVE_LARGEFILE_SUPPORT)
696 newsize = PyInt_AsLong(newsizeobj);
697#else
698 newsize = PyLong_Check(newsizeobj) ?
699 PyLong_AsLongLong(newsizeobj) :
700 PyInt_AsLong(newsizeobj);
701#endif
702 if (PyErr_Occurred())
703 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000704 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000705 else /* default to current position */
706 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000707
Tim Petersf1827cf2003-09-07 03:30:18 +0000708 /* Flush the stream. We're mixing stream-level I/O with lower-level
709 * I/O, and a flush may be necessary to synch both platform views
710 * of the current file state.
711 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000712 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000713 errno = 0;
714 ret = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000715 FILE_END_ALLOW_THREADS(f)
Tim Petersfb05db22002-03-11 00:24:00 +0000716 if (ret != 0)
717 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000718
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000719#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000720 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000721 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000722 {
Tim Petersfb05db22002-03-11 00:24:00 +0000723 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000724
Tim Petersf1827cf2003-09-07 03:30:18 +0000725 /* Have to move current pos to desired endpoint on Windows. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000726 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000727 errno = 0;
728 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000729 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000730 if (ret)
731 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000732
Tim Peters8f01b682002-03-12 03:04:44 +0000733 /* Truncate. Note that this may grow the file! */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000734 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters8f01b682002-03-12 03:04:44 +0000735 errno = 0;
736 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000737 ret = hFile == (HANDLE)-1;
738 if (ret == 0) {
739 ret = SetEndOfFile(hFile) == 0;
740 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000741 errno = EACCES;
742 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000743 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000744 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000745 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000746 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000747#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000748 FILE_BEGIN_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000749 errno = 0;
750 ret = ftruncate(fileno(f->f_fp), newsize);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000751 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000752 if (ret != 0)
753 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000754#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000755
Tim Petersf1827cf2003-09-07 03:30:18 +0000756 /* Restore original file position. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000757 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000758 errno = 0;
759 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000760 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000761 if (ret)
762 goto onioerror;
763
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764 Py_INCREF(Py_None);
765 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000766
767onioerror:
768 PyErr_SetFromErrno(PyExc_IOError);
769 clearerr(f->f_fp);
770 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000771}
772#endif /* HAVE_FTRUNCATE */
773
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000774static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000775file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000776{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000777 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000778
Guido van Rossumd7297e61992-07-06 14:19:26 +0000779 if (f->f_fp == NULL)
780 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000781 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000782 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000783 pos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000784 FILE_END_ALLOW_THREADS(f)
785
Trent Mickf29f47b2000-08-11 19:02:59 +0000786 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000787 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000788 clearerr(f->f_fp);
789 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000790 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000791 if (f->f_skipnextlf) {
792 int c;
793 c = GETC(f->f_fp);
794 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000795 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000796 pos++;
797 f->f_skipnextlf = 0;
798 } else if (c != EOF) ungetc(c, f->f_fp);
799 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000800#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000801 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000802#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000803 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000804#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000805}
806
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000807static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000808file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000809{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000810 if (f->f_fp == NULL)
811 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000813}
814
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000815static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000816file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000817{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000818 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000819
Guido van Rossumd7297e61992-07-06 14:19:26 +0000820 if (f->f_fp == NULL)
821 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000822 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000823 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000824 res = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000825 FILE_END_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000826 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000827 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000828 clearerr(f->f_fp);
829 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000830 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000831 Py_INCREF(Py_None);
832 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000833}
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000836file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000837{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000838 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000839 if (f->f_fp == NULL)
840 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000841 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000842 res = isatty((int)fileno(f->f_fp));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000843 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000844 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000845}
846
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000847
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000848#if BUFSIZ < 8192
849#define SMALLCHUNK 8192
850#else
851#define SMALLCHUNK BUFSIZ
852#endif
853
Guido van Rossum3c259041999-01-14 19:00:14 +0000854#if SIZEOF_INT < 4
855#define BIGCHUNK (512 * 32)
856#else
857#define BIGCHUNK (512 * 1024)
858#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000859
860static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000861new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000862{
863#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000864 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000865 struct stat st;
866 if (fstat(fileno(f->f_fp), &st) == 0) {
867 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000868 /* The following is not a bug: we really need to call lseek()
869 *and* ftell(). The reason is that some stdio libraries
870 mistakenly flush their buffer when ftell() is called and
871 the lseek() call it makes fails, thereby throwing away
872 data that cannot be recovered in any way. To avoid this,
873 we first test lseek(), and only call ftell() if lseek()
874 works. We can't use the lseek() value either, because we
875 need to take the amount of buffered data into account.
876 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000877 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000878 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000879 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000880 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000881 if (pos < 0)
882 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000883 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000884 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000885 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000886 }
887#endif
888 if (currentsize > SMALLCHUNK) {
889 /* Keep doubling until we reach BIGCHUNK;
890 then keep adding BIGCHUNK. */
891 if (currentsize <= BIGCHUNK)
892 return currentsize + currentsize;
893 else
894 return currentsize + BIGCHUNK;
895 }
896 return currentsize + SMALLCHUNK;
897}
898
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000899#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
900#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
901#else
902#ifdef EWOULDBLOCK
903#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
904#else
905#ifdef EAGAIN
906#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
907#else
908#define BLOCKED_ERRNO(x) 0
909#endif
910#endif
911#endif
912
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000913static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000914file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000915{
Guido van Rossum789a1611997-05-10 22:33:55 +0000916 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000917 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000918 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000919
Guido van Rossumd7297e61992-07-06 14:19:26 +0000920 if (f->f_fp == NULL)
921 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000922 /* refuse to mix with f.next() */
923 if (f->f_buf != NULL &&
924 (f->f_bufend - f->f_bufptr) > 0 &&
925 f->f_buf[0] != '\0')
926 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000927 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000928 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000929 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000930 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000931 else
932 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +0000933 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000934 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000935 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000936 return NULL;
937 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000938 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000939 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000940 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000941 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000942 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000943 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +0000944 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000945 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000946 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000947 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +0000948 if (chunksize == 0) {
949 if (!ferror(f->f_fp))
950 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000951 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000952 /* When in non-blocking mode, data shouldn't
953 * be discarded if a blocking signal was
954 * received. That will also happen if
955 * chunksize != 0, but bytesread < buffersize. */
956 if (bytesread > 0 && BLOCKED_ERRNO(errno))
957 break;
958 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000959 Py_DECREF(v);
960 return NULL;
961 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000962 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000963 if (bytesread < buffersize) {
964 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000965 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000966 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000967 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000968 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000969 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000970 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000971 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000972 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000973 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000974 }
975 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000976 if (bytesread != buffersize)
977 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000978 return v;
979}
980
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000981static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000982file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000983{
984 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000985 Py_ssize_t ntodo;
986 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000987
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000988 if (f->f_fp == NULL)
989 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000990 /* refuse to mix with f.next() */
991 if (f->f_buf != NULL &&
992 (f->f_bufend - f->f_bufptr) > 0 &&
993 f->f_buf[0] != '\0')
994 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000995 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000996 return NULL;
997 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000998 while (ntodo > 0) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000999 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001000 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +00001001 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001002 (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001003 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001004 if (nnow == 0) {
1005 if (!ferror(f->f_fp))
1006 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001007 PyErr_SetFromErrno(PyExc_IOError);
1008 clearerr(f->f_fp);
1009 return NULL;
1010 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001011 ndone += nnow;
1012 ntodo -= nnow;
1013 }
Neal Norwitz076d1e02006-08-21 18:20:10 +00001014 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001015}
1016
Tim Peters86821b22001-01-07 21:19:34 +00001017/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001018Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001019
1020Under MSVC 6:
1021
Tim Peters1c733232001-01-08 04:02:07 +00001022+ MS threadsafe getc is very slow (multiple layers of function calls before+
1023 after each character, to lock+unlock the stream).
1024+ The stream-locking functions are MS-internal -- can't access them from user
1025 code.
1026+ There's nothing Tim could find in the MS C or platform SDK libraries that
1027 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001028+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1029
1030So we use fgets for speed(!), despite that it's painful.
1031
1032MS realloc is also slow.
1033
Tim Petersf29b64d2001-01-15 06:33:19 +00001034Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1035have):
1036 Linux a wash
1037 Solaris a wash
1038 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001039
Tim Petersf29b64d2001-01-15 06:33:19 +00001040CAUTION: The C std isn't clear about this: in those cases where fgets
1041writes something into the buffer, can it write into any position beyond the
1042required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1043known on which it does; and it would be a strange way to code fgets. Still,
1044getline_via_fgets may not work correctly if it does. The std test
1045test_bufio.py should fail if platform fgets() routinely writes beyond the
1046trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001047**************************************************************************/
1048
Tim Petersf29b64d2001-01-15 06:33:19 +00001049/* Use this routine if told to, or by default on non-get_unlocked()
1050 * platforms unless told not to. Yikes! Let's spell that out:
1051 * On a platform with getc_unlocked():
1052 * By default, use getc_unlocked().
1053 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1054 * On a platform without getc_unlocked():
1055 * By default, use fgets().
1056 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1057 */
1058#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1059#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001060#endif
1061
Tim Petersf29b64d2001-01-15 06:33:19 +00001062#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1063#undef USE_FGETS_IN_GETLINE
1064#endif
1065
1066#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001067static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001068getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001069{
Tim Peters15b83852001-01-08 00:53:12 +00001070/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001071 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1072 * to fill this much of the buffer with a known value in order to figure out
1073 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1074 * than "most" lines, we waste time filling unused buffer slots. 100 is
1075 * surely adequate for most peoples' email archives, chewing over source code,
1076 * etc -- "regular old text files".
1077 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1078 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1079 * cautions about boosting that. 300 was chosen because the worst real-life
1080 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1081 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001082 */
Tim Peters142297a2001-01-15 10:36:56 +00001083#define INITBUFSIZE 100
1084#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001085 char* p; /* temp */
1086 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001087 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001088 char* pvfree; /* address of next free slot */
1089 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001090 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1091 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001092 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001093 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001094
Tim Peters15b83852001-01-08 00:53:12 +00001095 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001096 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001097 */
Tim Peters142297a2001-01-15 10:36:56 +00001098 total_v_size = INITBUFSIZE; /* start small and pray */
1099 pvfree = buf;
1100 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001101 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters142297a2001-01-15 10:36:56 +00001102 pvend = buf + total_v_size;
1103 nfree = pvend - pvfree;
1104 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1106 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001107 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001108
Tim Peters142297a2001-01-15 10:36:56 +00001109 if (p == NULL) {
1110 clearerr(fp);
1111 if (PyErr_CheckSignals())
1112 return NULL;
1113 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001114 return v;
1115 }
Tim Peters142297a2001-01-15 10:36:56 +00001116 /* fgets read *something* */
1117 p = memchr(pvfree, '\n', nfree);
1118 if (p != NULL) {
1119 /* Did the \n come from fgets or from us?
1120 * Since fgets stops at the first \n, and then writes
1121 * \0, if it's from fgets a \0 must be next. But if
1122 * that's so, it could not have come from us, since
1123 * the \n's we filled the buffer with have only more
1124 * \n's to the right.
1125 */
1126 if (p+1 < pvend && *(p+1) == '\0') {
1127 /* It's from fgets: we win! In particular,
1128 * we haven't done any mallocs yet, and can
1129 * build the final result on the first try.
1130 */
1131 ++p; /* include \n from fgets */
1132 }
1133 else {
1134 /* Must be from us: fgets didn't fill the
1135 * buffer and didn't find a newline, so it
1136 * must be the last and newline-free line of
1137 * the file.
1138 */
1139 assert(p > pvfree && *(p-1) == '\0');
1140 --p; /* don't include \0 from fgets */
1141 }
1142 v = PyString_FromStringAndSize(buf, p - buf);
1143 return v;
1144 }
1145 /* yuck: fgets overwrote all the newlines, i.e. the entire
1146 * buffer. So this line isn't over yet, or maybe it is but
1147 * we're exactly at EOF. If we haven't already, try using the
1148 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001149 */
Tim Peters142297a2001-01-15 10:36:56 +00001150 assert(*(pvend-1) == '\0');
1151 if (pvfree == buf) {
1152 pvfree = pvend - 1; /* overwrite trailing null */
1153 total_v_size = MAXBUFSIZE;
1154 }
1155 else
1156 break;
Tim Peters86821b22001-01-07 21:19:34 +00001157 }
Tim Peters142297a2001-01-15 10:36:56 +00001158
1159 /* The stack buffer isn't big enough; malloc a string object and read
1160 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001161 */
Tim Petersddea2082002-03-23 10:03:50 +00001162 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001163 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001164 if (v == NULL)
1165 return v;
1166 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001167 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1168 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001169
1170 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001171 * after setting p one beyond the end of the line. The code here is
1172 * very much like the code above, except reads into v's buffer; see
1173 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001174 */
1175 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001176 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001177 pvend = BUF(v) + total_v_size;
1178 nfree = pvend - pvfree;
1179 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001180 assert(nfree < INT_MAX);
1181 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001182 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001183
1184 if (p == NULL) {
1185 clearerr(fp);
1186 if (PyErr_CheckSignals()) {
1187 Py_DECREF(v);
1188 return NULL;
1189 }
1190 p = pvfree;
1191 break;
1192 }
Tim Peters86821b22001-01-07 21:19:34 +00001193 p = memchr(pvfree, '\n', nfree);
1194 if (p != NULL) {
1195 if (p+1 < pvend && *(p+1) == '\0') {
1196 /* \n came from fgets */
1197 ++p;
1198 break;
1199 }
1200 /* \n came from us; last line of file, no newline */
1201 assert(p > pvfree && *(p-1) == '\0');
1202 --p;
1203 break;
1204 }
1205 /* expand buffer and try again */
1206 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001207 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001208 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001209 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001210 /* check for overflow */
1211 if (total_v_size <= prev_v_size ||
1212 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001213 PyErr_SetString(PyExc_OverflowError,
1214 "line is longer than a Python string can hold");
1215 Py_DECREF(v);
1216 return NULL;
1217 }
1218 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1219 return NULL;
1220 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001221 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001222 }
1223 if (BUF(v) + total_v_size != p)
1224 _PyString_Resize(&v, p - BUF(v));
1225 return v;
1226#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001227#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001228}
Tim Petersf29b64d2001-01-15 06:33:19 +00001229#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001230
Guido van Rossum0bd24411991-04-04 15:21:57 +00001231/* Internal routine to get a line.
1232 Size argument interpretation:
1233 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001234 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001235*/
1236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001237static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001238get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001239{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001240 FILE *fp = f->f_fp;
1241 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001242 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001243 size_t total_v_size; /* total # of slots in buffer */
1244 size_t used_v_size; /* # used slots in buffer */
1245 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001246 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001247 int newlinetypes = f->f_newlinetypes;
1248 int skipnextlf = f->f_skipnextlf;
1249 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001250
Jack Jansen7b8c7542002-04-14 20:12:41 +00001251#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001252 if (n <= 0 && !univ_newline )
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001253 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001254#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001255 total_v_size = n > 0 ? n : 100;
1256 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001257 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001258 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001259 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001260 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001261
Guido van Rossumce5ba841991-03-06 13:06:18 +00001262 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001263 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001264 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001265 if (univ_newline) {
1266 c = 'x'; /* Shut up gcc warning */
1267 while ( buf != end && (c = GETC(fp)) != EOF ) {
1268 if (skipnextlf ) {
1269 skipnextlf = 0;
1270 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001271 /* Seeing a \n here with
1272 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001273 * saw a \r before.
1274 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001275 newlinetypes |= NEWLINE_CRLF;
1276 c = GETC(fp);
1277 if (c == EOF) break;
1278 } else {
1279 newlinetypes |= NEWLINE_CR;
1280 }
1281 }
1282 if (c == '\r') {
1283 skipnextlf = 1;
1284 c = '\n';
1285 } else if ( c == '\n')
1286 newlinetypes |= NEWLINE_LF;
1287 *buf++ = c;
1288 if (c == '\n') break;
1289 }
1290 if ( c == EOF && skipnextlf )
1291 newlinetypes |= NEWLINE_CR;
1292 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001293 while ((c = GETC(fp)) != EOF &&
1294 (*buf++ = c) != '\n' &&
1295 buf != end)
1296 ;
1297 FUNLOCKFILE(fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001298 FILE_END_ALLOW_THREADS(f)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001299 f->f_newlinetypes = newlinetypes;
1300 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001301 if (c == '\n')
1302 break;
1303 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001304 if (ferror(fp)) {
1305 PyErr_SetFromErrno(PyExc_IOError);
1306 clearerr(fp);
1307 Py_DECREF(v);
1308 return NULL;
1309 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001310 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001311 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001312 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001313 return NULL;
1314 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001315 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001316 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001317 /* Must be because buf == end */
1318 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001319 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001320 used_v_size = total_v_size;
1321 increment = total_v_size >> 2; /* mild exponential growth */
1322 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001323 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001324 PyErr_SetString(PyExc_OverflowError,
1325 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001326 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001327 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001328 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001329 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001330 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001331 buf = BUF(v) + used_v_size;
1332 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001333 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001334
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001335 used_v_size = buf - BUF(v);
1336 if (used_v_size != total_v_size)
1337 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001338 return v;
1339}
1340
Guido van Rossum0bd24411991-04-04 15:21:57 +00001341/* External C interface */
1342
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001343PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001344PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001345{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001346 PyObject *result;
1347
Guido van Rossum3165fe61992-09-25 21:59:05 +00001348 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001349 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001350 return NULL;
1351 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001352
1353 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001354 PyFileObject *fo = (PyFileObject *)f;
1355 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001356 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001357 /* refuse to mix with f.next() */
1358 if (fo->f_buf != NULL &&
1359 (fo->f_bufend - fo->f_bufptr) > 0 &&
1360 fo->f_buf[0] != '\0')
1361 return err_iterbuffered();
1362 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001363 }
1364 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365 PyObject *reader;
1366 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001367
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001368 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001369 if (reader == NULL)
1370 return NULL;
1371 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001372 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001373 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001374 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001375 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001377 return NULL;
1378 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001379 result = PyEval_CallObject(reader, args);
1380 Py_DECREF(reader);
1381 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001382 if (result != NULL && !PyString_Check(result) &&
1383 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001384 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001385 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001386 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001387 "object.readline() returned non-string");
1388 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001389 }
1390
1391 if (n < 0 && result != NULL && PyString_Check(result)) {
1392 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001393 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001394 if (len == 0) {
1395 Py_DECREF(result);
1396 result = NULL;
1397 PyErr_SetString(PyExc_EOFError,
1398 "EOF when reading a line");
1399 }
1400 else if (s[len-1] == '\n') {
1401 if (result->ob_refcnt == 1)
1402 _PyString_Resize(&result, len-1);
1403 else {
1404 PyObject *v;
1405 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001406 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001407 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001408 }
1409 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001410 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001411#ifdef Py_USING_UNICODE
1412 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1413 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001414 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001415 if (len == 0) {
1416 Py_DECREF(result);
1417 result = NULL;
1418 PyErr_SetString(PyExc_EOFError,
1419 "EOF when reading a line");
1420 }
1421 else if (s[len-1] == '\n') {
1422 if (result->ob_refcnt == 1)
1423 PyUnicode_Resize(&result, len-1);
1424 else {
1425 PyObject *v;
1426 v = PyUnicode_FromUnicode(s, len-1);
1427 Py_DECREF(result);
1428 result = v;
1429 }
1430 }
1431 }
1432#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001433 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001434}
1435
1436/* Python method */
1437
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001438static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001439file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001440{
Guido van Rossum789a1611997-05-10 22:33:55 +00001441 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001442
Guido van Rossumd7297e61992-07-06 14:19:26 +00001443 if (f->f_fp == NULL)
1444 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001445 /* refuse to mix with f.next() */
1446 if (f->f_buf != NULL &&
1447 (f->f_bufend - f->f_bufptr) > 0 &&
1448 f->f_buf[0] != '\0')
1449 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001450 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001451 return NULL;
1452 if (n == 0)
1453 return PyString_FromString("");
1454 if (n < 0)
1455 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001456 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001457}
1458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001459static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001460file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001461{
Guido van Rossum789a1611997-05-10 22:33:55 +00001462 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001463 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001464 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001465 char small_buffer[SMALLCHUNK];
1466 char *buffer = small_buffer;
1467 size_t buffersize = SMALLCHUNK;
1468 PyObject *big_buffer = NULL;
1469 size_t nfilled = 0;
1470 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001471 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001472 char *p, *q, *end;
1473 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001474 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001475
Guido van Rossumd7297e61992-07-06 14:19:26 +00001476 if (f->f_fp == NULL)
1477 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001478 /* refuse to mix with f.next() */
1479 if (f->f_buf != NULL &&
1480 (f->f_bufend - f->f_bufptr) > 0 &&
1481 f->f_buf[0] != '\0')
1482 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001483 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001484 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001485 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001486 return NULL;
1487 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001488 if (shortread)
1489 nread = 0;
1490 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001491 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001492 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001493 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001494 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001495 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001496 shortread = (nread < buffersize-nfilled);
1497 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001498 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001499 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001500 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001501 break;
1502 PyErr_SetFromErrno(PyExc_IOError);
1503 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001504 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001505 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001506 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001507 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001508 if (p == NULL) {
1509 /* Need a larger buffer to fit this line */
1510 nfilled += nread;
1511 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001512 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001513 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001514 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001515 goto error;
1516 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001517 if (big_buffer == NULL) {
1518 /* Create the big buffer */
1519 big_buffer = PyString_FromStringAndSize(
1520 NULL, buffersize);
1521 if (big_buffer == NULL)
1522 goto error;
1523 buffer = PyString_AS_STRING(big_buffer);
1524 memcpy(buffer, small_buffer, nfilled);
1525 }
1526 else {
1527 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001528 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1529 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001530 buffer = PyString_AS_STRING(big_buffer);
1531 }
1532 continue;
1533 }
1534 end = buffer+nfilled+nread;
1535 q = buffer;
1536 do {
1537 /* Process complete lines */
1538 p++;
1539 line = PyString_FromStringAndSize(q, p-q);
1540 if (line == NULL)
1541 goto error;
1542 err = PyList_Append(list, line);
1543 Py_DECREF(line);
1544 if (err != 0)
1545 goto error;
1546 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001547 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001548 } while (p != NULL);
1549 /* Move the remaining incomplete line to the start */
1550 nfilled = end-q;
1551 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001552 if (sizehint > 0)
1553 if (totalread >= (size_t)sizehint)
1554 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001555 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001556 if (nfilled != 0) {
1557 /* Partial last line */
1558 line = PyString_FromStringAndSize(buffer, nfilled);
1559 if (line == NULL)
1560 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001561 if (sizehint > 0) {
1562 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001563 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001564 if (rest == NULL) {
1565 Py_DECREF(line);
1566 goto error;
1567 }
1568 PyString_Concat(&line, rest);
1569 Py_DECREF(rest);
1570 if (line == NULL)
1571 goto error;
1572 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001573 err = PyList_Append(list, line);
1574 Py_DECREF(line);
1575 if (err != 0)
1576 goto error;
1577 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001578
1579cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001580 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001581 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001582
1583error:
1584 Py_CLEAR(list);
1585 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001586}
1587
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001588static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001589file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001590{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001591 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001592 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001593 if (f->f_fp == NULL)
1594 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001595 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001596 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001597 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001598 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001599 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001600 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001601 FILE_END_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001602 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001603 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001604 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001605 return NULL;
1606 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001607 Py_INCREF(Py_None);
1608 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001609}
1610
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001611static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001612file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001613{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001614#define CHUNKSIZE 1000
1615 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001616 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001617 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001618 int index, islist;
1619 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001620
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001621 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001622 if (f->f_fp == NULL)
1623 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001624
1625 result = NULL;
1626 list = NULL;
1627 islist = PyList_Check(seq);
1628 if (islist)
1629 it = NULL;
1630 else {
1631 it = PyObject_GetIter(seq);
1632 if (it == NULL) {
1633 PyErr_SetString(PyExc_TypeError,
1634 "writelines() requires an iterable argument");
1635 return NULL;
1636 }
1637 /* From here on, fail by going to error, to reclaim "it". */
1638 list = PyList_New(CHUNKSIZE);
1639 if (list == NULL)
1640 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001641 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001642
1643 /* Strategy: slurp CHUNKSIZE lines into a private list,
1644 checking that they are all strings, then write that list
1645 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001646 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001647 if (islist) {
1648 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001649 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001650 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001651 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001652 j = PyList_GET_SIZE(list);
1653 }
1654 else {
1655 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001656 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001657 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001658 if (PyErr_Occurred())
1659 goto error;
1660 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001661 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001662 PyList_SetItem(list, j, line);
1663 }
1664 }
1665 if (j == 0)
1666 break;
1667
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001668 /* Check that all entries are indeed strings. If not,
1669 apply the same rules as for file.write() and
1670 convert the results to strings. This is slow, but
1671 seems to be the only way since all conversion APIs
1672 could potentially execute Python code. */
1673 for (i = 0; i < j; i++) {
1674 PyObject *v = PyList_GET_ITEM(list, i);
1675 if (!PyString_Check(v)) {
1676 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001677 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001678 PyObject_AsReadBuffer(v,
1679 (const void**)&buffer,
1680 &len)) ||
1681 PyObject_AsCharBuffer(v,
1682 &buffer,
1683 &len))) {
1684 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001685 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001686 goto error;
1687 }
1688 line = PyString_FromStringAndSize(buffer,
1689 len);
1690 if (line == NULL)
1691 goto error;
1692 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001693 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001694 }
1695 }
1696
1697 /* Since we are releasing the global lock, the
1698 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001699 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001700 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001701 errno = 0;
1702 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001703 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001704 len = PyString_GET_SIZE(line);
1705 nwritten = fwrite(PyString_AS_STRING(line),
1706 1, len, f->f_fp);
1707 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001708 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001709 PyErr_SetFromErrno(PyExc_IOError);
1710 clearerr(f->f_fp);
1711 goto error;
1712 }
1713 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001714 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001715
1716 if (j < CHUNKSIZE)
1717 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001718 }
1719
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001720 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001721 result = Py_None;
1722 error:
1723 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001724 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001725 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001726#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001727}
1728
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001729static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001730file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001731{
1732 if (f->f_fp == NULL)
1733 return err_closed();
1734 Py_INCREF(f);
1735 return (PyObject *)f;
1736}
1737
Georg Brandl98b40ad2006-06-08 14:50:21 +00001738static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001739file_xreadlines(PyFileObject *f)
1740{
1741 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1742 "try 'for line in f' instead", 1) < 0)
1743 return NULL;
1744 return file_self(f);
1745}
1746
1747static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001748file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001749{
Georg Brandlad61bc82008-02-23 15:11:18 +00001750 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001751 if (!ret)
1752 /* If error occurred, pass through */
1753 return NULL;
1754 Py_DECREF(ret);
1755 /* We cannot return the result of close since a true
1756 * value will be interpreted as "yes, swallow the
1757 * exception if one was raised inside the with block". */
1758 Py_RETURN_NONE;
1759}
1760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001761PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001762"readline([size]) -> next line from the file, as a string.\n"
1763"\n"
1764"Retain newline. A non-negative size argument limits the maximum\n"
1765"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001766"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001768PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001769"read([size]) -> read at most size bytes, returned as a string.\n"
1770"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001771"If the size argument is negative or omitted, read until EOF is reached.\n"
1772"Notice that when in non-blocking mode, less data than what was requested\n"
1773"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001774
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001775PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001776"write(str) -> None. Write string str to file.\n"
1777"\n"
1778"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001779"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001781PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001782"fileno() -> integer \"file descriptor\".\n"
1783"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001784"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001786PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001787"seek(offset[, whence]) -> None. Move to new file position.\n"
1788"\n"
1789"Argument offset is a byte count. Optional argument whence defaults to\n"
1790"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1791"(move relative to current position, positive or negative), and 2 (move\n"
1792"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001793"seeking beyond the end of a file). If the file is opened in text mode,\n"
1794"only offsets returned by tell() are legal. Use of other offsets causes\n"
1795"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001796"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001797"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001798
Guido van Rossumd7047b31995-01-02 19:07:15 +00001799#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001800PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001801"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1802"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001803"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001804#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001806PyDoc_STRVAR(tell_doc,
1807"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001809PyDoc_STRVAR(readinto_doc,
1810"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001812PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001813"readlines([size]) -> list of strings, each a line from the file.\n"
1814"\n"
1815"Call readline() repeatedly and return a list of the lines so read.\n"
1816"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001817"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001819PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001820"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001821"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001822"For backward compatibility. File objects now include the performance\n"
1823"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001824
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001825PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001826"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001827"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001828"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001829"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001831PyDoc_STRVAR(flush_doc,
1832"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001834PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001835"close() -> None or (perhaps) an integer. Close the file.\n"
1836"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001837"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001838"further I/O operations. close() may be called more than once without\n"
1839"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001840"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001842PyDoc_STRVAR(isatty_doc,
1843"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001844
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001845PyDoc_STRVAR(enter_doc,
1846 "__enter__() -> self.");
1847
Georg Brandl98b40ad2006-06-08 14:50:21 +00001848PyDoc_STRVAR(exit_doc,
1849 "__exit__(*excinfo) -> None. Closes the file.");
1850
Tim Petersefc3a3a2001-09-20 07:55:22 +00001851static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001852 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1853 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1854 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1855 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1856 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001857#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001858 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001859#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001860 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1861 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
Georg Brandla9916b52008-05-17 22:11:54 +00001862 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
1863 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
1864 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001865 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1866 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1867 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001868 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00001869 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001870 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001871};
1872
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001873#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001874
Guido van Rossum6f799372001-09-20 20:46:19 +00001875static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00001876 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001877 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001878 {"name", T_OBJECT, OFF(f_name), RO,
1879 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001880 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1881 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001882 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001883 {NULL} /* Sentinel */
1884};
1885
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001886static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001888{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001889 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001890}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001891static PyObject *
1892get_newlines(PyFileObject *f, void *closure)
1893{
1894 switch (f->f_newlinetypes) {
1895 case NEWLINE_UNKNOWN:
1896 Py_INCREF(Py_None);
1897 return Py_None;
1898 case NEWLINE_CR:
1899 return PyString_FromString("\r");
1900 case NEWLINE_LF:
1901 return PyString_FromString("\n");
1902 case NEWLINE_CR|NEWLINE_LF:
1903 return Py_BuildValue("(ss)", "\r", "\n");
1904 case NEWLINE_CRLF:
1905 return PyString_FromString("\r\n");
1906 case NEWLINE_CR|NEWLINE_CRLF:
1907 return Py_BuildValue("(ss)", "\r", "\r\n");
1908 case NEWLINE_LF|NEWLINE_CRLF:
1909 return Py_BuildValue("(ss)", "\n", "\r\n");
1910 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1911 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1912 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001913 PyErr_Format(PyExc_SystemError,
1914 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001915 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001916 return NULL;
1917 }
1918}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001919
Georg Brandl65bb42d2008-03-21 20:38:24 +00001920static PyObject *
1921get_softspace(PyFileObject *f, void *closure)
1922{
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00001923 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00001924 return NULL;
1925 return PyInt_FromLong(f->f_softspace);
1926}
1927
1928static int
1929set_softspace(PyFileObject *f, PyObject *value)
1930{
1931 int new;
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00001932 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00001933 return -1;
1934
1935 if (value == NULL) {
1936 PyErr_SetString(PyExc_TypeError,
1937 "can't delete softspace attribute");
1938 return -1;
1939 }
1940
1941 new = PyInt_AsLong(value);
1942 if (new == -1 && PyErr_Occurred())
1943 return -1;
1944 f->f_softspace = new;
1945 return 0;
1946}
1947
Guido van Rossum32d34c82001-09-20 21:45:26 +00001948static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001949 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001950 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001951 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00001952 {"softspace", (getter)get_softspace, (setter)set_softspace,
1953 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 {0},
1955};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001956
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001957static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001958drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001959{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001960 if (f->f_buf != NULL) {
1961 PyMem_Free(f->f_buf);
1962 f->f_buf = NULL;
1963 }
Guido van Rossum65967252001-04-21 13:20:18 +00001964}
1965
Tim Petersf1827cf2003-09-07 03:30:18 +00001966/* Make sure that file has a readahead buffer with at least one byte
1967 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00001968 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001969static int
1970readahead(PyFileObject *f, int bufsize)
1971{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001972 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001973
1974 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001975 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001976 return 0;
1977 else
1978 drop_readahead(f);
1979 }
Anthony Baxter377be112006-04-11 06:54:30 +00001980 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00001981 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001982 return -1;
1983 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001984 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001985 errno = 0;
1986 chunksize = Py_UniversalNewlineFread(
1987 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001988 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001989 if (chunksize == 0) {
1990 if (ferror(f->f_fp)) {
1991 PyErr_SetFromErrno(PyExc_IOError);
1992 clearerr(f->f_fp);
1993 drop_readahead(f);
1994 return -1;
1995 }
1996 }
1997 f->f_bufptr = f->f_buf;
1998 f->f_bufend = f->f_buf + chunksize;
1999 return 0;
2000}
2001
2002/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002003 uninitialized bytes followed by the remainder of the line. Don't be
2004 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002005 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2006
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002007static PyStringObject *
2008readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2009{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002010 PyStringObject* s;
2011 char *bufptr;
2012 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002013 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002014
2015 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002016 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002017 return NULL;
2018
2019 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002020 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002021 return (PyStringObject *)
2022 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002023 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002024 if (bufptr != NULL) {
2025 bufptr++; /* Count the '\n' */
2026 len = bufptr - f->f_bufptr;
2027 s = (PyStringObject *)
2028 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002029 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002030 return NULL;
2031 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2032 f->f_bufptr = bufptr;
2033 if (bufptr == f->f_bufend)
2034 drop_readahead(f);
2035 } else {
2036 bufptr = f->f_bufptr;
2037 buf = f->f_buf;
2038 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002039 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002040 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002041 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002042 if (s == NULL) {
2043 PyMem_Free(buf);
2044 return NULL;
2045 }
2046 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2047 PyMem_Free(buf);
2048 }
2049 return s;
2050}
2051
2052/* A larger buffer size may actually decrease performance. */
2053#define READAHEAD_BUFSIZE 8192
2054
2055static PyObject *
2056file_iternext(PyFileObject *f)
2057{
2058 PyStringObject* l;
2059
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002060 if (f->f_fp == NULL)
2061 return err_closed();
2062
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002063 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2064 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2065 Py_XDECREF(l);
2066 return NULL;
2067 }
2068 return (PyObject *)l;
2069}
2070
2071
Tim Peters59c9a642001-09-13 05:38:56 +00002072static PyObject *
2073file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2074{
Tim Peters44410012001-09-14 03:26:08 +00002075 PyObject *self;
2076 static PyObject *not_yet_string;
2077
2078 assert(type != NULL && type->tp_alloc != NULL);
2079
2080 if (not_yet_string == NULL) {
Christian Heimesd7e1b2b2008-01-28 02:07:53 +00002081 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002082 if (not_yet_string == NULL)
2083 return NULL;
2084 }
2085
2086 self = type->tp_alloc(type, 0);
2087 if (self != NULL) {
2088 /* Always fill in the name and mode, so that nobody else
2089 needs to special-case NULLs there. */
2090 Py_INCREF(not_yet_string);
2091 ((PyFileObject *)self)->f_name = not_yet_string;
2092 Py_INCREF(not_yet_string);
2093 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002094 Py_INCREF(Py_None);
2095 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002096 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002097 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002098 }
2099 return self;
2100}
2101
2102static int
2103file_init(PyObject *self, PyObject *args, PyObject *kwds)
2104{
2105 PyFileObject *foself = (PyFileObject *)self;
2106 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002107 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002108 char *name = NULL;
2109 char *mode = "r";
2110 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002111 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00002112
2113 assert(PyFile_Check(self));
2114 if (foself->f_fp != NULL) {
2115 /* Have to close the existing file first. */
2116 PyObject *closeresult = file_close(foself);
2117 if (closeresult == NULL)
2118 return -1;
2119 Py_DECREF(closeresult);
2120 }
Tim Peters59c9a642001-09-13 05:38:56 +00002121
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002122#ifdef Py_WIN_WIDE_FILENAMES
2123 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2124 PyObject *po;
2125 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2126 kwlist, &po, &mode, &bufsize)) {
2127 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002128 if (fill_file_fields(foself, NULL, po, mode,
2129 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002130 goto Error;
2131 } else {
2132 /* Drop the argument parsing error as narrow
2133 strings are also valid. */
2134 PyErr_Clear();
2135 }
2136 }
2137#endif
2138
2139 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002140 PyObject *o_name;
2141
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002142 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2143 Py_FileSystemDefaultEncoding,
2144 &name,
2145 &mode, &bufsize))
2146 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002147
2148 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002149 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2150 kwlist, &o_name, &mode,
2151 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002152 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002153
2154 if (fill_file_fields(foself, NULL, o_name, mode,
2155 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002156 goto Error;
2157 }
Tim Peters44410012001-09-14 03:26:08 +00002158 if (open_the_file(foself, name, mode) == NULL)
2159 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002160 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002161 PyFile_SetBufSize(self, bufsize);
2162 goto Done;
2163
2164Error:
2165 ret = -1;
2166 /* fall through */
2167Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002168 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002169 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002170}
2171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002172PyDoc_VAR(file_doc) =
2173PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002174"file(name[, mode[, buffering]]) -> file object\n"
2175"\n"
2176"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2177"writing or appending. The file will be created if it doesn't exist\n"
2178"when opened for writing or appending; it will be truncated when\n"
2179"opened for writing. Add a 'b' to the mode for binary files.\n"
2180"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2181"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002182"buffered, and larger numbers specify the buffer size. The preferred way\n"
2183"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002184)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002185PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002186"Add a 'U' to mode to open the file for input with universal newline\n"
2187"support. Any line ending in the input file will be seen as a '\\n'\n"
2188"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2189"the value for this attribute is one of None (no newline read yet),\n"
2190"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2191"\n"
2192"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002193);
Tim Peters59c9a642001-09-13 05:38:56 +00002194
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002196 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002197 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002198 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002199 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002200 (destructor)file_dealloc, /* tp_dealloc */
2201 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202 0, /* tp_getattr */
2203 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002204 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002206 0, /* tp_as_number */
2207 0, /* tp_as_sequence */
2208 0, /* tp_as_mapping */
2209 0, /* tp_hash */
2210 0, /* tp_call */
2211 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002213 /* softspace is writable: we must supply tp_setattro */
2214 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002215 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002216 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002217 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218 0, /* tp_traverse */
2219 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002220 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002221 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002222 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002223 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224 file_methods, /* tp_methods */
2225 file_memberlist, /* tp_members */
2226 file_getsetlist, /* tp_getset */
2227 0, /* tp_base */
2228 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002229 0, /* tp_descr_get */
2230 0, /* tp_descr_set */
2231 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002232 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002233 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002234 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002235 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002236};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002237
2238/* Interface for the 'soft space' between print items. */
2239
2240int
Fred Drakefd99de62000-07-09 05:02:18 +00002241PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002242{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002243 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002244 if (f == NULL) {
2245 /* Do nothing */
2246 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002247 else if (PyFile_Check(f)) {
2248 oldflag = ((PyFileObject *)f)->f_softspace;
2249 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002250 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002251 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252 PyObject *v;
2253 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002254 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002255 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002256 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002257 if (PyInt_Check(v))
2258 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002259 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002261 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002262 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002263 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002264 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002265 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002266 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2267 PyErr_Clear();
2268 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002269 }
2270 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002271 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002272}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002273
2274/* Interfaces to write objects/strings to file-like objects */
2275
2276int
Fred Drakefd99de62000-07-09 05:02:18 +00002277PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002278{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002280 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002281 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002282 return -1;
2283 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002284 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002285 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002286#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002287 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002288 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002289#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002290 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002291 err_closed();
2292 return -1;
2293 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002294#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002295 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002296 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002297 char *cenc = PyString_AS_STRING(enc);
2298 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2299 if (value == NULL)
2300 return -1;
2301 } else {
2302 value = v;
2303 Py_INCREF(value);
2304 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002305 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002306 Py_DECREF(value);
2307 return result;
2308#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002309 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002310#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002311 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002312 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002313 if (writer == NULL)
2314 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002315 if (flags & Py_PRINT_RAW) {
2316 if (PyUnicode_Check(v)) {
2317 value = v;
2318 Py_INCREF(value);
2319 } else
2320 value = PyObject_Str(v);
2321 }
2322 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002323 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002324 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002325 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002326 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002327 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002328 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002329 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002330 Py_DECREF(value);
2331 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002332 return -1;
2333 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002334 result = PyEval_CallObject(writer, args);
2335 Py_DECREF(args);
2336 Py_DECREF(value);
2337 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002338 if (result == NULL)
2339 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002340 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002341 return 0;
2342}
2343
Guido van Rossum27a60b11997-05-22 22:25:11 +00002344int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002345PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002346{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002347
Guido van Rossum3165fe61992-09-25 21:59:05 +00002348 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002349 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002350 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002351 PyErr_SetString(PyExc_SystemError,
2352 "null file for PyFile_WriteString");
2353 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002354 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002355 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002356 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002357 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002358 if (fp == NULL) {
2359 err_closed();
2360 return -1;
2361 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002362 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002363 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002364 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002365 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002366 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002367 else if (!PyErr_Occurred()) {
2368 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002369 int err;
2370 if (v == NULL)
2371 return -1;
2372 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2373 Py_DECREF(v);
2374 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002375 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002376 else
2377 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002378}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002379
2380/* Try to get a file-descriptor from a Python object. If the object
2381 is an integer or long integer, its value is returned. If not, the
2382 object's fileno() method is called if it exists; the method must return
2383 an integer or long integer, which is returned as the file descriptor value.
2384 -1 is returned on failure.
2385*/
2386
2387int PyObject_AsFileDescriptor(PyObject *o)
2388{
2389 int fd;
2390 PyObject *meth;
2391
2392 if (PyInt_Check(o)) {
2393 fd = PyInt_AsLong(o);
2394 }
2395 else if (PyLong_Check(o)) {
2396 fd = PyLong_AsLong(o);
2397 }
2398 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2399 {
2400 PyObject *fno = PyEval_CallObject(meth, NULL);
2401 Py_DECREF(meth);
2402 if (fno == NULL)
2403 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002404
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002405 if (PyInt_Check(fno)) {
2406 fd = PyInt_AsLong(fno);
2407 Py_DECREF(fno);
2408 }
2409 else if (PyLong_Check(fno)) {
2410 fd = PyLong_AsLong(fno);
2411 Py_DECREF(fno);
2412 }
2413 else {
2414 PyErr_SetString(PyExc_TypeError,
2415 "fileno() returned a non-integer");
2416 Py_DECREF(fno);
2417 return -1;
2418 }
2419 }
2420 else {
2421 PyErr_SetString(PyExc_TypeError,
2422 "argument must be an int, or have a fileno() method.");
2423 return -1;
2424 }
2425
2426 if (fd < 0) {
2427 PyErr_Format(PyExc_ValueError,
2428 "file descriptor cannot be a negative integer (%i)",
2429 fd);
2430 return -1;
2431 }
2432 return fd;
2433}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002434
Jack Jansen7b8c7542002-04-14 20:12:41 +00002435/* From here on we need access to the real fgets and fread */
2436#undef fgets
2437#undef fread
2438
2439/*
2440** Py_UniversalNewlineFgets is an fgets variation that understands
2441** all of \r, \n and \r\n conventions.
2442** The stream should be opened in binary mode.
2443** If fobj is NULL the routine always does newline conversion, and
2444** it may peek one char ahead to gobble the second char in \r\n.
2445** If fobj is non-NULL it must be a PyFileObject. In this case there
2446** is no readahead but in stead a flag is used to skip a following
2447** \n on the next read. Also, if the file is open in binary mode
2448** the whole conversion is skipped. Finally, the routine keeps track of
2449** the different types of newlines seen.
2450** Note that we need no error handling: fgets() treats error and eof
2451** identically.
2452*/
2453char *
2454Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2455{
2456 char *p = buf;
2457 int c;
2458 int newlinetypes = 0;
2459 int skipnextlf = 0;
2460 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002461
Jack Jansen7b8c7542002-04-14 20:12:41 +00002462 if (fobj) {
2463 if (!PyFile_Check(fobj)) {
2464 errno = ENXIO; /* What can you do... */
2465 return NULL;
2466 }
2467 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2468 if ( !univ_newline )
2469 return fgets(buf, n, stream);
2470 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2471 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2472 }
2473 FLOCKFILE(stream);
2474 c = 'x'; /* Shut up gcc warning */
2475 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2476 if (skipnextlf ) {
2477 skipnextlf = 0;
2478 if (c == '\n') {
2479 /* Seeing a \n here with skipnextlf true
2480 ** means we saw a \r before.
2481 */
2482 newlinetypes |= NEWLINE_CRLF;
2483 c = GETC(stream);
2484 if (c == EOF) break;
2485 } else {
2486 /*
2487 ** Note that c == EOF also brings us here,
2488 ** so we're okay if the last char in the file
2489 ** is a CR.
2490 */
2491 newlinetypes |= NEWLINE_CR;
2492 }
2493 }
2494 if (c == '\r') {
2495 /* A \r is translated into a \n, and we skip
2496 ** an adjacent \n, if any. We don't set the
2497 ** newlinetypes flag until we've seen the next char.
2498 */
2499 skipnextlf = 1;
2500 c = '\n';
2501 } else if ( c == '\n') {
2502 newlinetypes |= NEWLINE_LF;
2503 }
2504 *p++ = c;
2505 if (c == '\n') break;
2506 }
2507 if ( c == EOF && skipnextlf )
2508 newlinetypes |= NEWLINE_CR;
2509 FUNLOCKFILE(stream);
2510 *p = '\0';
2511 if (fobj) {
2512 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2513 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2514 } else if ( skipnextlf ) {
2515 /* If we have no file object we cannot save the
2516 ** skipnextlf flag. We have to readahead, which
2517 ** will cause a pause if we're reading from an
2518 ** interactive stream, but that is very unlikely
2519 ** unless we're doing something silly like
2520 ** execfile("/dev/tty").
2521 */
2522 c = GETC(stream);
2523 if ( c != '\n' )
2524 ungetc(c, stream);
2525 }
2526 if (p == buf)
2527 return NULL;
2528 return buf;
2529}
2530
2531/*
2532** Py_UniversalNewlineFread is an fread variation that understands
2533** all of \r, \n and \r\n conventions.
2534** The stream should be opened in binary mode.
2535** fobj must be a PyFileObject. In this case there
2536** is no readahead but in stead a flag is used to skip a following
2537** \n on the next read. Also, if the file is open in binary mode
2538** the whole conversion is skipped. Finally, the routine keeps track of
2539** the different types of newlines seen.
2540*/
2541size_t
Tim Peters058b1412002-04-21 07:29:14 +00002542Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002543 FILE *stream, PyObject *fobj)
2544{
Tim Peters058b1412002-04-21 07:29:14 +00002545 char *dst = buf;
2546 PyFileObject *f = (PyFileObject *)fobj;
2547 int newlinetypes, skipnextlf;
2548
2549 assert(buf != NULL);
2550 assert(stream != NULL);
2551
Jack Jansen7b8c7542002-04-14 20:12:41 +00002552 if (!fobj || !PyFile_Check(fobj)) {
2553 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002554 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002555 }
Tim Peters058b1412002-04-21 07:29:14 +00002556 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002557 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002558 newlinetypes = f->f_newlinetypes;
2559 skipnextlf = f->f_skipnextlf;
2560 /* Invariant: n is the number of bytes remaining to be filled
2561 * in the buffer.
2562 */
2563 while (n) {
2564 size_t nread;
2565 int shortread;
2566 char *src = dst;
2567
2568 nread = fread(dst, 1, n, stream);
2569 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002570 if (nread == 0)
2571 break;
2572
Tim Peterse1682a82002-04-21 18:15:20 +00002573 n -= nread; /* assuming 1 byte out for each in; will adjust */
2574 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002575 while (nread--) {
2576 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002577 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002578 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002579 *dst++ = '\n';
2580 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002581 }
2582 else if (skipnextlf && c == '\n') {
2583 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002584 skipnextlf = 0;
2585 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002586 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002587 }
2588 else {
2589 /* Normal char to be stored in buffer. Also
2590 * update the newlinetypes flag if either this
2591 * is an LF or the previous char was a CR.
2592 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002593 if (c == '\n')
2594 newlinetypes |= NEWLINE_LF;
2595 else if (skipnextlf)
2596 newlinetypes |= NEWLINE_CR;
2597 *dst++ = c;
2598 skipnextlf = 0;
2599 }
2600 }
Tim Peters058b1412002-04-21 07:29:14 +00002601 if (shortread) {
2602 /* If this is EOF, update type flags. */
2603 if (skipnextlf && feof(stream))
2604 newlinetypes |= NEWLINE_CR;
2605 break;
2606 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002607 }
Tim Peters058b1412002-04-21 07:29:14 +00002608 f->f_newlinetypes = newlinetypes;
2609 f->f_skipnextlf = skipnextlf;
2610 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002611}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002612
2613#ifdef __cplusplus
2614}
2615#endif