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