blob: 2647b54269ca864a8c6c74e0b07072bcb7db0099 [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 }
Benjamin Petersonbf775542010-10-16 19:20:12 +00001852 /* The iterator might have closed the file on us. */
1853 if (f->f_fp == NULL) {
1854 err_closed();
1855 goto error;
1856 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001857 }
1858 if (j == 0)
1859 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001860
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 /* Check that all entries are indeed strings. If not,
1862 apply the same rules as for file.write() and
1863 convert the results to strings. This is slow, but
1864 seems to be the only way since all conversion APIs
1865 could potentially execute Python code. */
1866 for (i = 0; i < j; i++) {
1867 PyObject *v = PyList_GET_ITEM(list, i);
1868 if (!PyString_Check(v)) {
1869 const char *buffer;
1870 if (((f->f_binary &&
1871 PyObject_AsReadBuffer(v,
1872 (const void**)&buffer,
1873 &len)) ||
1874 PyObject_AsCharBuffer(v,
1875 &buffer,
1876 &len))) {
1877 PyErr_SetString(PyExc_TypeError,
1878 "writelines() argument must be a sequence of strings");
1879 goto error;
1880 }
1881 line = PyString_FromStringAndSize(buffer,
1882 len);
1883 if (line == NULL)
1884 goto error;
1885 Py_DECREF(v);
1886 PyList_SET_ITEM(list, i, line);
1887 }
1888 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001889
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001890 /* Since we are releasing the global lock, the
1891 following code may *not* execute Python code. */
1892 f->f_softspace = 0;
1893 FILE_BEGIN_ALLOW_THREADS(f)
1894 errno = 0;
1895 for (i = 0; i < j; i++) {
1896 line = PyList_GET_ITEM(list, i);
1897 len = PyString_GET_SIZE(line);
1898 nwritten = fwrite(PyString_AS_STRING(line),
1899 1, len, f->f_fp);
1900 if (nwritten != len) {
1901 FILE_ABORT_ALLOW_THREADS(f)
1902 PyErr_SetFromErrno(PyExc_IOError);
1903 clearerr(f->f_fp);
1904 goto error;
1905 }
1906 }
1907 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001908
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001909 if (j < CHUNKSIZE)
1910 break;
1911 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001912
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001913 Py_INCREF(Py_None);
1914 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001915 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001916 Py_XDECREF(list);
1917 Py_XDECREF(it);
1918 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001919#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001920}
1921
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001922static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001923file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001924{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001925 if (f->f_fp == NULL)
1926 return err_closed();
1927 Py_INCREF(f);
1928 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001929}
1930
Georg Brandl98b40ad2006-06-08 14:50:21 +00001931static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001932file_xreadlines(PyFileObject *f)
1933{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001934 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1935 "try 'for line in f' instead", 1) < 0)
1936 return NULL;
1937 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00001938}
1939
1940static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001941file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001943 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
1944 if (!ret)
1945 /* If error occurred, pass through */
1946 return NULL;
1947 Py_DECREF(ret);
1948 /* We cannot return the result of close since a true
1949 * value will be interpreted as "yes, swallow the
1950 * exception if one was raised inside the with block". */
1951 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00001952}
1953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001954PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001955"readline([size]) -> next line from the file, as a string.\n"
1956"\n"
1957"Retain newline. A non-negative size argument limits the maximum\n"
1958"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001959"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001960
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001961PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001962"read([size]) -> read at most size bytes, returned as a string.\n"
1963"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001964"If the size argument is negative or omitted, read until EOF is reached.\n"
1965"Notice that when in non-blocking mode, less data than what was requested\n"
1966"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001968PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001969"write(str) -> None. Write string str to file.\n"
1970"\n"
1971"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001972"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001973
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001974PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001975"fileno() -> integer \"file descriptor\".\n"
1976"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001977"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001978
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001979PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001980"seek(offset[, whence]) -> None. Move to new file position.\n"
1981"\n"
1982"Argument offset is a byte count. Optional argument whence defaults to\n"
1983"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1984"(move relative to current position, positive or negative), and 2 (move\n"
1985"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001986"seeking beyond the end of a file). If the file is opened in text mode,\n"
1987"only offsets returned by tell() are legal. Use of other offsets causes\n"
1988"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001989"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001990"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001991
Guido van Rossumd7047b31995-01-02 19:07:15 +00001992#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001993PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001994"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1995"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001996"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001997#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001999PyDoc_STRVAR(tell_doc,
2000"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002001
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002002PyDoc_STRVAR(readinto_doc,
2003"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002004
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002005PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002006"readlines([size]) -> list of strings, each a line from the file.\n"
2007"\n"
2008"Call readline() repeatedly and return a list of the lines so read.\n"
2009"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002010"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002011
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002012PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002013"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002014"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002015"For backward compatibility. File objects now include the performance\n"
2016"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002018PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002019"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002020"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002021"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002022"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024PyDoc_STRVAR(flush_doc,
2025"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002026
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002028"close() -> None or (perhaps) an integer. Close the file.\n"
2029"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00002030"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002031"further I/O operations. close() may be called more than once without\n"
2032"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002033"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002034
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002035PyDoc_STRVAR(isatty_doc,
2036"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002037
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002038PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002039 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002040
Georg Brandl98b40ad2006-06-08 14:50:21 +00002041PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002042 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002043
Tim Petersefc3a3a2001-09-20 07:55:22 +00002044static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002045 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2046 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2047 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2048 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2049 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002050#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002051 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002052#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002053 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2054 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2055 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2056 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2057 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2058 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2059 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2060 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2061 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2062 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2063 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002064};
2065
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002066#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002067
Guido van Rossum6f799372001-09-20 20:46:19 +00002068static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002069 {"mode", T_OBJECT, OFF(f_mode), RO,
2070 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2071 {"name", T_OBJECT, OFF(f_name), RO,
2072 "file name"},
2073 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2074 "file encoding"},
2075 {"errors", T_OBJECT, OFF(f_errors), RO,
2076 "Unicode error handler"},
2077 /* getattr(f, "closed") is implemented without this table */
2078 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002079};
2080
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002081static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002083{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002084 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002085}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002086static PyObject *
2087get_newlines(PyFileObject *f, void *closure)
2088{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002089 switch (f->f_newlinetypes) {
2090 case NEWLINE_UNKNOWN:
2091 Py_INCREF(Py_None);
2092 return Py_None;
2093 case NEWLINE_CR:
2094 return PyString_FromString("\r");
2095 case NEWLINE_LF:
2096 return PyString_FromString("\n");
2097 case NEWLINE_CR|NEWLINE_LF:
2098 return Py_BuildValue("(ss)", "\r", "\n");
2099 case NEWLINE_CRLF:
2100 return PyString_FromString("\r\n");
2101 case NEWLINE_CR|NEWLINE_CRLF:
2102 return Py_BuildValue("(ss)", "\r", "\r\n");
2103 case NEWLINE_LF|NEWLINE_CRLF:
2104 return Py_BuildValue("(ss)", "\n", "\r\n");
2105 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2106 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2107 default:
2108 PyErr_Format(PyExc_SystemError,
2109 "Unknown newlines value 0x%x\n",
2110 f->f_newlinetypes);
2111 return NULL;
2112 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002113}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002114
Georg Brandl65bb42d2008-03-21 20:38:24 +00002115static PyObject *
2116get_softspace(PyFileObject *f, void *closure)
2117{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2119 return NULL;
2120 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002121}
2122
2123static int
2124set_softspace(PyFileObject *f, PyObject *value)
2125{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002126 int new;
2127 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2128 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002129
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002130 if (value == NULL) {
2131 PyErr_SetString(PyExc_TypeError,
2132 "can't delete softspace attribute");
2133 return -1;
2134 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002135
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002136 new = PyInt_AsLong(value);
2137 if (new == -1 && PyErr_Occurred())
2138 return -1;
2139 f->f_softspace = new;
2140 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002141}
2142
Guido van Rossum32d34c82001-09-20 21:45:26 +00002143static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002144 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2145 {"newlines", (getter)get_newlines, NULL,
2146 "end-of-line convention used in this file"},
2147 {"softspace", (getter)get_softspace, (setter)set_softspace,
2148 "flag indicating that a space needs to be printed; used by print"},
2149 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002151
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002152static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002153drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002154{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002155 if (f->f_buf != NULL) {
2156 PyMem_Free(f->f_buf);
2157 f->f_buf = NULL;
2158 }
Guido van Rossum65967252001-04-21 13:20:18 +00002159}
2160
Tim Petersf1827cf2003-09-07 03:30:18 +00002161/* Make sure that file has a readahead buffer with at least one byte
2162 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002163 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002164static int
2165readahead(PyFileObject *f, int bufsize)
2166{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002167 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002168
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002169 if (f->f_buf != NULL) {
2170 if( (f->f_bufend - f->f_bufptr) >= 1)
2171 return 0;
2172 else
2173 drop_readahead(f);
2174 }
2175 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
2176 PyErr_NoMemory();
2177 return -1;
2178 }
2179 FILE_BEGIN_ALLOW_THREADS(f)
2180 errno = 0;
2181 chunksize = Py_UniversalNewlineFread(
2182 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
2183 FILE_END_ALLOW_THREADS(f)
2184 if (chunksize == 0) {
2185 if (ferror(f->f_fp)) {
2186 PyErr_SetFromErrno(PyExc_IOError);
2187 clearerr(f->f_fp);
2188 drop_readahead(f);
2189 return -1;
2190 }
2191 }
2192 f->f_bufptr = f->f_buf;
2193 f->f_bufend = f->f_buf + chunksize;
2194 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002195}
2196
2197/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002198 uninitialized bytes followed by the remainder of the line. Don't be
2199 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002200 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2201
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002202static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002203readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2204{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002205 PyStringObject* s;
2206 char *bufptr;
2207 char *buf;
2208 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002209
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002210 if (f->f_buf == NULL)
2211 if (readahead(f, bufsize) < 0)
2212 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002213
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002214 len = f->f_bufend - f->f_bufptr;
2215 if (len == 0)
2216 return (PyStringObject *)
2217 PyString_FromStringAndSize(NULL, skip);
2218 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
2219 if (bufptr != NULL) {
2220 bufptr++; /* Count the '\n' */
2221 len = bufptr - f->f_bufptr;
2222 s = (PyStringObject *)
2223 PyString_FromStringAndSize(NULL, skip+len);
2224 if (s == NULL)
2225 return NULL;
2226 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2227 f->f_bufptr = bufptr;
2228 if (bufptr == f->f_bufend)
2229 drop_readahead(f);
2230 } else {
2231 bufptr = f->f_bufptr;
2232 buf = f->f_buf;
2233 f->f_buf = NULL; /* Force new readahead buffer */
2234 assert(skip+len < INT_MAX);
2235 s = readahead_get_line_skip(
2236 f, (int)(skip+len), bufsize + (bufsize>>2) );
2237 if (s == NULL) {
2238 PyMem_Free(buf);
2239 return NULL;
2240 }
2241 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2242 PyMem_Free(buf);
2243 }
2244 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002245}
2246
2247/* A larger buffer size may actually decrease performance. */
2248#define READAHEAD_BUFSIZE 8192
2249
2250static PyObject *
2251file_iternext(PyFileObject *f)
2252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002253 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002254
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002255 if (f->f_fp == NULL)
2256 return err_closed();
2257 if (!f->readable)
2258 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002259
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002260 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2261 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2262 Py_XDECREF(l);
2263 return NULL;
2264 }
2265 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002266}
2267
2268
Tim Peters59c9a642001-09-13 05:38:56 +00002269static PyObject *
2270file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2271{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002272 PyObject *self;
2273 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002274
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002275 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002276
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002277 if (not_yet_string == NULL) {
2278 not_yet_string = PyString_InternFromString("<uninitialized file>");
2279 if (not_yet_string == NULL)
2280 return NULL;
2281 }
Tim Peters44410012001-09-14 03:26:08 +00002282
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002283 self = type->tp_alloc(type, 0);
2284 if (self != NULL) {
2285 /* Always fill in the name and mode, so that nobody else
2286 needs to special-case NULLs there. */
2287 Py_INCREF(not_yet_string);
2288 ((PyFileObject *)self)->f_name = not_yet_string;
2289 Py_INCREF(not_yet_string);
2290 ((PyFileObject *)self)->f_mode = not_yet_string;
2291 Py_INCREF(Py_None);
2292 ((PyFileObject *)self)->f_encoding = Py_None;
2293 Py_INCREF(Py_None);
2294 ((PyFileObject *)self)->f_errors = Py_None;
2295 ((PyFileObject *)self)->weakreflist = NULL;
2296 ((PyFileObject *)self)->unlocked_count = 0;
2297 }
2298 return self;
Tim Peters44410012001-09-14 03:26:08 +00002299}
2300
2301static int
2302file_init(PyObject *self, PyObject *args, PyObject *kwds)
2303{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002304 PyFileObject *foself = (PyFileObject *)self;
2305 int ret = 0;
2306 static char *kwlist[] = {"name", "mode", "buffering", 0};
2307 char *name = NULL;
2308 char *mode = "r";
2309 int bufsize = -1;
2310 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002311#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002312 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002313#endif
Tim Peters44410012001-09-14 03:26:08 +00002314
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002315 assert(PyFile_Check(self));
2316 if (foself->f_fp != NULL) {
2317 /* Have to close the existing file first. */
2318 PyObject *closeresult = file_close(foself);
2319 if (closeresult == NULL)
2320 return -1;
2321 Py_DECREF(closeresult);
2322 }
Tim Peters59c9a642001-09-13 05:38:56 +00002323
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002324#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002325 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2326 kwlist, &po, &mode, &bufsize)) {
2327 wideargument = 1;
2328 if (fill_file_fields(foself, NULL, po, mode,
2329 fclose) == NULL)
2330 goto Error;
2331 } else {
2332 /* Drop the argument parsing error as narrow
2333 strings are also valid. */
2334 PyErr_Clear();
2335 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002336#endif
2337
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002338 if (!wideargument) {
2339 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002340
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002341 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2342 Py_FileSystemDefaultEncoding,
2343 &name,
2344 &mode, &bufsize))
2345 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002347 /* We parse again to get the name as a PyObject */
2348 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2349 kwlist, &o_name, &mode,
2350 &bufsize))
2351 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002353 if (fill_file_fields(foself, NULL, o_name, mode,
2354 fclose) == NULL)
2355 goto Error;
2356 }
2357 if (open_the_file(foself, name, mode) == NULL)
2358 goto Error;
2359 foself->f_setbuf = NULL;
2360 PyFile_SetBufSize(self, bufsize);
2361 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002362
2363Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002364 ret = -1;
2365 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002366Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002367 PyMem_Free(name); /* free the encoded string */
2368 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002369}
2370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002371PyDoc_VAR(file_doc) =
2372PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002373"file(name[, mode[, buffering]]) -> file object\n"
2374"\n"
2375"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2376"writing or appending. The file will be created if it doesn't exist\n"
2377"when opened for writing or appending; it will be truncated when\n"
2378"opened for writing. Add a 'b' to the mode for binary files.\n"
2379"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2380"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002381"buffered, and larger numbers specify the buffer size. The preferred way\n"
2382"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002383)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002384PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002385"Add a 'U' to mode to open the file for input with universal newline\n"
2386"support. Any line ending in the input file will be seen as a '\\n'\n"
2387"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2388"the value for this attribute is one of None (no newline read yet),\n"
2389"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2390"\n"
2391"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002392);
Tim Peters59c9a642001-09-13 05:38:56 +00002393
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002394PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002395 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2396 "file",
2397 sizeof(PyFileObject),
2398 0,
2399 (destructor)file_dealloc, /* tp_dealloc */
2400 0, /* tp_print */
2401 0, /* tp_getattr */
2402 0, /* tp_setattr */
2403 0, /* tp_compare */
2404 (reprfunc)file_repr, /* tp_repr */
2405 0, /* tp_as_number */
2406 0, /* tp_as_sequence */
2407 0, /* tp_as_mapping */
2408 0, /* tp_hash */
2409 0, /* tp_call */
2410 0, /* tp_str */
2411 PyObject_GenericGetAttr, /* tp_getattro */
2412 /* softspace is writable: we must supply tp_setattro */
2413 PyObject_GenericSetAttr, /* tp_setattro */
2414 0, /* tp_as_buffer */
2415 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2416 file_doc, /* tp_doc */
2417 0, /* tp_traverse */
2418 0, /* tp_clear */
2419 0, /* tp_richcompare */
2420 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2421 (getiterfunc)file_self, /* tp_iter */
2422 (iternextfunc)file_iternext, /* tp_iternext */
2423 file_methods, /* tp_methods */
2424 file_memberlist, /* tp_members */
2425 file_getsetlist, /* tp_getset */
2426 0, /* tp_base */
2427 0, /* tp_dict */
2428 0, /* tp_descr_get */
2429 0, /* tp_descr_set */
2430 0, /* tp_dictoffset */
2431 file_init, /* tp_init */
2432 PyType_GenericAlloc, /* tp_alloc */
2433 file_new, /* tp_new */
2434 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002435};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002436
2437/* Interface for the 'soft space' between print items. */
2438
2439int
Fred Drakefd99de62000-07-09 05:02:18 +00002440PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002442 long oldflag = 0;
2443 if (f == NULL) {
2444 /* Do nothing */
2445 }
2446 else if (PyFile_Check(f)) {
2447 oldflag = ((PyFileObject *)f)->f_softspace;
2448 ((PyFileObject *)f)->f_softspace = newflag;
2449 }
2450 else {
2451 PyObject *v;
2452 v = PyObject_GetAttrString(f, "softspace");
2453 if (v == NULL)
2454 PyErr_Clear();
2455 else {
2456 if (PyInt_Check(v))
2457 oldflag = PyInt_AsLong(v);
2458 assert(oldflag < INT_MAX);
2459 Py_DECREF(v);
2460 }
2461 v = PyInt_FromLong((long)newflag);
2462 if (v == NULL)
2463 PyErr_Clear();
2464 else {
2465 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2466 PyErr_Clear();
2467 Py_DECREF(v);
2468 }
2469 }
2470 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002471}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002472
2473/* Interfaces to write objects/strings to file-like objects */
2474
2475int
Fred Drakefd99de62000-07-09 05:02:18 +00002476PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002477{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002478 PyObject *writer, *value, *args, *result;
2479 if (f == NULL) {
2480 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2481 return -1;
2482 }
2483 else if (PyFile_Check(f)) {
2484 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002485#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002486 PyObject *enc = fobj->f_encoding;
2487 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002488#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002489 if (fobj->f_fp == NULL) {
2490 err_closed();
2491 return -1;
2492 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002493#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002494 if ((flags & Py_PRINT_RAW) &&
2495 PyUnicode_Check(v) && enc != Py_None) {
2496 char *cenc = PyString_AS_STRING(enc);
2497 char *errors = fobj->f_errors == Py_None ?
2498 "strict" : PyString_AS_STRING(fobj->f_errors);
2499 value = PyUnicode_AsEncodedString(v, cenc, errors);
2500 if (value == NULL)
2501 return -1;
2502 } else {
2503 value = v;
2504 Py_INCREF(value);
2505 }
2506 result = file_PyObject_Print(value, fobj, flags);
2507 Py_DECREF(value);
2508 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002509#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002510 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002511#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002512 }
2513 writer = PyObject_GetAttrString(f, "write");
2514 if (writer == NULL)
2515 return -1;
2516 if (flags & Py_PRINT_RAW) {
2517 if (PyUnicode_Check(v)) {
2518 value = v;
2519 Py_INCREF(value);
2520 } else
2521 value = PyObject_Str(v);
2522 }
2523 else
2524 value = PyObject_Repr(v);
2525 if (value == NULL) {
2526 Py_DECREF(writer);
2527 return -1;
2528 }
2529 args = PyTuple_Pack(1, value);
2530 if (args == NULL) {
2531 Py_DECREF(value);
2532 Py_DECREF(writer);
2533 return -1;
2534 }
2535 result = PyEval_CallObject(writer, args);
2536 Py_DECREF(args);
2537 Py_DECREF(value);
2538 Py_DECREF(writer);
2539 if (result == NULL)
2540 return -1;
2541 Py_DECREF(result);
2542 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002543}
2544
Guido van Rossum27a60b11997-05-22 22:25:11 +00002545int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002546PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002547{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002549 if (f == NULL) {
2550 /* Should be caused by a pre-existing error */
2551 if (!PyErr_Occurred())
2552 PyErr_SetString(PyExc_SystemError,
2553 "null file for PyFile_WriteString");
2554 return -1;
2555 }
2556 else if (PyFile_Check(f)) {
2557 PyFileObject *fobj = (PyFileObject *) f;
2558 FILE *fp = PyFile_AsFile(f);
2559 if (fp == NULL) {
2560 err_closed();
2561 return -1;
2562 }
2563 FILE_BEGIN_ALLOW_THREADS(fobj)
2564 fputs(s, fp);
2565 FILE_END_ALLOW_THREADS(fobj)
2566 return 0;
2567 }
2568 else if (!PyErr_Occurred()) {
2569 PyObject *v = PyString_FromString(s);
2570 int err;
2571 if (v == NULL)
2572 return -1;
2573 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2574 Py_DECREF(v);
2575 return err;
2576 }
2577 else
2578 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002579}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002580
2581/* Try to get a file-descriptor from a Python object. If the object
2582 is an integer or long integer, its value is returned. If not, the
2583 object's fileno() method is called if it exists; the method must return
2584 an integer or long integer, which is returned as the file descriptor value.
2585 -1 is returned on failure.
2586*/
2587
2588int PyObject_AsFileDescriptor(PyObject *o)
2589{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002590 int fd;
2591 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002592
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002593 if (PyInt_Check(o)) {
2594 fd = PyInt_AsLong(o);
2595 }
2596 else if (PyLong_Check(o)) {
2597 fd = PyLong_AsLong(o);
2598 }
2599 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2600 {
2601 PyObject *fno = PyEval_CallObject(meth, NULL);
2602 Py_DECREF(meth);
2603 if (fno == NULL)
2604 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002605
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002606 if (PyInt_Check(fno)) {
2607 fd = PyInt_AsLong(fno);
2608 Py_DECREF(fno);
2609 }
2610 else if (PyLong_Check(fno)) {
2611 fd = PyLong_AsLong(fno);
2612 Py_DECREF(fno);
2613 }
2614 else {
2615 PyErr_SetString(PyExc_TypeError,
2616 "fileno() returned a non-integer");
2617 Py_DECREF(fno);
2618 return -1;
2619 }
2620 }
2621 else {
2622 PyErr_SetString(PyExc_TypeError,
2623 "argument must be an int, or have a fileno() method.");
2624 return -1;
2625 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002627 if (fd < 0) {
2628 PyErr_Format(PyExc_ValueError,
2629 "file descriptor cannot be a negative integer (%i)",
2630 fd);
2631 return -1;
2632 }
2633 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002634}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002635
Jack Jansen7b8c7542002-04-14 20:12:41 +00002636/* From here on we need access to the real fgets and fread */
2637#undef fgets
2638#undef fread
2639
2640/*
2641** Py_UniversalNewlineFgets is an fgets variation that understands
2642** all of \r, \n and \r\n conventions.
2643** The stream should be opened in binary mode.
2644** If fobj is NULL the routine always does newline conversion, and
2645** it may peek one char ahead to gobble the second char in \r\n.
2646** If fobj is non-NULL it must be a PyFileObject. In this case there
2647** is no readahead but in stead a flag is used to skip a following
2648** \n on the next read. Also, if the file is open in binary mode
2649** the whole conversion is skipped. Finally, the routine keeps track of
2650** the different types of newlines seen.
2651** Note that we need no error handling: fgets() treats error and eof
2652** identically.
2653*/
2654char *
2655Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2656{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002657 char *p = buf;
2658 int c;
2659 int newlinetypes = 0;
2660 int skipnextlf = 0;
2661 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002662
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002663 if (fobj) {
2664 if (!PyFile_Check(fobj)) {
2665 errno = ENXIO; /* What can you do... */
2666 return NULL;
2667 }
2668 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2669 if ( !univ_newline )
2670 return fgets(buf, n, stream);
2671 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2672 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2673 }
2674 FLOCKFILE(stream);
2675 c = 'x'; /* Shut up gcc warning */
2676 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2677 if (skipnextlf ) {
2678 skipnextlf = 0;
2679 if (c == '\n') {
2680 /* Seeing a \n here with skipnextlf true
2681 ** means we saw a \r before.
2682 */
2683 newlinetypes |= NEWLINE_CRLF;
2684 c = GETC(stream);
2685 if (c == EOF) break;
2686 } else {
2687 /*
2688 ** Note that c == EOF also brings us here,
2689 ** so we're okay if the last char in the file
2690 ** is a CR.
2691 */
2692 newlinetypes |= NEWLINE_CR;
2693 }
2694 }
2695 if (c == '\r') {
2696 /* A \r is translated into a \n, and we skip
2697 ** an adjacent \n, if any. We don't set the
2698 ** newlinetypes flag until we've seen the next char.
2699 */
2700 skipnextlf = 1;
2701 c = '\n';
2702 } else if ( c == '\n') {
2703 newlinetypes |= NEWLINE_LF;
2704 }
2705 *p++ = c;
2706 if (c == '\n') break;
2707 }
2708 if ( c == EOF && skipnextlf )
2709 newlinetypes |= NEWLINE_CR;
2710 FUNLOCKFILE(stream);
2711 *p = '\0';
2712 if (fobj) {
2713 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2714 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2715 } else if ( skipnextlf ) {
2716 /* If we have no file object we cannot save the
2717 ** skipnextlf flag. We have to readahead, which
2718 ** will cause a pause if we're reading from an
2719 ** interactive stream, but that is very unlikely
2720 ** unless we're doing something silly like
2721 ** execfile("/dev/tty").
2722 */
2723 c = GETC(stream);
2724 if ( c != '\n' )
2725 ungetc(c, stream);
2726 }
2727 if (p == buf)
2728 return NULL;
2729 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002730}
2731
2732/*
2733** Py_UniversalNewlineFread is an fread variation that understands
2734** all of \r, \n and \r\n conventions.
2735** The stream should be opened in binary mode.
2736** fobj must be a PyFileObject. In this case there
2737** is no readahead but in stead a flag is used to skip a following
2738** \n on the next read. Also, if the file is open in binary mode
2739** the whole conversion is skipped. Finally, the routine keeps track of
2740** the different types of newlines seen.
2741*/
2742size_t
Tim Peters058b1412002-04-21 07:29:14 +00002743Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002744 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002745{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002746 char *dst = buf;
2747 PyFileObject *f = (PyFileObject *)fobj;
2748 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002749
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002750 assert(buf != NULL);
2751 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002752
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002753 if (!fobj || !PyFile_Check(fobj)) {
2754 errno = ENXIO; /* What can you do... */
2755 return 0;
2756 }
2757 if (!f->f_univ_newline)
2758 return fread(buf, 1, n, stream);
2759 newlinetypes = f->f_newlinetypes;
2760 skipnextlf = f->f_skipnextlf;
2761 /* Invariant: n is the number of bytes remaining to be filled
2762 * in the buffer.
2763 */
2764 while (n) {
2765 size_t nread;
2766 int shortread;
2767 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002768
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002769 nread = fread(dst, 1, n, stream);
2770 assert(nread <= n);
2771 if (nread == 0)
2772 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002773
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002774 n -= nread; /* assuming 1 byte out for each in; will adjust */
2775 shortread = n != 0; /* true iff EOF or error */
2776 while (nread--) {
2777 char c = *src++;
2778 if (c == '\r') {
2779 /* Save as LF and set flag to skip next LF. */
2780 *dst++ = '\n';
2781 skipnextlf = 1;
2782 }
2783 else if (skipnextlf && c == '\n') {
2784 /* Skip LF, and remember we saw CR LF. */
2785 skipnextlf = 0;
2786 newlinetypes |= NEWLINE_CRLF;
2787 ++n;
2788 }
2789 else {
2790 /* Normal char to be stored in buffer. Also
2791 * update the newlinetypes flag if either this
2792 * is an LF or the previous char was a CR.
2793 */
2794 if (c == '\n')
2795 newlinetypes |= NEWLINE_LF;
2796 else if (skipnextlf)
2797 newlinetypes |= NEWLINE_CR;
2798 *dst++ = c;
2799 skipnextlf = 0;
2800 }
2801 }
2802 if (shortread) {
2803 /* If this is EOF, update type flags. */
2804 if (skipnextlf && feof(stream))
2805 newlinetypes |= NEWLINE_CR;
2806 break;
2807 }
2808 }
2809 f->f_newlinetypes = newlinetypes;
2810 f->f_skipnextlf = skipnextlf;
2811 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002812}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002813
2814#ifdef __cplusplus
2815}
2816#endif