blob: d83c054cf3e0ebc9bf6163ff8820cba1e6b07e93 [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
Andrew MacIntyrec4874392002-02-26 11:36:35 +000019#if defined(PYOS_OS2) && defined(PYCC_GCC)
20#include <io.h>
21#endif
22
Gregory P. Smithdd96db62008-06-09 04:58:54 +000023#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000024
Andrew M. Kuchling00b6a5c2010-02-22 23:10:52 +000025#ifdef HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000026#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000027#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028
Jack Jansen7b8c7542002-04-14 20:12:41 +000029#ifdef HAVE_GETC_UNLOCKED
30#define GETC(f) getc_unlocked(f)
31#define FLOCKFILE(f) flockfile(f)
32#define FUNLOCKFILE(f) funlockfile(f)
33#else
34#define GETC(f) getc(f)
35#define FLOCKFILE(f)
36#define FUNLOCKFILE(f)
37#endif
38
Jack Jansen7b8c7542002-04-14 20:12:41 +000039/* Bits in f_newlinetypes */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000040#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
41#define NEWLINE_CR 1 /* \r newline seen */
42#define NEWLINE_LF 2 /* \n newline seen */
43#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000044
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000045/*
46 * These macros release the GIL while preventing the f_close() function being
47 * called in the interval between them. For that purpose, a running total of
48 * the number of currently running unlocked code sections is kept in
49 * the unlocked_count field of the PyFileObject. The close() method raises
50 * an IOError if that field is non-zero. See issue #815646, #595601.
51 */
52
53#define FILE_BEGIN_ALLOW_THREADS(fobj) \
54{ \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000055 fobj->unlocked_count++; \
56 Py_BEGIN_ALLOW_THREADS
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000057
58#define FILE_END_ALLOW_THREADS(fobj) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000059 Py_END_ALLOW_THREADS \
60 fobj->unlocked_count--; \
61 assert(fobj->unlocked_count >= 0); \
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000062}
63
64#define FILE_ABORT_ALLOW_THREADS(fobj) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000065 Py_BLOCK_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000068
Anthony Baxterac6bd462006-04-13 02:06:09 +000069#ifdef __cplusplus
70extern "C" {
71#endif
72
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000074PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000076 if (f == NULL || !PyFile_Check(f))
77 return NULL;
78 else
79 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080}
81
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000082void PyFile_IncUseCount(PyFileObject *fobj)
83{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000084 fobj->unlocked_count++;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000085}
86
87void PyFile_DecUseCount(PyFileObject *fobj)
88{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000089 fobj->unlocked_count--;
90 assert(fobj->unlocked_count >= 0);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000091}
92
Guido van Rossumc0b618a1997-05-02 03:12:38 +000093PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000094PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000095{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000096 if (f == NULL || !PyFile_Check(f))
97 return NULL;
98 else
99 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000100}
101
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000102/* This is a safe wrapper around PyObject_Print to print to the FILE
103 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
104 about PyFileObject. */
105static int
106file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
107{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000108 int result;
109 PyFile_IncUseCount(f);
110 result = PyObject_Print(op, f->f_fp, flags);
111 PyFile_DecUseCount(f);
112 return result;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000113}
114
Neil Schemenauered19b882002-03-23 02:06:50 +0000115/* On Unix, fopen will succeed for directories.
116 In Python, there should be no file objects referring to
117 directories, so we need a check. */
118
119static PyFileObject*
120dircheck(PyFileObject* f)
121{
122#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000123 struct stat buf;
124 if (f->f_fp == NULL)
125 return f;
126 if (fstat(fileno(f->f_fp), &buf) == 0 &&
127 S_ISDIR(buf.st_mode)) {
128 char *msg = strerror(EISDIR);
129 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
130 EISDIR, msg, f->f_name);
131 PyErr_SetObject(PyExc_IOError, exc);
132 Py_XDECREF(exc);
133 return NULL;
134 }
Neil Schemenauered19b882002-03-23 02:06:50 +0000135#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000136 return f;
Neil Schemenauered19b882002-03-23 02:06:50 +0000137}
138
Tim Peters59c9a642001-09-13 05:38:56 +0000139
140static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000141fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000142 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 assert(name != NULL);
145 assert(f != NULL);
146 assert(PyFile_Check(f));
147 assert(f->f_fp == NULL);
Tim Peters44410012001-09-14 03:26:08 +0000148
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 Py_DECREF(f->f_name);
150 Py_DECREF(f->f_mode);
151 Py_DECREF(f->f_encoding);
152 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000153
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000154 Py_INCREF(name);
155 f->f_name = name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000156
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000158
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 f->f_close = close;
160 f->f_softspace = 0;
161 f->f_binary = strchr(mode,'b') != NULL;
162 f->f_buf = NULL;
163 f->f_univ_newline = (strchr(mode, 'U') != NULL);
164 f->f_newlinetypes = NEWLINE_UNKNOWN;
165 f->f_skipnextlf = 0;
166 Py_INCREF(Py_None);
167 f->f_encoding = Py_None;
168 Py_INCREF(Py_None);
169 f->f_errors = Py_None;
170 f->readable = f->writable = 0;
171 if (strchr(mode, 'r') != NULL || f->f_univ_newline)
172 f->readable = 1;
173 if (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL)
174 f->writable = 1;
175 if (strchr(mode, '+') != NULL)
176 f->readable = f->writable = 1;
Tim Petersf1827cf2003-09-07 03:30:18 +0000177
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000178 if (f->f_mode == NULL)
179 return NULL;
180 f->f_fp = fp;
181 f = dircheck(f);
182 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000185#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
186#define Py_VERIFY_WINNT
187/* The CRT on windows compiled with Visual Studio 2005 and higher may
188 * assert if given invalid mode strings. This is all fine and well
189 * in static languages like C where the mode string is typcially hard
190 * coded. But in Python, were we pass in the mode string from the user,
191 * we need to verify it first manually
192 */
193static int _PyVerify_Mode_WINNT(const char *mode)
194{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000195 /* See if mode string is valid on Windows to avoid hard assertions */
196 /* remove leading spacese */
197 int singles = 0;
198 int pairs = 0;
199 int encoding = 0;
200 const char *s, *c;
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000201
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000202 while(*mode == ' ') /* strip initial spaces */
203 ++mode;
204 if (!strchr("rwa", *mode)) /* must start with one of these */
205 return 0;
206 while (*++mode) {
207 if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
208 continue;
209 s = "+TD"; /* each of this can appear only once */
210 c = strchr(s, *mode);
211 if (c) {
212 ptrdiff_t idx = s-c;
213 if (singles & (1<<idx))
214 return 0;
215 singles |= (1<<idx);
216 continue;
217 }
218 s = "btcnSR"; /* only one of each letter in the pairs allowed */
219 c = strchr(s, *mode);
220 if (c) {
221 ptrdiff_t idx = (s-c)/2;
222 if (pairs & (1<<idx))
223 return 0;
224 pairs |= (1<<idx);
225 continue;
226 }
227 if (*mode == ',') {
228 encoding = 1;
229 break;
230 }
231 return 0; /* found an invalid char */
232 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000233
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000234 if (encoding) {
235 char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
236 while (*mode == ' ')
237 ++mode;
238 /* find 'ccs =' */
239 if (strncmp(mode, "ccs", 3))
240 return 0;
241 mode += 3;
242 while (*mode == ' ')
243 ++mode;
244 if (*mode != '=')
245 return 0;
246 while (*mode == ' ')
247 ++mode;
248 for(encoding = 0; encoding<_countof(e); ++encoding) {
249 size_t l = strlen(e[encoding]);
250 if (!strncmp(mode, e[encoding], l)) {
251 mode += l; /* found a valid encoding */
252 break;
253 }
254 }
255 if (encoding == _countof(e))
256 return 0;
257 }
258 /* skip trailing spaces */
259 while (*mode == ' ')
260 ++mode;
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000261
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 return *mode == '\0'; /* must be at the end of the string */
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000263}
264#endif
265
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000266/* check for known incorrect mode strings - problem is, platforms are
267 free to accept any mode characters they like and are supposed to
268 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000269 universal newline support is expressly forbidden by PEP 278.
270 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000271 won't know what it is. Non-zero return signals an exception */
272int
273_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000274{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 char *upos;
276 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 if (!len) {
279 PyErr_SetString(PyExc_ValueError, "empty mode string");
280 return -1;
281 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 upos = strchr(mode, 'U');
284 if (upos) {
285 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000286
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000287 if (mode[0] == 'w' || mode[0] == 'a') {
288 PyErr_Format(PyExc_ValueError, "universal newline "
289 "mode can only be used with modes "
290 "starting with 'r'");
291 return -1;
292 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000293
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000294 if (mode[0] != 'r') {
295 memmove(mode+1, mode, strlen(mode)+1);
296 mode[0] = 'r';
297 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000298
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 if (!strchr(mode, 'b')) {
300 memmove(mode+2, mode+1, strlen(mode));
301 mode[1] = 'b';
302 }
303 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
304 PyErr_Format(PyExc_ValueError, "mode string must begin with "
305 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
306 return -1;
307 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000308#ifdef Py_VERIFY_WINNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000309 /* additional checks on NT with visual studio 2005 and higher */
310 if (!_PyVerify_Mode_WINNT(mode)) {
311 PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
312 return -1;
313 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000314#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 return 0;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000316}
317
Tim Peters59c9a642001-09-13 05:38:56 +0000318static PyObject *
319open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000321 char *newmode;
322 assert(f != NULL);
323 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000324#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 /* windows ignores the passed name in order to support Unicode */
326 assert(f->f_name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000327#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000329#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 assert(mode != NULL);
331 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000332
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 /* probably need to replace 'U' by 'rb' */
334 newmode = PyMem_MALLOC(strlen(mode) + 3);
335 if (!newmode) {
336 PyErr_NoMemory();
337 return NULL;
338 }
339 strcpy(newmode, mode);
Georg Brandl7b90e162006-05-18 07:01:27 +0000340
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 if (_PyFile_SanitizeMode(newmode)) {
342 f = NULL;
343 goto cleanup;
344 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000345
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 /* rexec.py can't stop a user from getting the file() constructor --
347 all they have to do is get *any* file object f, and then do
348 type(f). Here we prevent them from doing damage with it. */
349 if (PyEval_GetRestricted()) {
350 PyErr_SetString(PyExc_IOError,
351 "file() constructor not accessible in restricted mode");
352 f = NULL;
353 goto cleanup;
354 }
355 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000356
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000357#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 if (PyUnicode_Check(f->f_name)) {
359 PyObject *wmode;
360 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
361 if (f->f_name && wmode) {
362 FILE_BEGIN_ALLOW_THREADS(f)
363 /* PyUnicode_AS_UNICODE OK without thread
364 lock as it is a simple dereference. */
365 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
366 PyUnicode_AS_UNICODE(wmode));
367 FILE_END_ALLOW_THREADS(f)
368 }
369 Py_XDECREF(wmode);
370 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000371#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000372 if (NULL == f->f_fp && NULL != name) {
373 FILE_BEGIN_ALLOW_THREADS(f)
374 f->f_fp = fopen(name, newmode);
375 FILE_END_ALLOW_THREADS(f)
376 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000377
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000378 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000379#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
381 * across all Windows flavors. When it sets EINVAL varies
382 * across Windows flavors, the exact conditions aren't
383 * documented, and the answer lies in the OS's implementation
384 * of Win32's CreateFile function (whose source is secret).
385 * Seems the best we can do is map EINVAL to ENOENT.
386 * Starting with Visual Studio .NET 2005, EINVAL is correctly
387 * set by our CRT error handler (set in exceptions.c.)
388 */
389 if (errno == 0) /* bad mode string */
390 errno = EINVAL;
391 else if (errno == EINVAL) /* unknown, but not a mode string */
392 errno = ENOENT;
Tim Peters2ea91112002-04-08 04:13:12 +0000393#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000394 /* EINVAL is returned when an invalid filename or
395 * an invalid mode is supplied. */
396 if (errno == EINVAL) {
397 PyObject *v;
398 char message[100];
399 PyOS_snprintf(message, 100,
400 "invalid mode ('%.50s') or filename", mode);
401 v = Py_BuildValue("(isO)", errno, message, f->f_name);
402 if (v != NULL) {
403 PyErr_SetObject(PyExc_IOError, v);
404 Py_DECREF(v);
405 }
406 }
407 else
408 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
409 f = NULL;
410 }
411 if (f != NULL)
412 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000413
414cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000415 PyMem_FREE(newmode);
Georg Brandl7b90e162006-05-18 07:01:27 +0000416
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 return (PyObject *)f;
Tim Peters59c9a642001-09-13 05:38:56 +0000418}
419
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000420static PyObject *
421close_the_file(PyFileObject *f)
422{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 int sts = 0;
424 int (*local_close)(FILE *);
425 FILE *local_fp = f->f_fp;
426 if (local_fp != NULL) {
427 local_close = f->f_close;
428 if (local_close != NULL && f->unlocked_count > 0) {
429 if (f->ob_refcnt > 0) {
430 PyErr_SetString(PyExc_IOError,
431 "close() called during concurrent "
432 "operation on the same file object.");
433 } else {
434 /* This should not happen unless someone is
435 * carelessly playing with the PyFileObject
436 * struct fields and/or its associated FILE
437 * pointer. */
438 PyErr_SetString(PyExc_SystemError,
439 "PyFileObject locking error in "
440 "destructor (refcnt <= 0 at close).");
441 }
442 return NULL;
443 }
444 /* NULL out the FILE pointer before releasing the GIL, because
445 * it will not be valid anymore after the close() function is
446 * called. */
447 f->f_fp = NULL;
448 if (local_close != NULL) {
449 Py_BEGIN_ALLOW_THREADS
450 errno = 0;
451 sts = (*local_close)(local_fp);
452 Py_END_ALLOW_THREADS
453 if (sts == EOF)
454 return PyErr_SetFromErrno(PyExc_IOError);
455 if (sts != 0)
456 return PyInt_FromLong((long)sts);
457 }
458 }
459 Py_RETURN_NONE;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000460}
461
Tim Peters59c9a642001-09-13 05:38:56 +0000462PyObject *
463PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
464{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
466 NULL, NULL);
467 if (f != NULL) {
468 PyObject *o_name = PyString_FromString(name);
469 if (o_name == NULL)
470 return NULL;
471 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
472 Py_DECREF(f);
473 f = NULL;
474 }
475 Py_DECREF(o_name);
476 }
477 return (PyObject *) f;
Tim Peters59c9a642001-09-13 05:38:56 +0000478}
479
480PyObject *
481PyFile_FromString(char *name, char *mode)
482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 extern int fclose(FILE *);
484 PyFileObject *f;
Tim Peters59c9a642001-09-13 05:38:56 +0000485
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
487 if (f != NULL) {
488 if (open_the_file(f, name, mode) == NULL) {
489 Py_DECREF(f);
490 f = NULL;
491 }
492 }
493 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000494}
495
Guido van Rossumb6775db1994-08-01 11:34:53 +0000496void
Fred Drakefd99de62000-07-09 05:02:18 +0000497PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000498{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 PyFileObject *file = (PyFileObject *)f;
500 if (bufsize >= 0) {
501 int type;
502 switch (bufsize) {
503 case 0:
504 type = _IONBF;
505 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000506#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000507 case 1:
508 type = _IOLBF;
509 bufsize = BUFSIZ;
510 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000511#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000512 default:
513 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000514#ifndef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000515 bufsize = BUFSIZ;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000516#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517 break;
518 }
519 fflush(file->f_fp);
520 if (type == _IONBF) {
521 PyMem_Free(file->f_setbuf);
522 file->f_setbuf = NULL;
523 } else {
524 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
525 bufsize);
526 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000527#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000529#else /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000530 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000531#endif /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000532 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000533}
534
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000535/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000536 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000537
538int
539PyFile_SetEncoding(PyObject *f, const char *enc)
540{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 return PyFile_SetEncodingAndErrors(f, enc, NULL);
Martin v. Löwis99815892008-06-01 07:20:46 +0000542}
543
544int
545PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
546{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 PyFileObject *file = (PyFileObject*)f;
548 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000549
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 assert(PyFile_Check(f));
551 str = PyString_FromString(enc);
552 if (!str)
553 return 0;
554 if (errors) {
555 oerrors = PyString_FromString(errors);
556 if (!oerrors) {
557 Py_DECREF(str);
558 return 0;
559 }
560 } else {
561 oerrors = Py_None;
562 Py_INCREF(Py_None);
563 }
564 Py_DECREF(file->f_encoding);
565 file->f_encoding = str;
566 Py_DECREF(file->f_errors);
567 file->f_errors = oerrors;
568 return 1;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000569}
570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000572err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000573{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000574 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
575 return NULL;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000576}
577
Antoine Pitroubb445a12010-02-05 17:05:54 +0000578static PyObject *
579err_mode(char *action)
580{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000581 PyErr_Format(PyExc_IOError, "File not open for %s", action);
582 return NULL;
Antoine Pitroubb445a12010-02-05 17:05:54 +0000583}
584
Thomas Woutersc45251a2006-02-12 11:53:32 +0000585/* Refuse regular file I/O if there's data in the iteration-buffer.
586 * Mixing them would cause data to arrive out of order, as the read*
587 * methods don't use the iteration buffer. */
588static PyObject *
589err_iterbuffered(void)
590{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000591 PyErr_SetString(PyExc_ValueError,
592 "Mixing iteration and read methods would lose data");
593 return NULL;
Thomas Woutersc45251a2006-02-12 11:53:32 +0000594}
595
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000596static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000597
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598/* Methods */
599
600static void
Fred Drakefd99de62000-07-09 05:02:18 +0000601file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000603 PyObject *ret;
604 if (f->weakreflist != NULL)
605 PyObject_ClearWeakRefs((PyObject *) f);
606 ret = close_the_file(f);
607 if (!ret) {
608 PySys_WriteStderr("close failed in file object destructor:\n");
609 PyErr_Print();
610 }
611 else {
612 Py_DECREF(ret);
613 }
614 PyMem_Free(f->f_setbuf);
615 Py_XDECREF(f->f_name);
616 Py_XDECREF(f->f_mode);
617 Py_XDECREF(f->f_encoding);
618 Py_XDECREF(f->f_errors);
619 drop_readahead(f);
620 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621}
622
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000624file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000625{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000626 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000627#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000628 PyObject *ret = NULL;
629 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
630 const char *name_str = name ? PyString_AsString(name) : "?";
631 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
632 f->f_fp == NULL ? "closed" : "open",
633 name_str,
634 PyString_AsString(f->f_mode),
635 f);
636 Py_XDECREF(name);
637 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000638#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 } else {
640 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
641 f->f_fp == NULL ? "closed" : "open",
642 PyString_AsString(f->f_name),
643 PyString_AsString(f->f_mode),
644 f);
645 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646}
647
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000648static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000649file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000650{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 PyObject *sts = close_the_file(f);
Antoine Pitrou83137c22010-05-17 19:56:59 +0000652 if (sts) {
653 PyMem_Free(f->f_setbuf);
654 f->f_setbuf = NULL;
655 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000656 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000657}
658
Trent Mickf29f47b2000-08-11 19:02:59 +0000659
Guido van Rossumb8552162001-09-05 14:58:11 +0000660/* Our very own off_t-like type, 64-bit if possible */
661#if !defined(HAVE_LARGEFILE_SUPPORT)
662typedef off_t Py_off_t;
663#elif SIZEOF_OFF_T >= 8
664typedef off_t Py_off_t;
665#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000666typedef fpos_t Py_off_t;
667#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000668#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000669#endif
670
671
Trent Mickf29f47b2000-08-11 19:02:59 +0000672/* a portable fseek() function
673 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000674static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000675_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000676{
Guido van Rossumb8552162001-09-05 14:58:11 +0000677#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000678 return fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000679#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000680 return fseeko(fp, offset, whence);
Trent Mickf29f47b2000-08-11 19:02:59 +0000681#elif defined(HAVE_FSEEK64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000682 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000683#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000685#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000686 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
687 and fgetpos() to implement fseek()*/
688 fpos_t pos;
689 switch (whence) {
690 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000691#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000692 fflush(fp);
693 if (_lseeki64(fileno(fp), 0, 2) == -1)
694 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000695#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000696 if (fseek(fp, 0, SEEK_END) != 0)
697 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000698#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000699 /* fall through */
700 case SEEK_CUR:
701 if (fgetpos(fp, &pos) != 0)
702 return -1;
703 offset += pos;
704 break;
705 /* case SEEK_SET: break; */
706 }
707 return fsetpos(fp, &offset);
Trent Mickf29f47b2000-08-11 19:02:59 +0000708#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000709#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000710#endif
711}
712
713
714/* a portable ftell() function
715 Return -1 on failure with errno set appropriately, current file
716 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000717static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000718_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000719{
Guido van Rossumb8552162001-09-05 14:58:11 +0000720#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000721 return ftell(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000722#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000723 return ftello(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000724#elif defined(HAVE_FTELL64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000725 return ftell64(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000726#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000727 fpos_t pos;
728 if (fgetpos(fp, &pos) != 0)
729 return -1;
730 return pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000731#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000732#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000733#endif
734}
735
736
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000738file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000739{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000740 int whence;
741 int ret;
742 Py_off_t offset;
743 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000744
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 if (f->f_fp == NULL)
746 return err_closed();
747 drop_readahead(f);
748 whence = 0;
749 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
750 return NULL;
751 off_index = PyNumber_Index(offobj);
752 if (!off_index) {
753 if (!PyFloat_Check(offobj))
754 return NULL;
755 /* Deprecated in 2.6 */
756 PyErr_Clear();
757 if (PyErr_WarnEx(PyExc_DeprecationWarning,
758 "integer argument expected, got float",
759 1) < 0)
760 return NULL;
761 off_index = offobj;
762 Py_INCREF(offobj);
763 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000764#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000765 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000766#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000767 offset = PyLong_Check(off_index) ?
768 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000769#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000770 Py_DECREF(off_index);
771 if (PyErr_Occurred())
772 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000773
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000774 FILE_BEGIN_ALLOW_THREADS(f)
775 errno = 0;
776 ret = _portable_fseek(f->f_fp, offset, whence);
777 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000778
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000779 if (ret != 0) {
780 PyErr_SetFromErrno(PyExc_IOError);
781 clearerr(f->f_fp);
782 return NULL;
783 }
784 f->f_skipnextlf = 0;
785 Py_INCREF(Py_None);
786 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000787}
788
Trent Mickf29f47b2000-08-11 19:02:59 +0000789
Guido van Rossumd7047b31995-01-02 19:07:15 +0000790#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000791static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000792file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000793{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000794 Py_off_t newsize;
795 PyObject *newsizeobj = NULL;
796 Py_off_t initialpos;
797 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000798
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000799 if (f->f_fp == NULL)
800 return err_closed();
801 if (!f->writable)
802 return err_mode("writing");
803 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
804 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000805
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000806 /* Get current file position. If the file happens to be open for
807 * update and the last operation was an input operation, C doesn't
808 * define what the later fflush() will do, but we promise truncate()
809 * won't change the current position (and fflush() *does* change it
810 * then at least on Windows). The easiest thing is to capture
811 * current pos now and seek back to it at the end.
812 */
813 FILE_BEGIN_ALLOW_THREADS(f)
814 errno = 0;
815 initialpos = _portable_ftell(f->f_fp);
816 FILE_END_ALLOW_THREADS(f)
817 if (initialpos == -1)
818 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000819
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000820 /* Set newsize to current postion if newsizeobj NULL, else to the
821 * specified value.
822 */
823 if (newsizeobj != NULL) {
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000824#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000825 newsize = PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000826#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000827 newsize = PyLong_Check(newsizeobj) ?
828 PyLong_AsLongLong(newsizeobj) :
829 PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000830#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000831 if (PyErr_Occurred())
832 return NULL;
833 }
834 else /* default to current position */
835 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000836
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000837 /* Flush the stream. We're mixing stream-level I/O with lower-level
838 * I/O, and a flush may be necessary to synch both platform views
839 * of the current file state.
840 */
841 FILE_BEGIN_ALLOW_THREADS(f)
842 errno = 0;
843 ret = fflush(f->f_fp);
844 FILE_END_ALLOW_THREADS(f)
845 if (ret != 0)
846 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000847
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000848#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
850 so don't even try using it. */
851 {
852 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000853
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000854 /* Have to move current pos to desired endpoint on Windows. */
855 FILE_BEGIN_ALLOW_THREADS(f)
856 errno = 0;
857 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
858 FILE_END_ALLOW_THREADS(f)
859 if (ret)
860 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000861
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000862 /* Truncate. Note that this may grow the file! */
863 FILE_BEGIN_ALLOW_THREADS(f)
864 errno = 0;
865 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
866 ret = hFile == (HANDLE)-1;
867 if (ret == 0) {
868 ret = SetEndOfFile(hFile) == 0;
869 if (ret)
870 errno = EACCES;
871 }
872 FILE_END_ALLOW_THREADS(f)
873 if (ret)
874 goto onioerror;
875 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000876#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 FILE_BEGIN_ALLOW_THREADS(f)
878 errno = 0;
879 ret = ftruncate(fileno(f->f_fp), newsize);
880 FILE_END_ALLOW_THREADS(f)
881 if (ret != 0)
882 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000883#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000884
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000885 /* Restore original file position. */
886 FILE_BEGIN_ALLOW_THREADS(f)
887 errno = 0;
888 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
889 FILE_END_ALLOW_THREADS(f)
890 if (ret)
891 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000892
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000893 Py_INCREF(Py_None);
894 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000895
896onioerror:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 PyErr_SetFromErrno(PyExc_IOError);
898 clearerr(f->f_fp);
899 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000900}
901#endif /* HAVE_FTRUNCATE */
902
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000903static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000904file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000905{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000907
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000908 if (f->f_fp == NULL)
909 return err_closed();
910 FILE_BEGIN_ALLOW_THREADS(f)
911 errno = 0;
912 pos = _portable_ftell(f->f_fp);
913 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000914
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000915 if (pos == -1) {
916 PyErr_SetFromErrno(PyExc_IOError);
917 clearerr(f->f_fp);
918 return NULL;
919 }
920 if (f->f_skipnextlf) {
921 int c;
922 c = GETC(f->f_fp);
923 if (c == '\n') {
924 f->f_newlinetypes |= NEWLINE_CRLF;
925 pos++;
926 f->f_skipnextlf = 0;
927 } else if (c != EOF) ungetc(c, f->f_fp);
928 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000929#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000930 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000931#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000932 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000933#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000934}
935
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000936static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000937file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000938{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000939 if (f->f_fp == NULL)
940 return err_closed();
941 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000942}
943
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000944static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000945file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000946{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000947 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000948
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 if (f->f_fp == NULL)
950 return err_closed();
951 FILE_BEGIN_ALLOW_THREADS(f)
952 errno = 0;
953 res = fflush(f->f_fp);
954 FILE_END_ALLOW_THREADS(f)
955 if (res != 0) {
956 PyErr_SetFromErrno(PyExc_IOError);
957 clearerr(f->f_fp);
958 return NULL;
959 }
960 Py_INCREF(Py_None);
961 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000962}
963
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000964static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000965file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000966{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 long res;
968 if (f->f_fp == NULL)
969 return err_closed();
970 FILE_BEGIN_ALLOW_THREADS(f)
971 res = isatty((int)fileno(f->f_fp));
972 FILE_END_ALLOW_THREADS(f)
973 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000974}
975
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000976
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000977#if BUFSIZ < 8192
978#define SMALLCHUNK 8192
979#else
980#define SMALLCHUNK BUFSIZ
981#endif
982
Guido van Rossum3c259041999-01-14 19:00:14 +0000983#if SIZEOF_INT < 4
984#define BIGCHUNK (512 * 32)
985#else
986#define BIGCHUNK (512 * 1024)
987#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000988
989static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000990new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000991{
992#ifdef HAVE_FSTAT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 off_t pos, end;
994 struct stat st;
995 if (fstat(fileno(f->f_fp), &st) == 0) {
996 end = st.st_size;
997 /* The following is not a bug: we really need to call lseek()
998 *and* ftell(). The reason is that some stdio libraries
999 mistakenly flush their buffer when ftell() is called and
1000 the lseek() call it makes fails, thereby throwing away
1001 data that cannot be recovered in any way. To avoid this,
1002 we first test lseek(), and only call ftell() if lseek()
1003 works. We can't use the lseek() value either, because we
1004 need to take the amount of buffered data into account.
1005 (Yet another reason why stdio stinks. :-) */
1006 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
1007 if (pos >= 0) {
1008 pos = ftell(f->f_fp);
1009 }
1010 if (pos < 0)
1011 clearerr(f->f_fp);
1012 if (end > pos && pos >= 0)
1013 return currentsize + end - pos + 1;
1014 /* Add 1 so if the file were to grow we'd notice. */
1015 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001016#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001017 if (currentsize > SMALLCHUNK) {
1018 /* Keep doubling until we reach BIGCHUNK;
1019 then keep adding BIGCHUNK. */
1020 if (currentsize <= BIGCHUNK)
1021 return currentsize + currentsize;
1022 else
1023 return currentsize + BIGCHUNK;
1024 }
1025 return currentsize + SMALLCHUNK;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001026}
1027
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001028#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1029#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1030#else
1031#ifdef EWOULDBLOCK
1032#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1033#else
1034#ifdef EAGAIN
1035#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1036#else
1037#define BLOCKED_ERRNO(x) 0
1038#endif
1039#endif
1040#endif
1041
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001042static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001043file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001044{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001045 long bytesrequested = -1;
1046 size_t bytesread, buffersize, chunksize;
1047 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001048
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001049 if (f->f_fp == NULL)
1050 return err_closed();
1051 if (!f->readable)
1052 return err_mode("reading");
1053 /* refuse to mix with f.next() */
1054 if (f->f_buf != NULL &&
1055 (f->f_bufend - f->f_bufptr) > 0 &&
1056 f->f_buf[0] != '\0')
1057 return err_iterbuffered();
1058 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
1059 return NULL;
1060 if (bytesrequested < 0)
1061 buffersize = new_buffersize(f, (size_t)0);
1062 else
1063 buffersize = bytesrequested;
1064 if (buffersize > PY_SSIZE_T_MAX) {
1065 PyErr_SetString(PyExc_OverflowError,
1066 "requested number of bytes is more than a Python string can hold");
1067 return NULL;
1068 }
1069 v = PyString_FromStringAndSize((char *)NULL, buffersize);
1070 if (v == NULL)
1071 return NULL;
1072 bytesread = 0;
1073 for (;;) {
1074 FILE_BEGIN_ALLOW_THREADS(f)
1075 errno = 0;
1076 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
1077 buffersize - bytesread, f->f_fp, (PyObject *)f);
1078 FILE_END_ALLOW_THREADS(f)
1079 if (chunksize == 0) {
1080 if (!ferror(f->f_fp))
1081 break;
1082 clearerr(f->f_fp);
1083 /* When in non-blocking mode, data shouldn't
1084 * be discarded if a blocking signal was
1085 * received. That will also happen if
1086 * chunksize != 0, but bytesread < buffersize. */
1087 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1088 break;
1089 PyErr_SetFromErrno(PyExc_IOError);
1090 Py_DECREF(v);
1091 return NULL;
1092 }
1093 bytesread += chunksize;
1094 if (bytesread < buffersize) {
1095 clearerr(f->f_fp);
1096 break;
1097 }
1098 if (bytesrequested < 0) {
1099 buffersize = new_buffersize(f, buffersize);
1100 if (_PyString_Resize(&v, buffersize) < 0)
1101 return NULL;
1102 } else {
1103 /* Got what was requested. */
1104 break;
1105 }
1106 }
1107 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1108 return NULL;
1109 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001110}
1111
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001112static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001113file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001114{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001115 char *ptr;
1116 Py_ssize_t ntodo;
1117 Py_ssize_t ndone, nnow;
1118 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 if (f->f_fp == NULL)
1121 return err_closed();
1122 if (!f->readable)
1123 return err_mode("reading");
1124 /* refuse to mix with f.next() */
1125 if (f->f_buf != NULL &&
1126 (f->f_bufend - f->f_bufptr) > 0 &&
1127 f->f_buf[0] != '\0')
1128 return err_iterbuffered();
1129 if (!PyArg_ParseTuple(args, "w*", &pbuf))
1130 return NULL;
1131 ptr = pbuf.buf;
1132 ntodo = pbuf.len;
1133 ndone = 0;
1134 while (ntodo > 0) {
1135 FILE_BEGIN_ALLOW_THREADS(f)
1136 errno = 0;
1137 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
1138 (PyObject *)f);
1139 FILE_END_ALLOW_THREADS(f)
1140 if (nnow == 0) {
1141 if (!ferror(f->f_fp))
1142 break;
1143 PyErr_SetFromErrno(PyExc_IOError);
1144 clearerr(f->f_fp);
1145 PyBuffer_Release(&pbuf);
1146 return NULL;
1147 }
1148 ndone += nnow;
1149 ntodo -= nnow;
1150 }
1151 PyBuffer_Release(&pbuf);
1152 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001153}
1154
Tim Peters86821b22001-01-07 21:19:34 +00001155/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001156Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001157
1158Under MSVC 6:
1159
Tim Peters1c733232001-01-08 04:02:07 +00001160+ MS threadsafe getc is very slow (multiple layers of function calls before+
1161 after each character, to lock+unlock the stream).
1162+ The stream-locking functions are MS-internal -- can't access them from user
1163 code.
1164+ There's nothing Tim could find in the MS C or platform SDK libraries that
1165 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001166+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1167
1168So we use fgets for speed(!), despite that it's painful.
1169
1170MS realloc is also slow.
1171
Tim Petersf29b64d2001-01-15 06:33:19 +00001172Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1173have):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 Linux a wash
1175 Solaris a wash
1176 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001177
Tim Petersf29b64d2001-01-15 06:33:19 +00001178CAUTION: The C std isn't clear about this: in those cases where fgets
1179writes something into the buffer, can it write into any position beyond the
1180required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1181known on which it does; and it would be a strange way to code fgets. Still,
1182getline_via_fgets may not work correctly if it does. The std test
1183test_bufio.py should fail if platform fgets() routinely writes beyond the
1184trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001185**************************************************************************/
1186
Tim Petersf29b64d2001-01-15 06:33:19 +00001187/* Use this routine if told to, or by default on non-get_unlocked()
1188 * platforms unless told not to. Yikes! Let's spell that out:
1189 * On a platform with getc_unlocked():
1190 * By default, use getc_unlocked().
1191 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1192 * On a platform without getc_unlocked():
1193 * By default, use fgets().
1194 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1195 */
1196#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1197#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001198#endif
1199
Tim Petersf29b64d2001-01-15 06:33:19 +00001200#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1201#undef USE_FGETS_IN_GETLINE
1202#endif
1203
1204#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001205static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001206getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001207{
Tim Peters15b83852001-01-08 00:53:12 +00001208/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001209 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1210 * to fill this much of the buffer with a known value in order to figure out
1211 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1212 * than "most" lines, we waste time filling unused buffer slots. 100 is
1213 * surely adequate for most peoples' email archives, chewing over source code,
1214 * etc -- "regular old text files".
1215 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1216 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1217 * cautions about boosting that. 300 was chosen because the worst real-life
1218 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1219 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001220 */
Tim Peters142297a2001-01-15 10:36:56 +00001221#define INITBUFSIZE 100
1222#define MAXBUFSIZE 300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 char* p; /* temp */
1224 char buf[MAXBUFSIZE];
1225 PyObject* v; /* the string object result */
1226 char* pvfree; /* address of next free slot */
1227 char* pvend; /* address one beyond last free slot */
1228 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1229 size_t total_v_size; /* total # of slots in buffer */
1230 size_t increment; /* amount to increment the buffer */
1231 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001232
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001233 /* Optimize for normal case: avoid _PyString_Resize if at all
1234 * possible via first reading into stack buffer "buf".
1235 */
1236 total_v_size = INITBUFSIZE; /* start small and pray */
1237 pvfree = buf;
1238 for (;;) {
1239 FILE_BEGIN_ALLOW_THREADS(f)
1240 pvend = buf + total_v_size;
1241 nfree = pvend - pvfree;
1242 memset(pvfree, '\n', nfree);
1243 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1244 p = fgets(pvfree, (int)nfree, fp);
1245 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001246
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001247 if (p == NULL) {
1248 clearerr(fp);
1249 if (PyErr_CheckSignals())
1250 return NULL;
1251 v = PyString_FromStringAndSize(buf, pvfree - buf);
1252 return v;
1253 }
1254 /* fgets read *something* */
1255 p = memchr(pvfree, '\n', nfree);
1256 if (p != NULL) {
1257 /* Did the \n come from fgets or from us?
1258 * Since fgets stops at the first \n, and then writes
1259 * \0, if it's from fgets a \0 must be next. But if
1260 * that's so, it could not have come from us, since
1261 * the \n's we filled the buffer with have only more
1262 * \n's to the right.
1263 */
1264 if (p+1 < pvend && *(p+1) == '\0') {
1265 /* It's from fgets: we win! In particular,
1266 * we haven't done any mallocs yet, and can
1267 * build the final result on the first try.
1268 */
1269 ++p; /* include \n from fgets */
1270 }
1271 else {
1272 /* Must be from us: fgets didn't fill the
1273 * buffer and didn't find a newline, so it
1274 * must be the last and newline-free line of
1275 * the file.
1276 */
1277 assert(p > pvfree && *(p-1) == '\0');
1278 --p; /* don't include \0 from fgets */
1279 }
1280 v = PyString_FromStringAndSize(buf, p - buf);
1281 return v;
1282 }
1283 /* yuck: fgets overwrote all the newlines, i.e. the entire
1284 * buffer. So this line isn't over yet, or maybe it is but
1285 * we're exactly at EOF. If we haven't already, try using the
1286 * rest of the stack buffer.
1287 */
1288 assert(*(pvend-1) == '\0');
1289 if (pvfree == buf) {
1290 pvfree = pvend - 1; /* overwrite trailing null */
1291 total_v_size = MAXBUFSIZE;
1292 }
1293 else
1294 break;
1295 }
Tim Peters142297a2001-01-15 10:36:56 +00001296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001297 /* The stack buffer isn't big enough; malloc a string object and read
1298 * into its buffer.
1299 */
1300 total_v_size = MAXBUFSIZE << 1;
1301 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
1302 if (v == NULL)
1303 return v;
1304 /* copy over everything except the last null byte */
1305 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1306 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001307
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001308 /* Keep reading stuff into v; if it ever ends successfully, break
1309 * after setting p one beyond the end of the line. The code here is
1310 * very much like the code above, except reads into v's buffer; see
1311 * the code above for detailed comments about the logic.
1312 */
1313 for (;;) {
1314 FILE_BEGIN_ALLOW_THREADS(f)
1315 pvend = BUF(v) + total_v_size;
1316 nfree = pvend - pvfree;
1317 memset(pvfree, '\n', nfree);
1318 assert(nfree < INT_MAX);
1319 p = fgets(pvfree, (int)nfree, fp);
1320 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001321
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001322 if (p == NULL) {
1323 clearerr(fp);
1324 if (PyErr_CheckSignals()) {
1325 Py_DECREF(v);
1326 return NULL;
1327 }
1328 p = pvfree;
1329 break;
1330 }
1331 p = memchr(pvfree, '\n', nfree);
1332 if (p != NULL) {
1333 if (p+1 < pvend && *(p+1) == '\0') {
1334 /* \n came from fgets */
1335 ++p;
1336 break;
1337 }
1338 /* \n came from us; last line of file, no newline */
1339 assert(p > pvfree && *(p-1) == '\0');
1340 --p;
1341 break;
1342 }
1343 /* expand buffer and try again */
1344 assert(*(pvend-1) == '\0');
1345 increment = total_v_size >> 2; /* mild exponential growth */
1346 prev_v_size = total_v_size;
1347 total_v_size += increment;
1348 /* check for overflow */
1349 if (total_v_size <= prev_v_size ||
1350 total_v_size > PY_SSIZE_T_MAX) {
1351 PyErr_SetString(PyExc_OverflowError,
1352 "line is longer than a Python string can hold");
1353 Py_DECREF(v);
1354 return NULL;
1355 }
1356 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1357 return NULL;
1358 /* overwrite the trailing null byte */
1359 pvfree = BUF(v) + (prev_v_size - 1);
1360 }
1361 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1362 return NULL;
1363 return v;
Tim Peters86821b22001-01-07 21:19:34 +00001364#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001365#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001366}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001367#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001368
Guido van Rossum0bd24411991-04-04 15:21:57 +00001369/* Internal routine to get a line.
1370 Size argument interpretation:
1371 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001372 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001373*/
1374
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001375static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001376get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001377{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001378 FILE *fp = f->f_fp;
1379 int c;
1380 char *buf, *end;
1381 size_t total_v_size; /* total # of slots in buffer */
1382 size_t used_v_size; /* # used slots in buffer */
1383 size_t increment; /* amount to increment the buffer */
1384 PyObject *v;
1385 int newlinetypes = f->f_newlinetypes;
1386 int skipnextlf = f->f_skipnextlf;
1387 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001388
Jack Jansen7b8c7542002-04-14 20:12:41 +00001389#if defined(USE_FGETS_IN_GETLINE)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001390 if (n <= 0 && !univ_newline )
1391 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001392#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001393 total_v_size = n > 0 ? n : 100;
1394 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
1395 if (v == NULL)
1396 return NULL;
1397 buf = BUF(v);
1398 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001399
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001400 for (;;) {
1401 FILE_BEGIN_ALLOW_THREADS(f)
1402 FLOCKFILE(fp);
1403 if (univ_newline) {
1404 c = 'x'; /* Shut up gcc warning */
1405 while ( buf != end && (c = GETC(fp)) != EOF ) {
1406 if (skipnextlf ) {
1407 skipnextlf = 0;
1408 if (c == '\n') {
1409 /* Seeing a \n here with
1410 * skipnextlf true means we
1411 * saw a \r before.
1412 */
1413 newlinetypes |= NEWLINE_CRLF;
1414 c = GETC(fp);
1415 if (c == EOF) break;
1416 } else {
1417 newlinetypes |= NEWLINE_CR;
1418 }
1419 }
1420 if (c == '\r') {
1421 skipnextlf = 1;
1422 c = '\n';
1423 } else if ( c == '\n')
1424 newlinetypes |= NEWLINE_LF;
1425 *buf++ = c;
1426 if (c == '\n') break;
1427 }
1428 if ( c == EOF && skipnextlf )
1429 newlinetypes |= NEWLINE_CR;
1430 } else /* If not universal newlines use the normal loop */
1431 while ((c = GETC(fp)) != EOF &&
1432 (*buf++ = c) != '\n' &&
1433 buf != end)
1434 ;
1435 FUNLOCKFILE(fp);
1436 FILE_END_ALLOW_THREADS(f)
1437 f->f_newlinetypes = newlinetypes;
1438 f->f_skipnextlf = skipnextlf;
1439 if (c == '\n')
1440 break;
1441 if (c == EOF) {
1442 if (ferror(fp)) {
1443 PyErr_SetFromErrno(PyExc_IOError);
1444 clearerr(fp);
1445 Py_DECREF(v);
1446 return NULL;
1447 }
1448 clearerr(fp);
1449 if (PyErr_CheckSignals()) {
1450 Py_DECREF(v);
1451 return NULL;
1452 }
1453 break;
1454 }
1455 /* Must be because buf == end */
1456 if (n > 0)
1457 break;
1458 used_v_size = total_v_size;
1459 increment = total_v_size >> 2; /* mild exponential growth */
1460 total_v_size += increment;
1461 if (total_v_size > PY_SSIZE_T_MAX) {
1462 PyErr_SetString(PyExc_OverflowError,
1463 "line is longer than a Python string can hold");
1464 Py_DECREF(v);
1465 return NULL;
1466 }
1467 if (_PyString_Resize(&v, total_v_size) < 0)
1468 return NULL;
1469 buf = BUF(v) + used_v_size;
1470 end = BUF(v) + total_v_size;
1471 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001472
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001473 used_v_size = buf - BUF(v);
1474 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1475 return NULL;
1476 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001477}
1478
Guido van Rossum0bd24411991-04-04 15:21:57 +00001479/* External C interface */
1480
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001481PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001482PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001483{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001484 PyObject *result;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001485
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001486 if (f == NULL) {
1487 PyErr_BadInternalCall();
1488 return NULL;
1489 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001490
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 if (PyFile_Check(f)) {
1492 PyFileObject *fo = (PyFileObject *)f;
1493 if (fo->f_fp == NULL)
1494 return err_closed();
1495 if (!fo->readable)
1496 return err_mode("reading");
1497 /* refuse to mix with f.next() */
1498 if (fo->f_buf != NULL &&
1499 (fo->f_bufend - fo->f_bufptr) > 0 &&
1500 fo->f_buf[0] != '\0')
1501 return err_iterbuffered();
1502 result = get_line(fo, n);
1503 }
1504 else {
1505 PyObject *reader;
1506 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001508 reader = PyObject_GetAttrString(f, "readline");
1509 if (reader == NULL)
1510 return NULL;
1511 if (n <= 0)
1512 args = PyTuple_New(0);
1513 else
1514 args = Py_BuildValue("(i)", n);
1515 if (args == NULL) {
1516 Py_DECREF(reader);
1517 return NULL;
1518 }
1519 result = PyEval_CallObject(reader, args);
1520 Py_DECREF(reader);
1521 Py_DECREF(args);
1522 if (result != NULL && !PyString_Check(result) &&
1523 !PyUnicode_Check(result)) {
1524 Py_DECREF(result);
1525 result = NULL;
1526 PyErr_SetString(PyExc_TypeError,
1527 "object.readline() returned non-string");
1528 }
1529 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001530
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001531 if (n < 0 && result != NULL && PyString_Check(result)) {
1532 char *s = PyString_AS_STRING(result);
1533 Py_ssize_t len = PyString_GET_SIZE(result);
1534 if (len == 0) {
1535 Py_DECREF(result);
1536 result = NULL;
1537 PyErr_SetString(PyExc_EOFError,
1538 "EOF when reading a line");
1539 }
1540 else if (s[len-1] == '\n') {
1541 if (result->ob_refcnt == 1) {
1542 if (_PyString_Resize(&result, len-1))
1543 return NULL;
1544 }
1545 else {
1546 PyObject *v;
1547 v = PyString_FromStringAndSize(s, len-1);
1548 Py_DECREF(result);
1549 result = v;
1550 }
1551 }
1552 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001553#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001554 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1555 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1556 Py_ssize_t len = PyUnicode_GET_SIZE(result);
1557 if (len == 0) {
1558 Py_DECREF(result);
1559 result = NULL;
1560 PyErr_SetString(PyExc_EOFError,
1561 "EOF when reading a line");
1562 }
1563 else if (s[len-1] == '\n') {
1564 if (result->ob_refcnt == 1)
1565 PyUnicode_Resize(&result, len-1);
1566 else {
1567 PyObject *v;
1568 v = PyUnicode_FromUnicode(s, len-1);
1569 Py_DECREF(result);
1570 result = v;
1571 }
1572 }
1573 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001574#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001575 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001576}
1577
1578/* Python method */
1579
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001580static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001581file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001582{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001583 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001584
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001585 if (f->f_fp == NULL)
1586 return err_closed();
1587 if (!f->readable)
1588 return err_mode("reading");
1589 /* refuse to mix with f.next() */
1590 if (f->f_buf != NULL &&
1591 (f->f_bufend - f->f_bufptr) > 0 &&
1592 f->f_buf[0] != '\0')
1593 return err_iterbuffered();
1594 if (!PyArg_ParseTuple(args, "|i:readline", &n))
1595 return NULL;
1596 if (n == 0)
1597 return PyString_FromString("");
1598 if (n < 0)
1599 n = 0;
1600 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001601}
1602
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001603static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001604file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001605{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001606 long sizehint = 0;
1607 PyObject *list = NULL;
1608 PyObject *line;
1609 char small_buffer[SMALLCHUNK];
1610 char *buffer = small_buffer;
1611 size_t buffersize = SMALLCHUNK;
1612 PyObject *big_buffer = NULL;
1613 size_t nfilled = 0;
1614 size_t nread;
1615 size_t totalread = 0;
1616 char *p, *q, *end;
1617 int err;
1618 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001619
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001620 if (f->f_fp == NULL)
1621 return err_closed();
1622 if (!f->readable)
1623 return err_mode("reading");
1624 /* refuse to mix with f.next() */
1625 if (f->f_buf != NULL &&
1626 (f->f_bufend - f->f_bufptr) > 0 &&
1627 f->f_buf[0] != '\0')
1628 return err_iterbuffered();
1629 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
1630 return NULL;
1631 if ((list = PyList_New(0)) == NULL)
1632 return NULL;
1633 for (;;) {
1634 if (shortread)
1635 nread = 0;
1636 else {
1637 FILE_BEGIN_ALLOW_THREADS(f)
1638 errno = 0;
1639 nread = Py_UniversalNewlineFread(buffer+nfilled,
1640 buffersize-nfilled, f->f_fp, (PyObject *)f);
1641 FILE_END_ALLOW_THREADS(f)
1642 shortread = (nread < buffersize-nfilled);
1643 }
1644 if (nread == 0) {
1645 sizehint = 0;
1646 if (!ferror(f->f_fp))
1647 break;
1648 PyErr_SetFromErrno(PyExc_IOError);
1649 clearerr(f->f_fp);
1650 goto error;
1651 }
1652 totalread += nread;
1653 p = (char *)memchr(buffer+nfilled, '\n', nread);
1654 if (p == NULL) {
1655 /* Need a larger buffer to fit this line */
1656 nfilled += nread;
1657 buffersize *= 2;
1658 if (buffersize > PY_SSIZE_T_MAX) {
1659 PyErr_SetString(PyExc_OverflowError,
1660 "line is longer than a Python string can hold");
1661 goto error;
1662 }
1663 if (big_buffer == NULL) {
1664 /* Create the big buffer */
1665 big_buffer = PyString_FromStringAndSize(
1666 NULL, buffersize);
1667 if (big_buffer == NULL)
1668 goto error;
1669 buffer = PyString_AS_STRING(big_buffer);
1670 memcpy(buffer, small_buffer, nfilled);
1671 }
1672 else {
1673 /* Grow the big buffer */
1674 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1675 goto error;
1676 buffer = PyString_AS_STRING(big_buffer);
1677 }
1678 continue;
1679 }
1680 end = buffer+nfilled+nread;
1681 q = buffer;
1682 do {
1683 /* Process complete lines */
1684 p++;
1685 line = PyString_FromStringAndSize(q, p-q);
1686 if (line == NULL)
1687 goto error;
1688 err = PyList_Append(list, line);
1689 Py_DECREF(line);
1690 if (err != 0)
1691 goto error;
1692 q = p;
1693 p = (char *)memchr(q, '\n', end-q);
1694 } while (p != NULL);
1695 /* Move the remaining incomplete line to the start */
1696 nfilled = end-q;
1697 memmove(buffer, q, nfilled);
1698 if (sizehint > 0)
1699 if (totalread >= (size_t)sizehint)
1700 break;
1701 }
1702 if (nfilled != 0) {
1703 /* Partial last line */
1704 line = PyString_FromStringAndSize(buffer, nfilled);
1705 if (line == NULL)
1706 goto error;
1707 if (sizehint > 0) {
1708 /* Need to complete the last line */
1709 PyObject *rest = get_line(f, 0);
1710 if (rest == NULL) {
1711 Py_DECREF(line);
1712 goto error;
1713 }
1714 PyString_Concat(&line, rest);
1715 Py_DECREF(rest);
1716 if (line == NULL)
1717 goto error;
1718 }
1719 err = PyList_Append(list, line);
1720 Py_DECREF(line);
1721 if (err != 0)
1722 goto error;
1723 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001724
1725cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001726 Py_XDECREF(big_buffer);
1727 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001728
1729error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001730 Py_CLEAR(list);
1731 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001732}
1733
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001734static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001735file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001736{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 Py_buffer pbuf;
1738 char *s;
1739 Py_ssize_t n, n2;
1740 if (f->f_fp == NULL)
1741 return err_closed();
1742 if (!f->writable)
1743 return err_mode("writing");
1744 if (f->f_binary) {
1745 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1746 return NULL;
1747 s = pbuf.buf;
1748 n = pbuf.len;
1749 } else
1750 if (!PyArg_ParseTuple(args, "t#", &s, &n))
1751 return NULL;
1752 f->f_softspace = 0;
1753 FILE_BEGIN_ALLOW_THREADS(f)
1754 errno = 0;
1755 n2 = fwrite(s, 1, n, f->f_fp);
1756 FILE_END_ALLOW_THREADS(f)
1757 if (f->f_binary)
1758 PyBuffer_Release(&pbuf);
1759 if (n2 != n) {
1760 PyErr_SetFromErrno(PyExc_IOError);
1761 clearerr(f->f_fp);
1762 return NULL;
1763 }
1764 Py_INCREF(Py_None);
1765 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001766}
1767
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001768static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001769file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001770{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001771#define CHUNKSIZE 1000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001772 PyObject *list, *line;
1773 PyObject *it; /* iter(seq) */
1774 PyObject *result;
1775 int index, islist;
1776 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001778 assert(seq != NULL);
1779 if (f->f_fp == NULL)
1780 return err_closed();
1781 if (!f->writable)
1782 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001783
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001784 result = NULL;
1785 list = NULL;
1786 islist = PyList_Check(seq);
1787 if (islist)
1788 it = NULL;
1789 else {
1790 it = PyObject_GetIter(seq);
1791 if (it == NULL) {
1792 PyErr_SetString(PyExc_TypeError,
1793 "writelines() requires an iterable argument");
1794 return NULL;
1795 }
1796 /* From here on, fail by going to error, to reclaim "it". */
1797 list = PyList_New(CHUNKSIZE);
1798 if (list == NULL)
1799 goto error;
1800 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001801
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001802 /* Strategy: slurp CHUNKSIZE lines into a private list,
1803 checking that they are all strings, then write that list
1804 without holding the interpreter lock, then come back for more. */
1805 for (index = 0; ; index += CHUNKSIZE) {
1806 if (islist) {
1807 Py_XDECREF(list);
1808 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
1809 if (list == NULL)
1810 goto error;
1811 j = PyList_GET_SIZE(list);
1812 }
1813 else {
1814 for (j = 0; j < CHUNKSIZE; j++) {
1815 line = PyIter_Next(it);
1816 if (line == NULL) {
1817 if (PyErr_Occurred())
1818 goto error;
1819 break;
1820 }
1821 PyList_SetItem(list, j, line);
1822 }
1823 }
1824 if (j == 0)
1825 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001826
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001827 /* Check that all entries are indeed strings. If not,
1828 apply the same rules as for file.write() and
1829 convert the results to strings. This is slow, but
1830 seems to be the only way since all conversion APIs
1831 could potentially execute Python code. */
1832 for (i = 0; i < j; i++) {
1833 PyObject *v = PyList_GET_ITEM(list, i);
1834 if (!PyString_Check(v)) {
1835 const char *buffer;
1836 if (((f->f_binary &&
1837 PyObject_AsReadBuffer(v,
1838 (const void**)&buffer,
1839 &len)) ||
1840 PyObject_AsCharBuffer(v,
1841 &buffer,
1842 &len))) {
1843 PyErr_SetString(PyExc_TypeError,
1844 "writelines() argument must be a sequence of strings");
1845 goto error;
1846 }
1847 line = PyString_FromStringAndSize(buffer,
1848 len);
1849 if (line == NULL)
1850 goto error;
1851 Py_DECREF(v);
1852 PyList_SET_ITEM(list, i, line);
1853 }
1854 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001855
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001856 /* Since we are releasing the global lock, the
1857 following code may *not* execute Python code. */
1858 f->f_softspace = 0;
1859 FILE_BEGIN_ALLOW_THREADS(f)
1860 errno = 0;
1861 for (i = 0; i < j; i++) {
1862 line = PyList_GET_ITEM(list, i);
1863 len = PyString_GET_SIZE(line);
1864 nwritten = fwrite(PyString_AS_STRING(line),
1865 1, len, f->f_fp);
1866 if (nwritten != len) {
1867 FILE_ABORT_ALLOW_THREADS(f)
1868 PyErr_SetFromErrno(PyExc_IOError);
1869 clearerr(f->f_fp);
1870 goto error;
1871 }
1872 }
1873 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 if (j < CHUNKSIZE)
1876 break;
1877 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001878
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 Py_INCREF(Py_None);
1880 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001881 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001882 Py_XDECREF(list);
1883 Py_XDECREF(it);
1884 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001885#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001886}
1887
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001888static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001889file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001890{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001891 if (f->f_fp == NULL)
1892 return err_closed();
1893 Py_INCREF(f);
1894 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001895}
1896
Georg Brandl98b40ad2006-06-08 14:50:21 +00001897static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001898file_xreadlines(PyFileObject *f)
1899{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001900 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1901 "try 'for line in f' instead", 1) < 0)
1902 return NULL;
1903 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00001904}
1905
1906static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001907file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001908{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001909 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
1910 if (!ret)
1911 /* If error occurred, pass through */
1912 return NULL;
1913 Py_DECREF(ret);
1914 /* We cannot return the result of close since a true
1915 * value will be interpreted as "yes, swallow the
1916 * exception if one was raised inside the with block". */
1917 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00001918}
1919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001920PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001921"readline([size]) -> next line from the file, as a string.\n"
1922"\n"
1923"Retain newline. A non-negative size argument limits the maximum\n"
1924"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001925"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001926
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001927PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001928"read([size]) -> read at most size bytes, returned as a string.\n"
1929"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001930"If the size argument is negative or omitted, read until EOF is reached.\n"
1931"Notice that when in non-blocking mode, less data than what was requested\n"
1932"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001934PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001935"write(str) -> None. Write string str to file.\n"
1936"\n"
1937"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001938"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001940PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001941"fileno() -> integer \"file descriptor\".\n"
1942"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001943"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001944
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001945PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001946"seek(offset[, whence]) -> None. Move to new file position.\n"
1947"\n"
1948"Argument offset is a byte count. Optional argument whence defaults to\n"
1949"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1950"(move relative to current position, positive or negative), and 2 (move\n"
1951"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001952"seeking beyond the end of a file). If the file is opened in text mode,\n"
1953"only offsets returned by tell() are legal. Use of other offsets causes\n"
1954"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001955"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001956"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001957
Guido van Rossumd7047b31995-01-02 19:07:15 +00001958#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001959PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001960"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1961"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001962"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001963#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001965PyDoc_STRVAR(tell_doc,
1966"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001968PyDoc_STRVAR(readinto_doc,
1969"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001970
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001972"readlines([size]) -> list of strings, each a line from the file.\n"
1973"\n"
1974"Call readline() repeatedly and return a list of the lines so read.\n"
1975"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001976"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001977
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001978PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001979"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001980"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001981"For backward compatibility. File objects now include the performance\n"
1982"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001983
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001984PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001985"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001986"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001987"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001988"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001989
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001990PyDoc_STRVAR(flush_doc,
1991"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001993PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001994"close() -> None or (perhaps) an integer. Close the file.\n"
1995"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001996"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001997"further I/O operations. close() may be called more than once without\n"
1998"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001999"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002000
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002001PyDoc_STRVAR(isatty_doc,
2002"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002003
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002004PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002005 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002006
Georg Brandl98b40ad2006-06-08 14:50:21 +00002007PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002008 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002009
Tim Petersefc3a3a2001-09-20 07:55:22 +00002010static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002011 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2012 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2013 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2014 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2015 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002016#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002017 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002018#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002019 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2020 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2021 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2022 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2023 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2024 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2025 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2026 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2027 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2028 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2029 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002030};
2031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002032#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002033
Guido van Rossum6f799372001-09-20 20:46:19 +00002034static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002035 {"mode", T_OBJECT, OFF(f_mode), RO,
2036 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2037 {"name", T_OBJECT, OFF(f_name), RO,
2038 "file name"},
2039 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2040 "file encoding"},
2041 {"errors", T_OBJECT, OFF(f_errors), RO,
2042 "Unicode error handler"},
2043 /* getattr(f, "closed") is implemented without this table */
2044 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002045};
2046
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002047static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002049{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002050 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002051}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002052static PyObject *
2053get_newlines(PyFileObject *f, void *closure)
2054{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002055 switch (f->f_newlinetypes) {
2056 case NEWLINE_UNKNOWN:
2057 Py_INCREF(Py_None);
2058 return Py_None;
2059 case NEWLINE_CR:
2060 return PyString_FromString("\r");
2061 case NEWLINE_LF:
2062 return PyString_FromString("\n");
2063 case NEWLINE_CR|NEWLINE_LF:
2064 return Py_BuildValue("(ss)", "\r", "\n");
2065 case NEWLINE_CRLF:
2066 return PyString_FromString("\r\n");
2067 case NEWLINE_CR|NEWLINE_CRLF:
2068 return Py_BuildValue("(ss)", "\r", "\r\n");
2069 case NEWLINE_LF|NEWLINE_CRLF:
2070 return Py_BuildValue("(ss)", "\n", "\r\n");
2071 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2072 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2073 default:
2074 PyErr_Format(PyExc_SystemError,
2075 "Unknown newlines value 0x%x\n",
2076 f->f_newlinetypes);
2077 return NULL;
2078 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002079}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002080
Georg Brandl65bb42d2008-03-21 20:38:24 +00002081static PyObject *
2082get_softspace(PyFileObject *f, void *closure)
2083{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002084 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2085 return NULL;
2086 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002087}
2088
2089static int
2090set_softspace(PyFileObject *f, PyObject *value)
2091{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002092 int new;
2093 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2094 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002095
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002096 if (value == NULL) {
2097 PyErr_SetString(PyExc_TypeError,
2098 "can't delete softspace attribute");
2099 return -1;
2100 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002101
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002102 new = PyInt_AsLong(value);
2103 if (new == -1 && PyErr_Occurred())
2104 return -1;
2105 f->f_softspace = new;
2106 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002107}
2108
Guido van Rossum32d34c82001-09-20 21:45:26 +00002109static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002110 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2111 {"newlines", (getter)get_newlines, NULL,
2112 "end-of-line convention used in this file"},
2113 {"softspace", (getter)get_softspace, (setter)set_softspace,
2114 "flag indicating that a space needs to be printed; used by print"},
2115 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002117
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002118static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002119drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002120{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002121 if (f->f_buf != NULL) {
2122 PyMem_Free(f->f_buf);
2123 f->f_buf = NULL;
2124 }
Guido van Rossum65967252001-04-21 13:20:18 +00002125}
2126
Tim Petersf1827cf2003-09-07 03:30:18 +00002127/* Make sure that file has a readahead buffer with at least one byte
2128 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002129 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002130static int
2131readahead(PyFileObject *f, int bufsize)
2132{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002133 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002134
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002135 if (f->f_buf != NULL) {
2136 if( (f->f_bufend - f->f_bufptr) >= 1)
2137 return 0;
2138 else
2139 drop_readahead(f);
2140 }
2141 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
2142 PyErr_NoMemory();
2143 return -1;
2144 }
2145 FILE_BEGIN_ALLOW_THREADS(f)
2146 errno = 0;
2147 chunksize = Py_UniversalNewlineFread(
2148 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
2149 FILE_END_ALLOW_THREADS(f)
2150 if (chunksize == 0) {
2151 if (ferror(f->f_fp)) {
2152 PyErr_SetFromErrno(PyExc_IOError);
2153 clearerr(f->f_fp);
2154 drop_readahead(f);
2155 return -1;
2156 }
2157 }
2158 f->f_bufptr = f->f_buf;
2159 f->f_bufend = f->f_buf + chunksize;
2160 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002161}
2162
2163/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002164 uninitialized bytes followed by the remainder of the line. Don't be
2165 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002166 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2167
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002168static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002169readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2170{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002171 PyStringObject* s;
2172 char *bufptr;
2173 char *buf;
2174 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002175
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002176 if (f->f_buf == NULL)
2177 if (readahead(f, bufsize) < 0)
2178 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002179
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002180 len = f->f_bufend - f->f_bufptr;
2181 if (len == 0)
2182 return (PyStringObject *)
2183 PyString_FromStringAndSize(NULL, skip);
2184 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
2185 if (bufptr != NULL) {
2186 bufptr++; /* Count the '\n' */
2187 len = bufptr - f->f_bufptr;
2188 s = (PyStringObject *)
2189 PyString_FromStringAndSize(NULL, skip+len);
2190 if (s == NULL)
2191 return NULL;
2192 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2193 f->f_bufptr = bufptr;
2194 if (bufptr == f->f_bufend)
2195 drop_readahead(f);
2196 } else {
2197 bufptr = f->f_bufptr;
2198 buf = f->f_buf;
2199 f->f_buf = NULL; /* Force new readahead buffer */
2200 assert(skip+len < INT_MAX);
2201 s = readahead_get_line_skip(
2202 f, (int)(skip+len), bufsize + (bufsize>>2) );
2203 if (s == NULL) {
2204 PyMem_Free(buf);
2205 return NULL;
2206 }
2207 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2208 PyMem_Free(buf);
2209 }
2210 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002211}
2212
2213/* A larger buffer size may actually decrease performance. */
2214#define READAHEAD_BUFSIZE 8192
2215
2216static PyObject *
2217file_iternext(PyFileObject *f)
2218{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002219 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002220
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002221 if (f->f_fp == NULL)
2222 return err_closed();
2223 if (!f->readable)
2224 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002225
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002226 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2227 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2228 Py_XDECREF(l);
2229 return NULL;
2230 }
2231 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002232}
2233
2234
Tim Peters59c9a642001-09-13 05:38:56 +00002235static PyObject *
2236file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2237{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002238 PyObject *self;
2239 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002241 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002242
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002243 if (not_yet_string == NULL) {
2244 not_yet_string = PyString_InternFromString("<uninitialized file>");
2245 if (not_yet_string == NULL)
2246 return NULL;
2247 }
Tim Peters44410012001-09-14 03:26:08 +00002248
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002249 self = type->tp_alloc(type, 0);
2250 if (self != NULL) {
2251 /* Always fill in the name and mode, so that nobody else
2252 needs to special-case NULLs there. */
2253 Py_INCREF(not_yet_string);
2254 ((PyFileObject *)self)->f_name = not_yet_string;
2255 Py_INCREF(not_yet_string);
2256 ((PyFileObject *)self)->f_mode = not_yet_string;
2257 Py_INCREF(Py_None);
2258 ((PyFileObject *)self)->f_encoding = Py_None;
2259 Py_INCREF(Py_None);
2260 ((PyFileObject *)self)->f_errors = Py_None;
2261 ((PyFileObject *)self)->weakreflist = NULL;
2262 ((PyFileObject *)self)->unlocked_count = 0;
2263 }
2264 return self;
Tim Peters44410012001-09-14 03:26:08 +00002265}
2266
2267static int
2268file_init(PyObject *self, PyObject *args, PyObject *kwds)
2269{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002270 PyFileObject *foself = (PyFileObject *)self;
2271 int ret = 0;
2272 static char *kwlist[] = {"name", "mode", "buffering", 0};
2273 char *name = NULL;
2274 char *mode = "r";
2275 int bufsize = -1;
2276 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002277#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002278 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002279#endif
Tim Peters44410012001-09-14 03:26:08 +00002280
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002281 assert(PyFile_Check(self));
2282 if (foself->f_fp != NULL) {
2283 /* Have to close the existing file first. */
2284 PyObject *closeresult = file_close(foself);
2285 if (closeresult == NULL)
2286 return -1;
2287 Py_DECREF(closeresult);
2288 }
Tim Peters59c9a642001-09-13 05:38:56 +00002289
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002290#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002291 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2292 kwlist, &po, &mode, &bufsize)) {
2293 wideargument = 1;
2294 if (fill_file_fields(foself, NULL, po, mode,
2295 fclose) == NULL)
2296 goto Error;
2297 } else {
2298 /* Drop the argument parsing error as narrow
2299 strings are also valid. */
2300 PyErr_Clear();
2301 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002302#endif
2303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002304 if (!wideargument) {
2305 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002306
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002307 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2308 Py_FileSystemDefaultEncoding,
2309 &name,
2310 &mode, &bufsize))
2311 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 /* We parse again to get the name as a PyObject */
2314 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2315 kwlist, &o_name, &mode,
2316 &bufsize))
2317 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002318
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002319 if (fill_file_fields(foself, NULL, o_name, mode,
2320 fclose) == NULL)
2321 goto Error;
2322 }
2323 if (open_the_file(foself, name, mode) == NULL)
2324 goto Error;
2325 foself->f_setbuf = NULL;
2326 PyFile_SetBufSize(self, bufsize);
2327 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002328
2329Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002330 ret = -1;
2331 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002332Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002333 PyMem_Free(name); /* free the encoded string */
2334 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002335}
2336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002337PyDoc_VAR(file_doc) =
2338PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002339"file(name[, mode[, buffering]]) -> file object\n"
2340"\n"
2341"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2342"writing or appending. The file will be created if it doesn't exist\n"
2343"when opened for writing or appending; it will be truncated when\n"
2344"opened for writing. Add a 'b' to the mode for binary files.\n"
2345"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2346"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002347"buffered, and larger numbers specify the buffer size. The preferred way\n"
2348"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002349)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002350PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002351"Add a 'U' to mode to open the file for input with universal newline\n"
2352"support. Any line ending in the input file will be seen as a '\\n'\n"
2353"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2354"the value for this attribute is one of None (no newline read yet),\n"
2355"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2356"\n"
2357"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002358);
Tim Peters59c9a642001-09-13 05:38:56 +00002359
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002361 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2362 "file",
2363 sizeof(PyFileObject),
2364 0,
2365 (destructor)file_dealloc, /* tp_dealloc */
2366 0, /* tp_print */
2367 0, /* tp_getattr */
2368 0, /* tp_setattr */
2369 0, /* tp_compare */
2370 (reprfunc)file_repr, /* tp_repr */
2371 0, /* tp_as_number */
2372 0, /* tp_as_sequence */
2373 0, /* tp_as_mapping */
2374 0, /* tp_hash */
2375 0, /* tp_call */
2376 0, /* tp_str */
2377 PyObject_GenericGetAttr, /* tp_getattro */
2378 /* softspace is writable: we must supply tp_setattro */
2379 PyObject_GenericSetAttr, /* tp_setattro */
2380 0, /* tp_as_buffer */
2381 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2382 file_doc, /* tp_doc */
2383 0, /* tp_traverse */
2384 0, /* tp_clear */
2385 0, /* tp_richcompare */
2386 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2387 (getiterfunc)file_self, /* tp_iter */
2388 (iternextfunc)file_iternext, /* tp_iternext */
2389 file_methods, /* tp_methods */
2390 file_memberlist, /* tp_members */
2391 file_getsetlist, /* tp_getset */
2392 0, /* tp_base */
2393 0, /* tp_dict */
2394 0, /* tp_descr_get */
2395 0, /* tp_descr_set */
2396 0, /* tp_dictoffset */
2397 file_init, /* tp_init */
2398 PyType_GenericAlloc, /* tp_alloc */
2399 file_new, /* tp_new */
2400 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002401};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002402
2403/* Interface for the 'soft space' between print items. */
2404
2405int
Fred Drakefd99de62000-07-09 05:02:18 +00002406PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002407{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002408 long oldflag = 0;
2409 if (f == NULL) {
2410 /* Do nothing */
2411 }
2412 else if (PyFile_Check(f)) {
2413 oldflag = ((PyFileObject *)f)->f_softspace;
2414 ((PyFileObject *)f)->f_softspace = newflag;
2415 }
2416 else {
2417 PyObject *v;
2418 v = PyObject_GetAttrString(f, "softspace");
2419 if (v == NULL)
2420 PyErr_Clear();
2421 else {
2422 if (PyInt_Check(v))
2423 oldflag = PyInt_AsLong(v);
2424 assert(oldflag < INT_MAX);
2425 Py_DECREF(v);
2426 }
2427 v = PyInt_FromLong((long)newflag);
2428 if (v == NULL)
2429 PyErr_Clear();
2430 else {
2431 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2432 PyErr_Clear();
2433 Py_DECREF(v);
2434 }
2435 }
2436 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002437}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002438
2439/* Interfaces to write objects/strings to file-like objects */
2440
2441int
Fred Drakefd99de62000-07-09 05:02:18 +00002442PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002443{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002444 PyObject *writer, *value, *args, *result;
2445 if (f == NULL) {
2446 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2447 return -1;
2448 }
2449 else if (PyFile_Check(f)) {
2450 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002451#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002452 PyObject *enc = fobj->f_encoding;
2453 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002454#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002455 if (fobj->f_fp == NULL) {
2456 err_closed();
2457 return -1;
2458 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002459#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002460 if ((flags & Py_PRINT_RAW) &&
2461 PyUnicode_Check(v) && enc != Py_None) {
2462 char *cenc = PyString_AS_STRING(enc);
2463 char *errors = fobj->f_errors == Py_None ?
2464 "strict" : PyString_AS_STRING(fobj->f_errors);
2465 value = PyUnicode_AsEncodedString(v, cenc, errors);
2466 if (value == NULL)
2467 return -1;
2468 } else {
2469 value = v;
2470 Py_INCREF(value);
2471 }
2472 result = file_PyObject_Print(value, fobj, flags);
2473 Py_DECREF(value);
2474 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002475#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002476 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002477#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002478 }
2479 writer = PyObject_GetAttrString(f, "write");
2480 if (writer == NULL)
2481 return -1;
2482 if (flags & Py_PRINT_RAW) {
2483 if (PyUnicode_Check(v)) {
2484 value = v;
2485 Py_INCREF(value);
2486 } else
2487 value = PyObject_Str(v);
2488 }
2489 else
2490 value = PyObject_Repr(v);
2491 if (value == NULL) {
2492 Py_DECREF(writer);
2493 return -1;
2494 }
2495 args = PyTuple_Pack(1, value);
2496 if (args == NULL) {
2497 Py_DECREF(value);
2498 Py_DECREF(writer);
2499 return -1;
2500 }
2501 result = PyEval_CallObject(writer, args);
2502 Py_DECREF(args);
2503 Py_DECREF(value);
2504 Py_DECREF(writer);
2505 if (result == NULL)
2506 return -1;
2507 Py_DECREF(result);
2508 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002509}
2510
Guido van Rossum27a60b11997-05-22 22:25:11 +00002511int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002512PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002513{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002514
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002515 if (f == NULL) {
2516 /* Should be caused by a pre-existing error */
2517 if (!PyErr_Occurred())
2518 PyErr_SetString(PyExc_SystemError,
2519 "null file for PyFile_WriteString");
2520 return -1;
2521 }
2522 else if (PyFile_Check(f)) {
2523 PyFileObject *fobj = (PyFileObject *) f;
2524 FILE *fp = PyFile_AsFile(f);
2525 if (fp == NULL) {
2526 err_closed();
2527 return -1;
2528 }
2529 FILE_BEGIN_ALLOW_THREADS(fobj)
2530 fputs(s, fp);
2531 FILE_END_ALLOW_THREADS(fobj)
2532 return 0;
2533 }
2534 else if (!PyErr_Occurred()) {
2535 PyObject *v = PyString_FromString(s);
2536 int err;
2537 if (v == NULL)
2538 return -1;
2539 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2540 Py_DECREF(v);
2541 return err;
2542 }
2543 else
2544 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002545}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002546
2547/* Try to get a file-descriptor from a Python object. If the object
2548 is an integer or long integer, its value is returned. If not, the
2549 object's fileno() method is called if it exists; the method must return
2550 an integer or long integer, which is returned as the file descriptor value.
2551 -1 is returned on failure.
2552*/
2553
2554int PyObject_AsFileDescriptor(PyObject *o)
2555{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002556 int fd;
2557 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002559 if (PyInt_Check(o)) {
2560 fd = PyInt_AsLong(o);
2561 }
2562 else if (PyLong_Check(o)) {
2563 fd = PyLong_AsLong(o);
2564 }
2565 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2566 {
2567 PyObject *fno = PyEval_CallObject(meth, NULL);
2568 Py_DECREF(meth);
2569 if (fno == NULL)
2570 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002571
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002572 if (PyInt_Check(fno)) {
2573 fd = PyInt_AsLong(fno);
2574 Py_DECREF(fno);
2575 }
2576 else if (PyLong_Check(fno)) {
2577 fd = PyLong_AsLong(fno);
2578 Py_DECREF(fno);
2579 }
2580 else {
2581 PyErr_SetString(PyExc_TypeError,
2582 "fileno() returned a non-integer");
2583 Py_DECREF(fno);
2584 return -1;
2585 }
2586 }
2587 else {
2588 PyErr_SetString(PyExc_TypeError,
2589 "argument must be an int, or have a fileno() method.");
2590 return -1;
2591 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002592
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002593 if (fd < 0) {
2594 PyErr_Format(PyExc_ValueError,
2595 "file descriptor cannot be a negative integer (%i)",
2596 fd);
2597 return -1;
2598 }
2599 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002600}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002601
Jack Jansen7b8c7542002-04-14 20:12:41 +00002602/* From here on we need access to the real fgets and fread */
2603#undef fgets
2604#undef fread
2605
2606/*
2607** Py_UniversalNewlineFgets is an fgets variation that understands
2608** all of \r, \n and \r\n conventions.
2609** The stream should be opened in binary mode.
2610** If fobj is NULL the routine always does newline conversion, and
2611** it may peek one char ahead to gobble the second char in \r\n.
2612** If fobj is non-NULL it must be a PyFileObject. In this case there
2613** is no readahead but in stead a flag is used to skip a following
2614** \n on the next read. Also, if the file is open in binary mode
2615** the whole conversion is skipped. Finally, the routine keeps track of
2616** the different types of newlines seen.
2617** Note that we need no error handling: fgets() treats error and eof
2618** identically.
2619*/
2620char *
2621Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2622{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002623 char *p = buf;
2624 int c;
2625 int newlinetypes = 0;
2626 int skipnextlf = 0;
2627 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002628
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002629 if (fobj) {
2630 if (!PyFile_Check(fobj)) {
2631 errno = ENXIO; /* What can you do... */
2632 return NULL;
2633 }
2634 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2635 if ( !univ_newline )
2636 return fgets(buf, n, stream);
2637 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2638 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2639 }
2640 FLOCKFILE(stream);
2641 c = 'x'; /* Shut up gcc warning */
2642 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2643 if (skipnextlf ) {
2644 skipnextlf = 0;
2645 if (c == '\n') {
2646 /* Seeing a \n here with skipnextlf true
2647 ** means we saw a \r before.
2648 */
2649 newlinetypes |= NEWLINE_CRLF;
2650 c = GETC(stream);
2651 if (c == EOF) break;
2652 } else {
2653 /*
2654 ** Note that c == EOF also brings us here,
2655 ** so we're okay if the last char in the file
2656 ** is a CR.
2657 */
2658 newlinetypes |= NEWLINE_CR;
2659 }
2660 }
2661 if (c == '\r') {
2662 /* A \r is translated into a \n, and we skip
2663 ** an adjacent \n, if any. We don't set the
2664 ** newlinetypes flag until we've seen the next char.
2665 */
2666 skipnextlf = 1;
2667 c = '\n';
2668 } else if ( c == '\n') {
2669 newlinetypes |= NEWLINE_LF;
2670 }
2671 *p++ = c;
2672 if (c == '\n') break;
2673 }
2674 if ( c == EOF && skipnextlf )
2675 newlinetypes |= NEWLINE_CR;
2676 FUNLOCKFILE(stream);
2677 *p = '\0';
2678 if (fobj) {
2679 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2680 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2681 } else if ( skipnextlf ) {
2682 /* If we have no file object we cannot save the
2683 ** skipnextlf flag. We have to readahead, which
2684 ** will cause a pause if we're reading from an
2685 ** interactive stream, but that is very unlikely
2686 ** unless we're doing something silly like
2687 ** execfile("/dev/tty").
2688 */
2689 c = GETC(stream);
2690 if ( c != '\n' )
2691 ungetc(c, stream);
2692 }
2693 if (p == buf)
2694 return NULL;
2695 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002696}
2697
2698/*
2699** Py_UniversalNewlineFread is an fread variation that understands
2700** all of \r, \n and \r\n conventions.
2701** The stream should be opened in binary mode.
2702** fobj must be a PyFileObject. In this case there
2703** is no readahead but in stead a flag is used to skip a following
2704** \n on the next read. Also, if the file is open in binary mode
2705** the whole conversion is skipped. Finally, the routine keeps track of
2706** the different types of newlines seen.
2707*/
2708size_t
Tim Peters058b1412002-04-21 07:29:14 +00002709Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002710 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002711{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002712 char *dst = buf;
2713 PyFileObject *f = (PyFileObject *)fobj;
2714 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002715
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002716 assert(buf != NULL);
2717 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002718
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002719 if (!fobj || !PyFile_Check(fobj)) {
2720 errno = ENXIO; /* What can you do... */
2721 return 0;
2722 }
2723 if (!f->f_univ_newline)
2724 return fread(buf, 1, n, stream);
2725 newlinetypes = f->f_newlinetypes;
2726 skipnextlf = f->f_skipnextlf;
2727 /* Invariant: n is the number of bytes remaining to be filled
2728 * in the buffer.
2729 */
2730 while (n) {
2731 size_t nread;
2732 int shortread;
2733 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002734
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002735 nread = fread(dst, 1, n, stream);
2736 assert(nread <= n);
2737 if (nread == 0)
2738 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002740 n -= nread; /* assuming 1 byte out for each in; will adjust */
2741 shortread = n != 0; /* true iff EOF or error */
2742 while (nread--) {
2743 char c = *src++;
2744 if (c == '\r') {
2745 /* Save as LF and set flag to skip next LF. */
2746 *dst++ = '\n';
2747 skipnextlf = 1;
2748 }
2749 else if (skipnextlf && c == '\n') {
2750 /* Skip LF, and remember we saw CR LF. */
2751 skipnextlf = 0;
2752 newlinetypes |= NEWLINE_CRLF;
2753 ++n;
2754 }
2755 else {
2756 /* Normal char to be stored in buffer. Also
2757 * update the newlinetypes flag if either this
2758 * is an LF or the previous char was a CR.
2759 */
2760 if (c == '\n')
2761 newlinetypes |= NEWLINE_LF;
2762 else if (skipnextlf)
2763 newlinetypes |= NEWLINE_CR;
2764 *dst++ = c;
2765 skipnextlf = 0;
2766 }
2767 }
2768 if (shortread) {
2769 /* If this is EOF, update type flags. */
2770 if (skipnextlf && feof(stream))
2771 newlinetypes |= NEWLINE_CR;
2772 break;
2773 }
2774 }
2775 f->f_newlinetypes = newlinetypes;
2776 f->f_skipnextlf = skipnextlf;
2777 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002778}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002779
2780#ifdef __cplusplus
2781}
2782#endif