blob: 6b95a0c212d10ce72ec350eff349220044d82496 [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);
652 PyMem_Free(f->f_setbuf);
653 f->f_setbuf = NULL;
654 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655}
656
Trent Mickf29f47b2000-08-11 19:02:59 +0000657
Guido van Rossumb8552162001-09-05 14:58:11 +0000658/* Our very own off_t-like type, 64-bit if possible */
659#if !defined(HAVE_LARGEFILE_SUPPORT)
660typedef off_t Py_off_t;
661#elif SIZEOF_OFF_T >= 8
662typedef off_t Py_off_t;
663#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000664typedef fpos_t Py_off_t;
665#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000666#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000667#endif
668
669
Trent Mickf29f47b2000-08-11 19:02:59 +0000670/* a portable fseek() function
671 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000672static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000673_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000674{
Guido van Rossumb8552162001-09-05 14:58:11 +0000675#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000676 return fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000677#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000678 return fseeko(fp, offset, whence);
Trent Mickf29f47b2000-08-11 19:02:59 +0000679#elif defined(HAVE_FSEEK64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000680 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000681#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000682 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000683#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
685 and fgetpos() to implement fseek()*/
686 fpos_t pos;
687 switch (whence) {
688 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000689#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 fflush(fp);
691 if (_lseeki64(fileno(fp), 0, 2) == -1)
692 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000693#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000694 if (fseek(fp, 0, SEEK_END) != 0)
695 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000696#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000697 /* fall through */
698 case SEEK_CUR:
699 if (fgetpos(fp, &pos) != 0)
700 return -1;
701 offset += pos;
702 break;
703 /* case SEEK_SET: break; */
704 }
705 return fsetpos(fp, &offset);
Trent Mickf29f47b2000-08-11 19:02:59 +0000706#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000707#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000708#endif
709}
710
711
712/* a portable ftell() function
713 Return -1 on failure with errno set appropriately, current file
714 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000715static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000716_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000717{
Guido van Rossumb8552162001-09-05 14:58:11 +0000718#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000719 return ftell(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000720#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000721 return ftello(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000722#elif defined(HAVE_FTELL64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000723 return ftell64(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000724#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000725 fpos_t pos;
726 if (fgetpos(fp, &pos) != 0)
727 return -1;
728 return pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000729#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000730#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000731#endif
732}
733
734
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000736file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000738 int whence;
739 int ret;
740 Py_off_t offset;
741 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000742
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 if (f->f_fp == NULL)
744 return err_closed();
745 drop_readahead(f);
746 whence = 0;
747 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
748 return NULL;
749 off_index = PyNumber_Index(offobj);
750 if (!off_index) {
751 if (!PyFloat_Check(offobj))
752 return NULL;
753 /* Deprecated in 2.6 */
754 PyErr_Clear();
755 if (PyErr_WarnEx(PyExc_DeprecationWarning,
756 "integer argument expected, got float",
757 1) < 0)
758 return NULL;
759 off_index = offobj;
760 Py_INCREF(offobj);
761 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000762#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000763 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000764#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000765 offset = PyLong_Check(off_index) ?
766 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000767#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000768 Py_DECREF(off_index);
769 if (PyErr_Occurred())
770 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000771
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000772 FILE_BEGIN_ALLOW_THREADS(f)
773 errno = 0;
774 ret = _portable_fseek(f->f_fp, offset, whence);
775 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000776
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000777 if (ret != 0) {
778 PyErr_SetFromErrno(PyExc_IOError);
779 clearerr(f->f_fp);
780 return NULL;
781 }
782 f->f_skipnextlf = 0;
783 Py_INCREF(Py_None);
784 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000785}
786
Trent Mickf29f47b2000-08-11 19:02:59 +0000787
Guido van Rossumd7047b31995-01-02 19:07:15 +0000788#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000790file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000791{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 Py_off_t newsize;
793 PyObject *newsizeobj = NULL;
794 Py_off_t initialpos;
795 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000796
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 if (f->f_fp == NULL)
798 return err_closed();
799 if (!f->writable)
800 return err_mode("writing");
801 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
802 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000803
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 /* Get current file position. If the file happens to be open for
805 * update and the last operation was an input operation, C doesn't
806 * define what the later fflush() will do, but we promise truncate()
807 * won't change the current position (and fflush() *does* change it
808 * then at least on Windows). The easiest thing is to capture
809 * current pos now and seek back to it at the end.
810 */
811 FILE_BEGIN_ALLOW_THREADS(f)
812 errno = 0;
813 initialpos = _portable_ftell(f->f_fp);
814 FILE_END_ALLOW_THREADS(f)
815 if (initialpos == -1)
816 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000817
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000818 /* Set newsize to current postion if newsizeobj NULL, else to the
819 * specified value.
820 */
821 if (newsizeobj != NULL) {
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000822#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 newsize = PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000824#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000825 newsize = PyLong_Check(newsizeobj) ?
826 PyLong_AsLongLong(newsizeobj) :
827 PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000828#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000829 if (PyErr_Occurred())
830 return NULL;
831 }
832 else /* default to current position */
833 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000834
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000835 /* Flush the stream. We're mixing stream-level I/O with lower-level
836 * I/O, and a flush may be necessary to synch both platform views
837 * of the current file state.
838 */
839 FILE_BEGIN_ALLOW_THREADS(f)
840 errno = 0;
841 ret = fflush(f->f_fp);
842 FILE_END_ALLOW_THREADS(f)
843 if (ret != 0)
844 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000845
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000846#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000847 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
848 so don't even try using it. */
849 {
850 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000851
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000852 /* Have to move current pos to desired endpoint on Windows. */
853 FILE_BEGIN_ALLOW_THREADS(f)
854 errno = 0;
855 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
856 FILE_END_ALLOW_THREADS(f)
857 if (ret)
858 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000859
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000860 /* Truncate. Note that this may grow the file! */
861 FILE_BEGIN_ALLOW_THREADS(f)
862 errno = 0;
863 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
864 ret = hFile == (HANDLE)-1;
865 if (ret == 0) {
866 ret = SetEndOfFile(hFile) == 0;
867 if (ret)
868 errno = EACCES;
869 }
870 FILE_END_ALLOW_THREADS(f)
871 if (ret)
872 goto onioerror;
873 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000874#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000875 FILE_BEGIN_ALLOW_THREADS(f)
876 errno = 0;
877 ret = ftruncate(fileno(f->f_fp), newsize);
878 FILE_END_ALLOW_THREADS(f)
879 if (ret != 0)
880 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000881#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000882
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000883 /* Restore original file position. */
884 FILE_BEGIN_ALLOW_THREADS(f)
885 errno = 0;
886 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
887 FILE_END_ALLOW_THREADS(f)
888 if (ret)
889 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000890
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000891 Py_INCREF(Py_None);
892 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000893
894onioerror:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000895 PyErr_SetFromErrno(PyExc_IOError);
896 clearerr(f->f_fp);
897 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000898}
899#endif /* HAVE_FTRUNCATE */
900
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000901static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000902file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000903{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000904 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000905
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 if (f->f_fp == NULL)
907 return err_closed();
908 FILE_BEGIN_ALLOW_THREADS(f)
909 errno = 0;
910 pos = _portable_ftell(f->f_fp);
911 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000912
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 if (pos == -1) {
914 PyErr_SetFromErrno(PyExc_IOError);
915 clearerr(f->f_fp);
916 return NULL;
917 }
918 if (f->f_skipnextlf) {
919 int c;
920 c = GETC(f->f_fp);
921 if (c == '\n') {
922 f->f_newlinetypes |= NEWLINE_CRLF;
923 pos++;
924 f->f_skipnextlf = 0;
925 } else if (c != EOF) ungetc(c, f->f_fp);
926 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000927#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000929#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000930 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000931#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000932}
933
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000934static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000935file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 if (f->f_fp == NULL)
938 return err_closed();
939 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000940}
941
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000942static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000943file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000944{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000945 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000946
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000947 if (f->f_fp == NULL)
948 return err_closed();
949 FILE_BEGIN_ALLOW_THREADS(f)
950 errno = 0;
951 res = fflush(f->f_fp);
952 FILE_END_ALLOW_THREADS(f)
953 if (res != 0) {
954 PyErr_SetFromErrno(PyExc_IOError);
955 clearerr(f->f_fp);
956 return NULL;
957 }
958 Py_INCREF(Py_None);
959 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000960}
961
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000962static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000963file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000964{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000965 long res;
966 if (f->f_fp == NULL)
967 return err_closed();
968 FILE_BEGIN_ALLOW_THREADS(f)
969 res = isatty((int)fileno(f->f_fp));
970 FILE_END_ALLOW_THREADS(f)
971 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000972}
973
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000974
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000975#if BUFSIZ < 8192
976#define SMALLCHUNK 8192
977#else
978#define SMALLCHUNK BUFSIZ
979#endif
980
Guido van Rossum3c259041999-01-14 19:00:14 +0000981#if SIZEOF_INT < 4
982#define BIGCHUNK (512 * 32)
983#else
984#define BIGCHUNK (512 * 1024)
985#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000986
987static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000988new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000989{
990#ifdef HAVE_FSTAT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000991 off_t pos, end;
992 struct stat st;
993 if (fstat(fileno(f->f_fp), &st) == 0) {
994 end = st.st_size;
995 /* The following is not a bug: we really need to call lseek()
996 *and* ftell(). The reason is that some stdio libraries
997 mistakenly flush their buffer when ftell() is called and
998 the lseek() call it makes fails, thereby throwing away
999 data that cannot be recovered in any way. To avoid this,
1000 we first test lseek(), and only call ftell() if lseek()
1001 works. We can't use the lseek() value either, because we
1002 need to take the amount of buffered data into account.
1003 (Yet another reason why stdio stinks. :-) */
1004 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
1005 if (pos >= 0) {
1006 pos = ftell(f->f_fp);
1007 }
1008 if (pos < 0)
1009 clearerr(f->f_fp);
1010 if (end > pos && pos >= 0)
1011 return currentsize + end - pos + 1;
1012 /* Add 1 so if the file were to grow we'd notice. */
1013 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001014#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 if (currentsize > SMALLCHUNK) {
1016 /* Keep doubling until we reach BIGCHUNK;
1017 then keep adding BIGCHUNK. */
1018 if (currentsize <= BIGCHUNK)
1019 return currentsize + currentsize;
1020 else
1021 return currentsize + BIGCHUNK;
1022 }
1023 return currentsize + SMALLCHUNK;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001024}
1025
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001026#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1027#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1028#else
1029#ifdef EWOULDBLOCK
1030#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1031#else
1032#ifdef EAGAIN
1033#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1034#else
1035#define BLOCKED_ERRNO(x) 0
1036#endif
1037#endif
1038#endif
1039
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001040static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001041file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001042{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001043 long bytesrequested = -1;
1044 size_t bytesread, buffersize, chunksize;
1045 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001046
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001047 if (f->f_fp == NULL)
1048 return err_closed();
1049 if (!f->readable)
1050 return err_mode("reading");
1051 /* refuse to mix with f.next() */
1052 if (f->f_buf != NULL &&
1053 (f->f_bufend - f->f_bufptr) > 0 &&
1054 f->f_buf[0] != '\0')
1055 return err_iterbuffered();
1056 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
1057 return NULL;
1058 if (bytesrequested < 0)
1059 buffersize = new_buffersize(f, (size_t)0);
1060 else
1061 buffersize = bytesrequested;
1062 if (buffersize > PY_SSIZE_T_MAX) {
1063 PyErr_SetString(PyExc_OverflowError,
1064 "requested number of bytes is more than a Python string can hold");
1065 return NULL;
1066 }
1067 v = PyString_FromStringAndSize((char *)NULL, buffersize);
1068 if (v == NULL)
1069 return NULL;
1070 bytesread = 0;
1071 for (;;) {
1072 FILE_BEGIN_ALLOW_THREADS(f)
1073 errno = 0;
1074 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
1075 buffersize - bytesread, f->f_fp, (PyObject *)f);
1076 FILE_END_ALLOW_THREADS(f)
1077 if (chunksize == 0) {
1078 if (!ferror(f->f_fp))
1079 break;
1080 clearerr(f->f_fp);
1081 /* When in non-blocking mode, data shouldn't
1082 * be discarded if a blocking signal was
1083 * received. That will also happen if
1084 * chunksize != 0, but bytesread < buffersize. */
1085 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1086 break;
1087 PyErr_SetFromErrno(PyExc_IOError);
1088 Py_DECREF(v);
1089 return NULL;
1090 }
1091 bytesread += chunksize;
1092 if (bytesread < buffersize) {
1093 clearerr(f->f_fp);
1094 break;
1095 }
1096 if (bytesrequested < 0) {
1097 buffersize = new_buffersize(f, buffersize);
1098 if (_PyString_Resize(&v, buffersize) < 0)
1099 return NULL;
1100 } else {
1101 /* Got what was requested. */
1102 break;
1103 }
1104 }
1105 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1106 return NULL;
1107 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001108}
1109
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001110static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001111file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001112{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001113 char *ptr;
1114 Py_ssize_t ntodo;
1115 Py_ssize_t ndone, nnow;
1116 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001118 if (f->f_fp == NULL)
1119 return err_closed();
1120 if (!f->readable)
1121 return err_mode("reading");
1122 /* refuse to mix with f.next() */
1123 if (f->f_buf != NULL &&
1124 (f->f_bufend - f->f_bufptr) > 0 &&
1125 f->f_buf[0] != '\0')
1126 return err_iterbuffered();
1127 if (!PyArg_ParseTuple(args, "w*", &pbuf))
1128 return NULL;
1129 ptr = pbuf.buf;
1130 ntodo = pbuf.len;
1131 ndone = 0;
1132 while (ntodo > 0) {
1133 FILE_BEGIN_ALLOW_THREADS(f)
1134 errno = 0;
1135 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
1136 (PyObject *)f);
1137 FILE_END_ALLOW_THREADS(f)
1138 if (nnow == 0) {
1139 if (!ferror(f->f_fp))
1140 break;
1141 PyErr_SetFromErrno(PyExc_IOError);
1142 clearerr(f->f_fp);
1143 PyBuffer_Release(&pbuf);
1144 return NULL;
1145 }
1146 ndone += nnow;
1147 ntodo -= nnow;
1148 }
1149 PyBuffer_Release(&pbuf);
1150 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001151}
1152
Tim Peters86821b22001-01-07 21:19:34 +00001153/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001154Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001155
1156Under MSVC 6:
1157
Tim Peters1c733232001-01-08 04:02:07 +00001158+ MS threadsafe getc is very slow (multiple layers of function calls before+
1159 after each character, to lock+unlock the stream).
1160+ The stream-locking functions are MS-internal -- can't access them from user
1161 code.
1162+ There's nothing Tim could find in the MS C or platform SDK libraries that
1163 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001164+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1165
1166So we use fgets for speed(!), despite that it's painful.
1167
1168MS realloc is also slow.
1169
Tim Petersf29b64d2001-01-15 06:33:19 +00001170Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1171have):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001172 Linux a wash
1173 Solaris a wash
1174 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001175
Tim Petersf29b64d2001-01-15 06:33:19 +00001176CAUTION: The C std isn't clear about this: in those cases where fgets
1177writes something into the buffer, can it write into any position beyond the
1178required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1179known on which it does; and it would be a strange way to code fgets. Still,
1180getline_via_fgets may not work correctly if it does. The std test
1181test_bufio.py should fail if platform fgets() routinely writes beyond the
1182trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001183**************************************************************************/
1184
Tim Petersf29b64d2001-01-15 06:33:19 +00001185/* Use this routine if told to, or by default on non-get_unlocked()
1186 * platforms unless told not to. Yikes! Let's spell that out:
1187 * On a platform with getc_unlocked():
1188 * By default, use getc_unlocked().
1189 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1190 * On a platform without getc_unlocked():
1191 * By default, use fgets().
1192 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1193 */
1194#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1195#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001196#endif
1197
Tim Petersf29b64d2001-01-15 06:33:19 +00001198#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1199#undef USE_FGETS_IN_GETLINE
1200#endif
1201
1202#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001203static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001204getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001205{
Tim Peters15b83852001-01-08 00:53:12 +00001206/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001207 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1208 * to fill this much of the buffer with a known value in order to figure out
1209 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1210 * than "most" lines, we waste time filling unused buffer slots. 100 is
1211 * surely adequate for most peoples' email archives, chewing over source code,
1212 * etc -- "regular old text files".
1213 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1214 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1215 * cautions about boosting that. 300 was chosen because the worst real-life
1216 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1217 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001218 */
Tim Peters142297a2001-01-15 10:36:56 +00001219#define INITBUFSIZE 100
1220#define MAXBUFSIZE 300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001221 char* p; /* temp */
1222 char buf[MAXBUFSIZE];
1223 PyObject* v; /* the string object result */
1224 char* pvfree; /* address of next free slot */
1225 char* pvend; /* address one beyond last free slot */
1226 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1227 size_t total_v_size; /* total # of slots in buffer */
1228 size_t increment; /* amount to increment the buffer */
1229 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001230
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001231 /* Optimize for normal case: avoid _PyString_Resize if at all
1232 * possible via first reading into stack buffer "buf".
1233 */
1234 total_v_size = INITBUFSIZE; /* start small and pray */
1235 pvfree = buf;
1236 for (;;) {
1237 FILE_BEGIN_ALLOW_THREADS(f)
1238 pvend = buf + total_v_size;
1239 nfree = pvend - pvfree;
1240 memset(pvfree, '\n', nfree);
1241 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1242 p = fgets(pvfree, (int)nfree, fp);
1243 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001244
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001245 if (p == NULL) {
1246 clearerr(fp);
1247 if (PyErr_CheckSignals())
1248 return NULL;
1249 v = PyString_FromStringAndSize(buf, pvfree - buf);
1250 return v;
1251 }
1252 /* fgets read *something* */
1253 p = memchr(pvfree, '\n', nfree);
1254 if (p != NULL) {
1255 /* Did the \n come from fgets or from us?
1256 * Since fgets stops at the first \n, and then writes
1257 * \0, if it's from fgets a \0 must be next. But if
1258 * that's so, it could not have come from us, since
1259 * the \n's we filled the buffer with have only more
1260 * \n's to the right.
1261 */
1262 if (p+1 < pvend && *(p+1) == '\0') {
1263 /* It's from fgets: we win! In particular,
1264 * we haven't done any mallocs yet, and can
1265 * build the final result on the first try.
1266 */
1267 ++p; /* include \n from fgets */
1268 }
1269 else {
1270 /* Must be from us: fgets didn't fill the
1271 * buffer and didn't find a newline, so it
1272 * must be the last and newline-free line of
1273 * the file.
1274 */
1275 assert(p > pvfree && *(p-1) == '\0');
1276 --p; /* don't include \0 from fgets */
1277 }
1278 v = PyString_FromStringAndSize(buf, p - buf);
1279 return v;
1280 }
1281 /* yuck: fgets overwrote all the newlines, i.e. the entire
1282 * buffer. So this line isn't over yet, or maybe it is but
1283 * we're exactly at EOF. If we haven't already, try using the
1284 * rest of the stack buffer.
1285 */
1286 assert(*(pvend-1) == '\0');
1287 if (pvfree == buf) {
1288 pvfree = pvend - 1; /* overwrite trailing null */
1289 total_v_size = MAXBUFSIZE;
1290 }
1291 else
1292 break;
1293 }
Tim Peters142297a2001-01-15 10:36:56 +00001294
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001295 /* The stack buffer isn't big enough; malloc a string object and read
1296 * into its buffer.
1297 */
1298 total_v_size = MAXBUFSIZE << 1;
1299 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
1300 if (v == NULL)
1301 return v;
1302 /* copy over everything except the last null byte */
1303 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1304 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001305
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001306 /* Keep reading stuff into v; if it ever ends successfully, break
1307 * after setting p one beyond the end of the line. The code here is
1308 * very much like the code above, except reads into v's buffer; see
1309 * the code above for detailed comments about the logic.
1310 */
1311 for (;;) {
1312 FILE_BEGIN_ALLOW_THREADS(f)
1313 pvend = BUF(v) + total_v_size;
1314 nfree = pvend - pvfree;
1315 memset(pvfree, '\n', nfree);
1316 assert(nfree < INT_MAX);
1317 p = fgets(pvfree, (int)nfree, fp);
1318 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001319
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001320 if (p == NULL) {
1321 clearerr(fp);
1322 if (PyErr_CheckSignals()) {
1323 Py_DECREF(v);
1324 return NULL;
1325 }
1326 p = pvfree;
1327 break;
1328 }
1329 p = memchr(pvfree, '\n', nfree);
1330 if (p != NULL) {
1331 if (p+1 < pvend && *(p+1) == '\0') {
1332 /* \n came from fgets */
1333 ++p;
1334 break;
1335 }
1336 /* \n came from us; last line of file, no newline */
1337 assert(p > pvfree && *(p-1) == '\0');
1338 --p;
1339 break;
1340 }
1341 /* expand buffer and try again */
1342 assert(*(pvend-1) == '\0');
1343 increment = total_v_size >> 2; /* mild exponential growth */
1344 prev_v_size = total_v_size;
1345 total_v_size += increment;
1346 /* check for overflow */
1347 if (total_v_size <= prev_v_size ||
1348 total_v_size > PY_SSIZE_T_MAX) {
1349 PyErr_SetString(PyExc_OverflowError,
1350 "line is longer than a Python string can hold");
1351 Py_DECREF(v);
1352 return NULL;
1353 }
1354 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1355 return NULL;
1356 /* overwrite the trailing null byte */
1357 pvfree = BUF(v) + (prev_v_size - 1);
1358 }
1359 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1360 return NULL;
1361 return v;
Tim Peters86821b22001-01-07 21:19:34 +00001362#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001363#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001364}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001365#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001366
Guido van Rossum0bd24411991-04-04 15:21:57 +00001367/* Internal routine to get a line.
1368 Size argument interpretation:
1369 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001370 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001371*/
1372
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001374get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001375{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001376 FILE *fp = f->f_fp;
1377 int c;
1378 char *buf, *end;
1379 size_t total_v_size; /* total # of slots in buffer */
1380 size_t used_v_size; /* # used slots in buffer */
1381 size_t increment; /* amount to increment the buffer */
1382 PyObject *v;
1383 int newlinetypes = f->f_newlinetypes;
1384 int skipnextlf = f->f_skipnextlf;
1385 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001386
Jack Jansen7b8c7542002-04-14 20:12:41 +00001387#if defined(USE_FGETS_IN_GETLINE)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001388 if (n <= 0 && !univ_newline )
1389 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001390#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001391 total_v_size = n > 0 ? n : 100;
1392 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
1393 if (v == NULL)
1394 return NULL;
1395 buf = BUF(v);
1396 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001397
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001398 for (;;) {
1399 FILE_BEGIN_ALLOW_THREADS(f)
1400 FLOCKFILE(fp);
1401 if (univ_newline) {
1402 c = 'x'; /* Shut up gcc warning */
1403 while ( buf != end && (c = GETC(fp)) != EOF ) {
1404 if (skipnextlf ) {
1405 skipnextlf = 0;
1406 if (c == '\n') {
1407 /* Seeing a \n here with
1408 * skipnextlf true means we
1409 * saw a \r before.
1410 */
1411 newlinetypes |= NEWLINE_CRLF;
1412 c = GETC(fp);
1413 if (c == EOF) break;
1414 } else {
1415 newlinetypes |= NEWLINE_CR;
1416 }
1417 }
1418 if (c == '\r') {
1419 skipnextlf = 1;
1420 c = '\n';
1421 } else if ( c == '\n')
1422 newlinetypes |= NEWLINE_LF;
1423 *buf++ = c;
1424 if (c == '\n') break;
1425 }
1426 if ( c == EOF && skipnextlf )
1427 newlinetypes |= NEWLINE_CR;
1428 } else /* If not universal newlines use the normal loop */
1429 while ((c = GETC(fp)) != EOF &&
1430 (*buf++ = c) != '\n' &&
1431 buf != end)
1432 ;
1433 FUNLOCKFILE(fp);
1434 FILE_END_ALLOW_THREADS(f)
1435 f->f_newlinetypes = newlinetypes;
1436 f->f_skipnextlf = skipnextlf;
1437 if (c == '\n')
1438 break;
1439 if (c == EOF) {
1440 if (ferror(fp)) {
1441 PyErr_SetFromErrno(PyExc_IOError);
1442 clearerr(fp);
1443 Py_DECREF(v);
1444 return NULL;
1445 }
1446 clearerr(fp);
1447 if (PyErr_CheckSignals()) {
1448 Py_DECREF(v);
1449 return NULL;
1450 }
1451 break;
1452 }
1453 /* Must be because buf == end */
1454 if (n > 0)
1455 break;
1456 used_v_size = total_v_size;
1457 increment = total_v_size >> 2; /* mild exponential growth */
1458 total_v_size += increment;
1459 if (total_v_size > PY_SSIZE_T_MAX) {
1460 PyErr_SetString(PyExc_OverflowError,
1461 "line is longer than a Python string can hold");
1462 Py_DECREF(v);
1463 return NULL;
1464 }
1465 if (_PyString_Resize(&v, total_v_size) < 0)
1466 return NULL;
1467 buf = BUF(v) + used_v_size;
1468 end = BUF(v) + total_v_size;
1469 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001471 used_v_size = buf - BUF(v);
1472 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1473 return NULL;
1474 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001475}
1476
Guido van Rossum0bd24411991-04-04 15:21:57 +00001477/* External C interface */
1478
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001479PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001480PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001481{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001482 PyObject *result;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001483
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001484 if (f == NULL) {
1485 PyErr_BadInternalCall();
1486 return NULL;
1487 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001488
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001489 if (PyFile_Check(f)) {
1490 PyFileObject *fo = (PyFileObject *)f;
1491 if (fo->f_fp == NULL)
1492 return err_closed();
1493 if (!fo->readable)
1494 return err_mode("reading");
1495 /* refuse to mix with f.next() */
1496 if (fo->f_buf != NULL &&
1497 (fo->f_bufend - fo->f_bufptr) > 0 &&
1498 fo->f_buf[0] != '\0')
1499 return err_iterbuffered();
1500 result = get_line(fo, n);
1501 }
1502 else {
1503 PyObject *reader;
1504 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 reader = PyObject_GetAttrString(f, "readline");
1507 if (reader == NULL)
1508 return NULL;
1509 if (n <= 0)
1510 args = PyTuple_New(0);
1511 else
1512 args = Py_BuildValue("(i)", n);
1513 if (args == NULL) {
1514 Py_DECREF(reader);
1515 return NULL;
1516 }
1517 result = PyEval_CallObject(reader, args);
1518 Py_DECREF(reader);
1519 Py_DECREF(args);
1520 if (result != NULL && !PyString_Check(result) &&
1521 !PyUnicode_Check(result)) {
1522 Py_DECREF(result);
1523 result = NULL;
1524 PyErr_SetString(PyExc_TypeError,
1525 "object.readline() returned non-string");
1526 }
1527 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001529 if (n < 0 && result != NULL && PyString_Check(result)) {
1530 char *s = PyString_AS_STRING(result);
1531 Py_ssize_t len = PyString_GET_SIZE(result);
1532 if (len == 0) {
1533 Py_DECREF(result);
1534 result = NULL;
1535 PyErr_SetString(PyExc_EOFError,
1536 "EOF when reading a line");
1537 }
1538 else if (s[len-1] == '\n') {
1539 if (result->ob_refcnt == 1) {
1540 if (_PyString_Resize(&result, len-1))
1541 return NULL;
1542 }
1543 else {
1544 PyObject *v;
1545 v = PyString_FromStringAndSize(s, len-1);
1546 Py_DECREF(result);
1547 result = v;
1548 }
1549 }
1550 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001551#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001552 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1553 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1554 Py_ssize_t len = PyUnicode_GET_SIZE(result);
1555 if (len == 0) {
1556 Py_DECREF(result);
1557 result = NULL;
1558 PyErr_SetString(PyExc_EOFError,
1559 "EOF when reading a line");
1560 }
1561 else if (s[len-1] == '\n') {
1562 if (result->ob_refcnt == 1)
1563 PyUnicode_Resize(&result, len-1);
1564 else {
1565 PyObject *v;
1566 v = PyUnicode_FromUnicode(s, len-1);
1567 Py_DECREF(result);
1568 result = v;
1569 }
1570 }
1571 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001572#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001573 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001574}
1575
1576/* Python method */
1577
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001578static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001579file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001580{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001581 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001583 if (f->f_fp == NULL)
1584 return err_closed();
1585 if (!f->readable)
1586 return err_mode("reading");
1587 /* refuse to mix with f.next() */
1588 if (f->f_buf != NULL &&
1589 (f->f_bufend - f->f_bufptr) > 0 &&
1590 f->f_buf[0] != '\0')
1591 return err_iterbuffered();
1592 if (!PyArg_ParseTuple(args, "|i:readline", &n))
1593 return NULL;
1594 if (n == 0)
1595 return PyString_FromString("");
1596 if (n < 0)
1597 n = 0;
1598 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001599}
1600
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001601static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001602file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001603{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001604 long sizehint = 0;
1605 PyObject *list = NULL;
1606 PyObject *line;
1607 char small_buffer[SMALLCHUNK];
1608 char *buffer = small_buffer;
1609 size_t buffersize = SMALLCHUNK;
1610 PyObject *big_buffer = NULL;
1611 size_t nfilled = 0;
1612 size_t nread;
1613 size_t totalread = 0;
1614 char *p, *q, *end;
1615 int err;
1616 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001617
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001618 if (f->f_fp == NULL)
1619 return err_closed();
1620 if (!f->readable)
1621 return err_mode("reading");
1622 /* refuse to mix with f.next() */
1623 if (f->f_buf != NULL &&
1624 (f->f_bufend - f->f_bufptr) > 0 &&
1625 f->f_buf[0] != '\0')
1626 return err_iterbuffered();
1627 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
1628 return NULL;
1629 if ((list = PyList_New(0)) == NULL)
1630 return NULL;
1631 for (;;) {
1632 if (shortread)
1633 nread = 0;
1634 else {
1635 FILE_BEGIN_ALLOW_THREADS(f)
1636 errno = 0;
1637 nread = Py_UniversalNewlineFread(buffer+nfilled,
1638 buffersize-nfilled, f->f_fp, (PyObject *)f);
1639 FILE_END_ALLOW_THREADS(f)
1640 shortread = (nread < buffersize-nfilled);
1641 }
1642 if (nread == 0) {
1643 sizehint = 0;
1644 if (!ferror(f->f_fp))
1645 break;
1646 PyErr_SetFromErrno(PyExc_IOError);
1647 clearerr(f->f_fp);
1648 goto error;
1649 }
1650 totalread += nread;
1651 p = (char *)memchr(buffer+nfilled, '\n', nread);
1652 if (p == NULL) {
1653 /* Need a larger buffer to fit this line */
1654 nfilled += nread;
1655 buffersize *= 2;
1656 if (buffersize > PY_SSIZE_T_MAX) {
1657 PyErr_SetString(PyExc_OverflowError,
1658 "line is longer than a Python string can hold");
1659 goto error;
1660 }
1661 if (big_buffer == NULL) {
1662 /* Create the big buffer */
1663 big_buffer = PyString_FromStringAndSize(
1664 NULL, buffersize);
1665 if (big_buffer == NULL)
1666 goto error;
1667 buffer = PyString_AS_STRING(big_buffer);
1668 memcpy(buffer, small_buffer, nfilled);
1669 }
1670 else {
1671 /* Grow the big buffer */
1672 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1673 goto error;
1674 buffer = PyString_AS_STRING(big_buffer);
1675 }
1676 continue;
1677 }
1678 end = buffer+nfilled+nread;
1679 q = buffer;
1680 do {
1681 /* Process complete lines */
1682 p++;
1683 line = PyString_FromStringAndSize(q, p-q);
1684 if (line == NULL)
1685 goto error;
1686 err = PyList_Append(list, line);
1687 Py_DECREF(line);
1688 if (err != 0)
1689 goto error;
1690 q = p;
1691 p = (char *)memchr(q, '\n', end-q);
1692 } while (p != NULL);
1693 /* Move the remaining incomplete line to the start */
1694 nfilled = end-q;
1695 memmove(buffer, q, nfilled);
1696 if (sizehint > 0)
1697 if (totalread >= (size_t)sizehint)
1698 break;
1699 }
1700 if (nfilled != 0) {
1701 /* Partial last line */
1702 line = PyString_FromStringAndSize(buffer, nfilled);
1703 if (line == NULL)
1704 goto error;
1705 if (sizehint > 0) {
1706 /* Need to complete the last line */
1707 PyObject *rest = get_line(f, 0);
1708 if (rest == NULL) {
1709 Py_DECREF(line);
1710 goto error;
1711 }
1712 PyString_Concat(&line, rest);
1713 Py_DECREF(rest);
1714 if (line == NULL)
1715 goto error;
1716 }
1717 err = PyList_Append(list, line);
1718 Py_DECREF(line);
1719 if (err != 0)
1720 goto error;
1721 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001722
1723cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 Py_XDECREF(big_buffer);
1725 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001726
1727error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001728 Py_CLEAR(list);
1729 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001730}
1731
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001732static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001733file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001734{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001735 Py_buffer pbuf;
1736 char *s;
1737 Py_ssize_t n, n2;
1738 if (f->f_fp == NULL)
1739 return err_closed();
1740 if (!f->writable)
1741 return err_mode("writing");
1742 if (f->f_binary) {
1743 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1744 return NULL;
1745 s = pbuf.buf;
1746 n = pbuf.len;
1747 } else
1748 if (!PyArg_ParseTuple(args, "t#", &s, &n))
1749 return NULL;
1750 f->f_softspace = 0;
1751 FILE_BEGIN_ALLOW_THREADS(f)
1752 errno = 0;
1753 n2 = fwrite(s, 1, n, f->f_fp);
1754 FILE_END_ALLOW_THREADS(f)
1755 if (f->f_binary)
1756 PyBuffer_Release(&pbuf);
1757 if (n2 != n) {
1758 PyErr_SetFromErrno(PyExc_IOError);
1759 clearerr(f->f_fp);
1760 return NULL;
1761 }
1762 Py_INCREF(Py_None);
1763 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001764}
1765
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001766static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001767file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001768{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001769#define CHUNKSIZE 1000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001770 PyObject *list, *line;
1771 PyObject *it; /* iter(seq) */
1772 PyObject *result;
1773 int index, islist;
1774 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001775
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001776 assert(seq != NULL);
1777 if (f->f_fp == NULL)
1778 return err_closed();
1779 if (!f->writable)
1780 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001781
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001782 result = NULL;
1783 list = NULL;
1784 islist = PyList_Check(seq);
1785 if (islist)
1786 it = NULL;
1787 else {
1788 it = PyObject_GetIter(seq);
1789 if (it == NULL) {
1790 PyErr_SetString(PyExc_TypeError,
1791 "writelines() requires an iterable argument");
1792 return NULL;
1793 }
1794 /* From here on, fail by going to error, to reclaim "it". */
1795 list = PyList_New(CHUNKSIZE);
1796 if (list == NULL)
1797 goto error;
1798 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001799
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001800 /* Strategy: slurp CHUNKSIZE lines into a private list,
1801 checking that they are all strings, then write that list
1802 without holding the interpreter lock, then come back for more. */
1803 for (index = 0; ; index += CHUNKSIZE) {
1804 if (islist) {
1805 Py_XDECREF(list);
1806 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
1807 if (list == NULL)
1808 goto error;
1809 j = PyList_GET_SIZE(list);
1810 }
1811 else {
1812 for (j = 0; j < CHUNKSIZE; j++) {
1813 line = PyIter_Next(it);
1814 if (line == NULL) {
1815 if (PyErr_Occurred())
1816 goto error;
1817 break;
1818 }
1819 PyList_SetItem(list, j, line);
1820 }
1821 }
1822 if (j == 0)
1823 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001824
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001825 /* Check that all entries are indeed strings. If not,
1826 apply the same rules as for file.write() and
1827 convert the results to strings. This is slow, but
1828 seems to be the only way since all conversion APIs
1829 could potentially execute Python code. */
1830 for (i = 0; i < j; i++) {
1831 PyObject *v = PyList_GET_ITEM(list, i);
1832 if (!PyString_Check(v)) {
1833 const char *buffer;
1834 if (((f->f_binary &&
1835 PyObject_AsReadBuffer(v,
1836 (const void**)&buffer,
1837 &len)) ||
1838 PyObject_AsCharBuffer(v,
1839 &buffer,
1840 &len))) {
1841 PyErr_SetString(PyExc_TypeError,
1842 "writelines() argument must be a sequence of strings");
1843 goto error;
1844 }
1845 line = PyString_FromStringAndSize(buffer,
1846 len);
1847 if (line == NULL)
1848 goto error;
1849 Py_DECREF(v);
1850 PyList_SET_ITEM(list, i, line);
1851 }
1852 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001853
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001854 /* Since we are releasing the global lock, the
1855 following code may *not* execute Python code. */
1856 f->f_softspace = 0;
1857 FILE_BEGIN_ALLOW_THREADS(f)
1858 errno = 0;
1859 for (i = 0; i < j; i++) {
1860 line = PyList_GET_ITEM(list, i);
1861 len = PyString_GET_SIZE(line);
1862 nwritten = fwrite(PyString_AS_STRING(line),
1863 1, len, f->f_fp);
1864 if (nwritten != len) {
1865 FILE_ABORT_ALLOW_THREADS(f)
1866 PyErr_SetFromErrno(PyExc_IOError);
1867 clearerr(f->f_fp);
1868 goto error;
1869 }
1870 }
1871 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001872
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001873 if (j < CHUNKSIZE)
1874 break;
1875 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001876
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001877 Py_INCREF(Py_None);
1878 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001879 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001880 Py_XDECREF(list);
1881 Py_XDECREF(it);
1882 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001883#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001884}
1885
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001886static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001887file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001888{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001889 if (f->f_fp == NULL)
1890 return err_closed();
1891 Py_INCREF(f);
1892 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001893}
1894
Georg Brandl98b40ad2006-06-08 14:50:21 +00001895static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001896file_xreadlines(PyFileObject *f)
1897{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001898 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1899 "try 'for line in f' instead", 1) < 0)
1900 return NULL;
1901 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00001902}
1903
1904static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001905file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001906{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001907 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
1908 if (!ret)
1909 /* If error occurred, pass through */
1910 return NULL;
1911 Py_DECREF(ret);
1912 /* We cannot return the result of close since a true
1913 * value will be interpreted as "yes, swallow the
1914 * exception if one was raised inside the with block". */
1915 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00001916}
1917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001918PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001919"readline([size]) -> next line from the file, as a string.\n"
1920"\n"
1921"Retain newline. A non-negative size argument limits the maximum\n"
1922"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001923"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001925PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001926"read([size]) -> read at most size bytes, returned as a string.\n"
1927"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001928"If the size argument is negative or omitted, read until EOF is reached.\n"
1929"Notice that when in non-blocking mode, less data than what was requested\n"
1930"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001932PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001933"write(str) -> None. Write string str to file.\n"
1934"\n"
1935"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001936"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001938PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001939"fileno() -> integer \"file descriptor\".\n"
1940"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001941"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001943PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001944"seek(offset[, whence]) -> None. Move to new file position.\n"
1945"\n"
1946"Argument offset is a byte count. Optional argument whence defaults to\n"
1947"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1948"(move relative to current position, positive or negative), and 2 (move\n"
1949"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001950"seeking beyond the end of a file). If the file is opened in text mode,\n"
1951"only offsets returned by tell() are legal. Use of other offsets causes\n"
1952"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001953"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001954"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001955
Guido van Rossumd7047b31995-01-02 19:07:15 +00001956#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001957PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001958"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1959"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001960"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001961#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001963PyDoc_STRVAR(tell_doc,
1964"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001966PyDoc_STRVAR(readinto_doc,
1967"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001968
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001969PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001970"readlines([size]) -> list of strings, each a line from the file.\n"
1971"\n"
1972"Call readline() repeatedly and return a list of the lines so read.\n"
1973"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001974"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001975
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001976PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001977"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001978"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001979"For backward compatibility. File objects now include the performance\n"
1980"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001981
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001982PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001983"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001984"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001985"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001987
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001988PyDoc_STRVAR(flush_doc,
1989"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001990
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001991PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001992"close() -> None or (perhaps) an integer. Close the file.\n"
1993"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001994"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001995"further I/O operations. close() may be called more than once without\n"
1996"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001999PyDoc_STRVAR(isatty_doc,
2000"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002001
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002002PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002003 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002004
Georg Brandl98b40ad2006-06-08 14:50:21 +00002005PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002006 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002007
Tim Petersefc3a3a2001-09-20 07:55:22 +00002008static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002009 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2010 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2011 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2012 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2013 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002014#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002015 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002016#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002017 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2018 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2019 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2020 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2021 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2022 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2023 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2024 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2025 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2026 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2027 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002028};
2029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002031
Guido van Rossum6f799372001-09-20 20:46:19 +00002032static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002033 {"mode", T_OBJECT, OFF(f_mode), RO,
2034 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2035 {"name", T_OBJECT, OFF(f_name), RO,
2036 "file name"},
2037 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2038 "file encoding"},
2039 {"errors", T_OBJECT, OFF(f_errors), RO,
2040 "Unicode error handler"},
2041 /* getattr(f, "closed") is implemented without this table */
2042 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002043};
2044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002045static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002047{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002048 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002049}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002050static PyObject *
2051get_newlines(PyFileObject *f, void *closure)
2052{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002053 switch (f->f_newlinetypes) {
2054 case NEWLINE_UNKNOWN:
2055 Py_INCREF(Py_None);
2056 return Py_None;
2057 case NEWLINE_CR:
2058 return PyString_FromString("\r");
2059 case NEWLINE_LF:
2060 return PyString_FromString("\n");
2061 case NEWLINE_CR|NEWLINE_LF:
2062 return Py_BuildValue("(ss)", "\r", "\n");
2063 case NEWLINE_CRLF:
2064 return PyString_FromString("\r\n");
2065 case NEWLINE_CR|NEWLINE_CRLF:
2066 return Py_BuildValue("(ss)", "\r", "\r\n");
2067 case NEWLINE_LF|NEWLINE_CRLF:
2068 return Py_BuildValue("(ss)", "\n", "\r\n");
2069 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2070 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2071 default:
2072 PyErr_Format(PyExc_SystemError,
2073 "Unknown newlines value 0x%x\n",
2074 f->f_newlinetypes);
2075 return NULL;
2076 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002077}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002078
Georg Brandl65bb42d2008-03-21 20:38:24 +00002079static PyObject *
2080get_softspace(PyFileObject *f, void *closure)
2081{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002082 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2083 return NULL;
2084 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002085}
2086
2087static int
2088set_softspace(PyFileObject *f, PyObject *value)
2089{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002090 int new;
2091 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2092 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002094 if (value == NULL) {
2095 PyErr_SetString(PyExc_TypeError,
2096 "can't delete softspace attribute");
2097 return -1;
2098 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002099
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002100 new = PyInt_AsLong(value);
2101 if (new == -1 && PyErr_Occurred())
2102 return -1;
2103 f->f_softspace = new;
2104 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002105}
2106
Guido van Rossum32d34c82001-09-20 21:45:26 +00002107static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002108 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2109 {"newlines", (getter)get_newlines, NULL,
2110 "end-of-line convention used in this file"},
2111 {"softspace", (getter)get_softspace, (setter)set_softspace,
2112 "flag indicating that a space needs to be printed; used by print"},
2113 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002115
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002116static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002117drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002118{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002119 if (f->f_buf != NULL) {
2120 PyMem_Free(f->f_buf);
2121 f->f_buf = NULL;
2122 }
Guido van Rossum65967252001-04-21 13:20:18 +00002123}
2124
Tim Petersf1827cf2003-09-07 03:30:18 +00002125/* Make sure that file has a readahead buffer with at least one byte
2126 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002127 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002128static int
2129readahead(PyFileObject *f, int bufsize)
2130{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002131 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002132
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002133 if (f->f_buf != NULL) {
2134 if( (f->f_bufend - f->f_bufptr) >= 1)
2135 return 0;
2136 else
2137 drop_readahead(f);
2138 }
2139 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
2140 PyErr_NoMemory();
2141 return -1;
2142 }
2143 FILE_BEGIN_ALLOW_THREADS(f)
2144 errno = 0;
2145 chunksize = Py_UniversalNewlineFread(
2146 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
2147 FILE_END_ALLOW_THREADS(f)
2148 if (chunksize == 0) {
2149 if (ferror(f->f_fp)) {
2150 PyErr_SetFromErrno(PyExc_IOError);
2151 clearerr(f->f_fp);
2152 drop_readahead(f);
2153 return -1;
2154 }
2155 }
2156 f->f_bufptr = f->f_buf;
2157 f->f_bufend = f->f_buf + chunksize;
2158 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002159}
2160
2161/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002162 uninitialized bytes followed by the remainder of the line. Don't be
2163 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002164 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2165
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002166static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002167readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2168{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002169 PyStringObject* s;
2170 char *bufptr;
2171 char *buf;
2172 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002174 if (f->f_buf == NULL)
2175 if (readahead(f, bufsize) < 0)
2176 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002177
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002178 len = f->f_bufend - f->f_bufptr;
2179 if (len == 0)
2180 return (PyStringObject *)
2181 PyString_FromStringAndSize(NULL, skip);
2182 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
2183 if (bufptr != NULL) {
2184 bufptr++; /* Count the '\n' */
2185 len = bufptr - f->f_bufptr;
2186 s = (PyStringObject *)
2187 PyString_FromStringAndSize(NULL, skip+len);
2188 if (s == NULL)
2189 return NULL;
2190 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2191 f->f_bufptr = bufptr;
2192 if (bufptr == f->f_bufend)
2193 drop_readahead(f);
2194 } else {
2195 bufptr = f->f_bufptr;
2196 buf = f->f_buf;
2197 f->f_buf = NULL; /* Force new readahead buffer */
2198 assert(skip+len < INT_MAX);
2199 s = readahead_get_line_skip(
2200 f, (int)(skip+len), bufsize + (bufsize>>2) );
2201 if (s == NULL) {
2202 PyMem_Free(buf);
2203 return NULL;
2204 }
2205 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2206 PyMem_Free(buf);
2207 }
2208 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002209}
2210
2211/* A larger buffer size may actually decrease performance. */
2212#define READAHEAD_BUFSIZE 8192
2213
2214static PyObject *
2215file_iternext(PyFileObject *f)
2216{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002217 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002218
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002219 if (f->f_fp == NULL)
2220 return err_closed();
2221 if (!f->readable)
2222 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002223
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002224 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2225 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2226 Py_XDECREF(l);
2227 return NULL;
2228 }
2229 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002230}
2231
2232
Tim Peters59c9a642001-09-13 05:38:56 +00002233static PyObject *
2234file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2235{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002236 PyObject *self;
2237 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002238
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002239 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002241 if (not_yet_string == NULL) {
2242 not_yet_string = PyString_InternFromString("<uninitialized file>");
2243 if (not_yet_string == NULL)
2244 return NULL;
2245 }
Tim Peters44410012001-09-14 03:26:08 +00002246
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002247 self = type->tp_alloc(type, 0);
2248 if (self != NULL) {
2249 /* Always fill in the name and mode, so that nobody else
2250 needs to special-case NULLs there. */
2251 Py_INCREF(not_yet_string);
2252 ((PyFileObject *)self)->f_name = not_yet_string;
2253 Py_INCREF(not_yet_string);
2254 ((PyFileObject *)self)->f_mode = not_yet_string;
2255 Py_INCREF(Py_None);
2256 ((PyFileObject *)self)->f_encoding = Py_None;
2257 Py_INCREF(Py_None);
2258 ((PyFileObject *)self)->f_errors = Py_None;
2259 ((PyFileObject *)self)->weakreflist = NULL;
2260 ((PyFileObject *)self)->unlocked_count = 0;
2261 }
2262 return self;
Tim Peters44410012001-09-14 03:26:08 +00002263}
2264
2265static int
2266file_init(PyObject *self, PyObject *args, PyObject *kwds)
2267{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002268 PyFileObject *foself = (PyFileObject *)self;
2269 int ret = 0;
2270 static char *kwlist[] = {"name", "mode", "buffering", 0};
2271 char *name = NULL;
2272 char *mode = "r";
2273 int bufsize = -1;
2274 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002275#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002276 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002277#endif
Tim Peters44410012001-09-14 03:26:08 +00002278
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002279 assert(PyFile_Check(self));
2280 if (foself->f_fp != NULL) {
2281 /* Have to close the existing file first. */
2282 PyObject *closeresult = file_close(foself);
2283 if (closeresult == NULL)
2284 return -1;
2285 Py_DECREF(closeresult);
2286 }
Tim Peters59c9a642001-09-13 05:38:56 +00002287
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002288#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002289 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2290 kwlist, &po, &mode, &bufsize)) {
2291 wideargument = 1;
2292 if (fill_file_fields(foself, NULL, po, mode,
2293 fclose) == NULL)
2294 goto Error;
2295 } else {
2296 /* Drop the argument parsing error as narrow
2297 strings are also valid. */
2298 PyErr_Clear();
2299 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002300#endif
2301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002302 if (!wideargument) {
2303 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002304
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002305 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2306 Py_FileSystemDefaultEncoding,
2307 &name,
2308 &mode, &bufsize))
2309 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002310
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002311 /* We parse again to get the name as a PyObject */
2312 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2313 kwlist, &o_name, &mode,
2314 &bufsize))
2315 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002316
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002317 if (fill_file_fields(foself, NULL, o_name, mode,
2318 fclose) == NULL)
2319 goto Error;
2320 }
2321 if (open_the_file(foself, name, mode) == NULL)
2322 goto Error;
2323 foself->f_setbuf = NULL;
2324 PyFile_SetBufSize(self, bufsize);
2325 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002326
2327Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002328 ret = -1;
2329 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002330Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002331 PyMem_Free(name); /* free the encoded string */
2332 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002333}
2334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002335PyDoc_VAR(file_doc) =
2336PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002337"file(name[, mode[, buffering]]) -> file object\n"
2338"\n"
2339"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2340"writing or appending. The file will be created if it doesn't exist\n"
2341"when opened for writing or appending; it will be truncated when\n"
2342"opened for writing. Add a 'b' to the mode for binary files.\n"
2343"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2344"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002345"buffered, and larger numbers specify the buffer size. The preferred way\n"
2346"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002347)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002348PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002349"Add a 'U' to mode to open the file for input with universal newline\n"
2350"support. Any line ending in the input file will be seen as a '\\n'\n"
2351"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2352"the value for this attribute is one of None (no newline read yet),\n"
2353"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2354"\n"
2355"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002356);
Tim Peters59c9a642001-09-13 05:38:56 +00002357
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002358PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002359 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2360 "file",
2361 sizeof(PyFileObject),
2362 0,
2363 (destructor)file_dealloc, /* tp_dealloc */
2364 0, /* tp_print */
2365 0, /* tp_getattr */
2366 0, /* tp_setattr */
2367 0, /* tp_compare */
2368 (reprfunc)file_repr, /* tp_repr */
2369 0, /* tp_as_number */
2370 0, /* tp_as_sequence */
2371 0, /* tp_as_mapping */
2372 0, /* tp_hash */
2373 0, /* tp_call */
2374 0, /* tp_str */
2375 PyObject_GenericGetAttr, /* tp_getattro */
2376 /* softspace is writable: we must supply tp_setattro */
2377 PyObject_GenericSetAttr, /* tp_setattro */
2378 0, /* tp_as_buffer */
2379 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2380 file_doc, /* tp_doc */
2381 0, /* tp_traverse */
2382 0, /* tp_clear */
2383 0, /* tp_richcompare */
2384 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2385 (getiterfunc)file_self, /* tp_iter */
2386 (iternextfunc)file_iternext, /* tp_iternext */
2387 file_methods, /* tp_methods */
2388 file_memberlist, /* tp_members */
2389 file_getsetlist, /* tp_getset */
2390 0, /* tp_base */
2391 0, /* tp_dict */
2392 0, /* tp_descr_get */
2393 0, /* tp_descr_set */
2394 0, /* tp_dictoffset */
2395 file_init, /* tp_init */
2396 PyType_GenericAlloc, /* tp_alloc */
2397 file_new, /* tp_new */
2398 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002399};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002400
2401/* Interface for the 'soft space' between print items. */
2402
2403int
Fred Drakefd99de62000-07-09 05:02:18 +00002404PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002405{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002406 long oldflag = 0;
2407 if (f == NULL) {
2408 /* Do nothing */
2409 }
2410 else if (PyFile_Check(f)) {
2411 oldflag = ((PyFileObject *)f)->f_softspace;
2412 ((PyFileObject *)f)->f_softspace = newflag;
2413 }
2414 else {
2415 PyObject *v;
2416 v = PyObject_GetAttrString(f, "softspace");
2417 if (v == NULL)
2418 PyErr_Clear();
2419 else {
2420 if (PyInt_Check(v))
2421 oldflag = PyInt_AsLong(v);
2422 assert(oldflag < INT_MAX);
2423 Py_DECREF(v);
2424 }
2425 v = PyInt_FromLong((long)newflag);
2426 if (v == NULL)
2427 PyErr_Clear();
2428 else {
2429 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2430 PyErr_Clear();
2431 Py_DECREF(v);
2432 }
2433 }
2434 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002435}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002436
2437/* Interfaces to write objects/strings to file-like objects */
2438
2439int
Fred Drakefd99de62000-07-09 05:02:18 +00002440PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002442 PyObject *writer, *value, *args, *result;
2443 if (f == NULL) {
2444 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2445 return -1;
2446 }
2447 else if (PyFile_Check(f)) {
2448 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002449#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002450 PyObject *enc = fobj->f_encoding;
2451 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002452#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002453 if (fobj->f_fp == NULL) {
2454 err_closed();
2455 return -1;
2456 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002457#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002458 if ((flags & Py_PRINT_RAW) &&
2459 PyUnicode_Check(v) && enc != Py_None) {
2460 char *cenc = PyString_AS_STRING(enc);
2461 char *errors = fobj->f_errors == Py_None ?
2462 "strict" : PyString_AS_STRING(fobj->f_errors);
2463 value = PyUnicode_AsEncodedString(v, cenc, errors);
2464 if (value == NULL)
2465 return -1;
2466 } else {
2467 value = v;
2468 Py_INCREF(value);
2469 }
2470 result = file_PyObject_Print(value, fobj, flags);
2471 Py_DECREF(value);
2472 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002473#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002474 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002475#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002476 }
2477 writer = PyObject_GetAttrString(f, "write");
2478 if (writer == NULL)
2479 return -1;
2480 if (flags & Py_PRINT_RAW) {
2481 if (PyUnicode_Check(v)) {
2482 value = v;
2483 Py_INCREF(value);
2484 } else
2485 value = PyObject_Str(v);
2486 }
2487 else
2488 value = PyObject_Repr(v);
2489 if (value == NULL) {
2490 Py_DECREF(writer);
2491 return -1;
2492 }
2493 args = PyTuple_Pack(1, value);
2494 if (args == NULL) {
2495 Py_DECREF(value);
2496 Py_DECREF(writer);
2497 return -1;
2498 }
2499 result = PyEval_CallObject(writer, args);
2500 Py_DECREF(args);
2501 Py_DECREF(value);
2502 Py_DECREF(writer);
2503 if (result == NULL)
2504 return -1;
2505 Py_DECREF(result);
2506 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002507}
2508
Guido van Rossum27a60b11997-05-22 22:25:11 +00002509int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002510PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002511{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002512
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002513 if (f == NULL) {
2514 /* Should be caused by a pre-existing error */
2515 if (!PyErr_Occurred())
2516 PyErr_SetString(PyExc_SystemError,
2517 "null file for PyFile_WriteString");
2518 return -1;
2519 }
2520 else if (PyFile_Check(f)) {
2521 PyFileObject *fobj = (PyFileObject *) f;
2522 FILE *fp = PyFile_AsFile(f);
2523 if (fp == NULL) {
2524 err_closed();
2525 return -1;
2526 }
2527 FILE_BEGIN_ALLOW_THREADS(fobj)
2528 fputs(s, fp);
2529 FILE_END_ALLOW_THREADS(fobj)
2530 return 0;
2531 }
2532 else if (!PyErr_Occurred()) {
2533 PyObject *v = PyString_FromString(s);
2534 int err;
2535 if (v == NULL)
2536 return -1;
2537 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2538 Py_DECREF(v);
2539 return err;
2540 }
2541 else
2542 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002543}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002544
2545/* Try to get a file-descriptor from a Python object. If the object
2546 is an integer or long integer, its value is returned. If not, the
2547 object's fileno() method is called if it exists; the method must return
2548 an integer or long integer, which is returned as the file descriptor value.
2549 -1 is returned on failure.
2550*/
2551
2552int PyObject_AsFileDescriptor(PyObject *o)
2553{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002554 int fd;
2555 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002556
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002557 if (PyInt_Check(o)) {
2558 fd = PyInt_AsLong(o);
2559 }
2560 else if (PyLong_Check(o)) {
2561 fd = PyLong_AsLong(o);
2562 }
2563 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2564 {
2565 PyObject *fno = PyEval_CallObject(meth, NULL);
2566 Py_DECREF(meth);
2567 if (fno == NULL)
2568 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002569
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002570 if (PyInt_Check(fno)) {
2571 fd = PyInt_AsLong(fno);
2572 Py_DECREF(fno);
2573 }
2574 else if (PyLong_Check(fno)) {
2575 fd = PyLong_AsLong(fno);
2576 Py_DECREF(fno);
2577 }
2578 else {
2579 PyErr_SetString(PyExc_TypeError,
2580 "fileno() returned a non-integer");
2581 Py_DECREF(fno);
2582 return -1;
2583 }
2584 }
2585 else {
2586 PyErr_SetString(PyExc_TypeError,
2587 "argument must be an int, or have a fileno() method.");
2588 return -1;
2589 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002590
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002591 if (fd < 0) {
2592 PyErr_Format(PyExc_ValueError,
2593 "file descriptor cannot be a negative integer (%i)",
2594 fd);
2595 return -1;
2596 }
2597 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002598}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002599
Jack Jansen7b8c7542002-04-14 20:12:41 +00002600/* From here on we need access to the real fgets and fread */
2601#undef fgets
2602#undef fread
2603
2604/*
2605** Py_UniversalNewlineFgets is an fgets variation that understands
2606** all of \r, \n and \r\n conventions.
2607** The stream should be opened in binary mode.
2608** If fobj is NULL the routine always does newline conversion, and
2609** it may peek one char ahead to gobble the second char in \r\n.
2610** If fobj is non-NULL it must be a PyFileObject. In this case there
2611** is no readahead but in stead a flag is used to skip a following
2612** \n on the next read. Also, if the file is open in binary mode
2613** the whole conversion is skipped. Finally, the routine keeps track of
2614** the different types of newlines seen.
2615** Note that we need no error handling: fgets() treats error and eof
2616** identically.
2617*/
2618char *
2619Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2620{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002621 char *p = buf;
2622 int c;
2623 int newlinetypes = 0;
2624 int skipnextlf = 0;
2625 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002627 if (fobj) {
2628 if (!PyFile_Check(fobj)) {
2629 errno = ENXIO; /* What can you do... */
2630 return NULL;
2631 }
2632 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2633 if ( !univ_newline )
2634 return fgets(buf, n, stream);
2635 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2636 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2637 }
2638 FLOCKFILE(stream);
2639 c = 'x'; /* Shut up gcc warning */
2640 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2641 if (skipnextlf ) {
2642 skipnextlf = 0;
2643 if (c == '\n') {
2644 /* Seeing a \n here with skipnextlf true
2645 ** means we saw a \r before.
2646 */
2647 newlinetypes |= NEWLINE_CRLF;
2648 c = GETC(stream);
2649 if (c == EOF) break;
2650 } else {
2651 /*
2652 ** Note that c == EOF also brings us here,
2653 ** so we're okay if the last char in the file
2654 ** is a CR.
2655 */
2656 newlinetypes |= NEWLINE_CR;
2657 }
2658 }
2659 if (c == '\r') {
2660 /* A \r is translated into a \n, and we skip
2661 ** an adjacent \n, if any. We don't set the
2662 ** newlinetypes flag until we've seen the next char.
2663 */
2664 skipnextlf = 1;
2665 c = '\n';
2666 } else if ( c == '\n') {
2667 newlinetypes |= NEWLINE_LF;
2668 }
2669 *p++ = c;
2670 if (c == '\n') break;
2671 }
2672 if ( c == EOF && skipnextlf )
2673 newlinetypes |= NEWLINE_CR;
2674 FUNLOCKFILE(stream);
2675 *p = '\0';
2676 if (fobj) {
2677 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2678 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2679 } else if ( skipnextlf ) {
2680 /* If we have no file object we cannot save the
2681 ** skipnextlf flag. We have to readahead, which
2682 ** will cause a pause if we're reading from an
2683 ** interactive stream, but that is very unlikely
2684 ** unless we're doing something silly like
2685 ** execfile("/dev/tty").
2686 */
2687 c = GETC(stream);
2688 if ( c != '\n' )
2689 ungetc(c, stream);
2690 }
2691 if (p == buf)
2692 return NULL;
2693 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002694}
2695
2696/*
2697** Py_UniversalNewlineFread is an fread variation that understands
2698** all of \r, \n and \r\n conventions.
2699** The stream should be opened in binary mode.
2700** fobj must be a PyFileObject. In this case there
2701** is no readahead but in stead a flag is used to skip a following
2702** \n on the next read. Also, if the file is open in binary mode
2703** the whole conversion is skipped. Finally, the routine keeps track of
2704** the different types of newlines seen.
2705*/
2706size_t
Tim Peters058b1412002-04-21 07:29:14 +00002707Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002708 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002710 char *dst = buf;
2711 PyFileObject *f = (PyFileObject *)fobj;
2712 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002714 assert(buf != NULL);
2715 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002716
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002717 if (!fobj || !PyFile_Check(fobj)) {
2718 errno = ENXIO; /* What can you do... */
2719 return 0;
2720 }
2721 if (!f->f_univ_newline)
2722 return fread(buf, 1, n, stream);
2723 newlinetypes = f->f_newlinetypes;
2724 skipnextlf = f->f_skipnextlf;
2725 /* Invariant: n is the number of bytes remaining to be filled
2726 * in the buffer.
2727 */
2728 while (n) {
2729 size_t nread;
2730 int shortread;
2731 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002733 nread = fread(dst, 1, n, stream);
2734 assert(nread <= n);
2735 if (nread == 0)
2736 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002737
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002738 n -= nread; /* assuming 1 byte out for each in; will adjust */
2739 shortread = n != 0; /* true iff EOF or error */
2740 while (nread--) {
2741 char c = *src++;
2742 if (c == '\r') {
2743 /* Save as LF and set flag to skip next LF. */
2744 *dst++ = '\n';
2745 skipnextlf = 1;
2746 }
2747 else if (skipnextlf && c == '\n') {
2748 /* Skip LF, and remember we saw CR LF. */
2749 skipnextlf = 0;
2750 newlinetypes |= NEWLINE_CRLF;
2751 ++n;
2752 }
2753 else {
2754 /* Normal char to be stored in buffer. Also
2755 * update the newlinetypes flag if either this
2756 * is an LF or the previous char was a CR.
2757 */
2758 if (c == '\n')
2759 newlinetypes |= NEWLINE_LF;
2760 else if (skipnextlf)
2761 newlinetypes |= NEWLINE_CR;
2762 *dst++ = c;
2763 skipnextlf = 0;
2764 }
2765 }
2766 if (shortread) {
2767 /* If this is EOF, update type flags. */
2768 if (skipnextlf && feof(stream))
2769 newlinetypes |= NEWLINE_CR;
2770 break;
2771 }
2772 }
2773 f->f_newlinetypes = newlinetypes;
2774 f->f_skipnextlf = skipnextlf;
2775 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002776}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002777
2778#ifdef __cplusplus
2779}
2780#endif