blob: 1d8142e17c5982eeb118c69bedbe3c92cbcd81fa [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;
Antoine Pitrou638cee62010-10-28 14:50:57 +0000426 char *local_setbuf = f->f_setbuf;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000427 if (local_fp != NULL) {
428 local_close = f->f_close;
429 if (local_close != NULL && f->unlocked_count > 0) {
430 if (f->ob_refcnt > 0) {
431 PyErr_SetString(PyExc_IOError,
432 "close() called during concurrent "
433 "operation on the same file object.");
434 } else {
435 /* This should not happen unless someone is
436 * carelessly playing with the PyFileObject
437 * struct fields and/or its associated FILE
438 * pointer. */
439 PyErr_SetString(PyExc_SystemError,
440 "PyFileObject locking error in "
441 "destructor (refcnt <= 0 at close).");
442 }
443 return NULL;
444 }
445 /* NULL out the FILE pointer before releasing the GIL, because
446 * it will not be valid anymore after the close() function is
447 * called. */
448 f->f_fp = NULL;
449 if (local_close != NULL) {
Antoine Pitrou638cee62010-10-28 14:50:57 +0000450 /* Issue #9295: must temporarily reset f_setbuf so that another
451 thread doesn't free it when running file_close() concurrently.
452 Otherwise this close() will crash when flushing the buffer. */
453 f->f_setbuf = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000454 Py_BEGIN_ALLOW_THREADS
455 errno = 0;
456 sts = (*local_close)(local_fp);
457 Py_END_ALLOW_THREADS
Antoine Pitrou638cee62010-10-28 14:50:57 +0000458 f->f_setbuf = local_setbuf;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000459 if (sts == EOF)
460 return PyErr_SetFromErrno(PyExc_IOError);
461 if (sts != 0)
462 return PyInt_FromLong((long)sts);
463 }
464 }
465 Py_RETURN_NONE;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000466}
467
Tim Peters59c9a642001-09-13 05:38:56 +0000468PyObject *
469PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
470{
Victor Stinner63c22fa2011-09-23 19:37:03 +0200471 PyFileObject *f;
472 PyObject *o_name;
473
474 f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, NULL, NULL);
475 if (f == NULL)
476 return NULL;
477 o_name = PyString_FromString(name);
478 if (o_name == NULL) {
479 if (close != NULL && fp != NULL)
480 close(fp);
481 Py_DECREF(f);
482 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 }
Victor Stinner63c22fa2011-09-23 19:37:03 +0200484 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
485 Py_DECREF(f);
486 Py_DECREF(o_name);
487 return NULL;
488 }
489 Py_DECREF(o_name);
490 return (PyObject *)f;
Tim Peters59c9a642001-09-13 05:38:56 +0000491}
492
493PyObject *
494PyFile_FromString(char *name, char *mode)
495{
Antoine Pitrou02a38012012-04-05 14:07:52 +0200496 extern int fclose(FILE *);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000497 PyFileObject *f;
Tim Peters59c9a642001-09-13 05:38:56 +0000498
Antoine Pitrou02a38012012-04-05 14:07:52 +0200499 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000500 if (f != NULL) {
501 if (open_the_file(f, name, mode) == NULL) {
502 Py_DECREF(f);
503 f = NULL;
504 }
505 }
506 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000507}
508
Guido van Rossumb6775db1994-08-01 11:34:53 +0000509void
Fred Drakefd99de62000-07-09 05:02:18 +0000510PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000511{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000512 PyFileObject *file = (PyFileObject *)f;
513 if (bufsize >= 0) {
514 int type;
515 switch (bufsize) {
516 case 0:
517 type = _IONBF;
518 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000519#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000520 case 1:
521 type = _IOLBF;
522 bufsize = BUFSIZ;
523 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000524#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000525 default:
526 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000527#ifndef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 bufsize = BUFSIZ;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000529#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000530 break;
531 }
532 fflush(file->f_fp);
533 if (type == _IONBF) {
534 PyMem_Free(file->f_setbuf);
535 file->f_setbuf = NULL;
536 } else {
537 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
538 bufsize);
539 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000540#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000542#else /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000544#endif /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000545 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000546}
547
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000548/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000549 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000550
551int
552PyFile_SetEncoding(PyObject *f, const char *enc)
553{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000554 return PyFile_SetEncodingAndErrors(f, enc, NULL);
Martin v. Löwis99815892008-06-01 07:20:46 +0000555}
556
557int
558PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
559{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000560 PyFileObject *file = (PyFileObject*)f;
561 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000562
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 assert(PyFile_Check(f));
564 str = PyString_FromString(enc);
565 if (!str)
566 return 0;
567 if (errors) {
568 oerrors = PyString_FromString(errors);
569 if (!oerrors) {
570 Py_DECREF(str);
571 return 0;
572 }
573 } else {
574 oerrors = Py_None;
575 Py_INCREF(Py_None);
576 }
577 Py_DECREF(file->f_encoding);
578 file->f_encoding = str;
579 Py_DECREF(file->f_errors);
580 file->f_errors = oerrors;
581 return 1;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000582}
583
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000584static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000585err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000587 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
588 return NULL;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000589}
590
Antoine Pitroubb445a12010-02-05 17:05:54 +0000591static PyObject *
592err_mode(char *action)
593{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000594 PyErr_Format(PyExc_IOError, "File not open for %s", action);
595 return NULL;
Antoine Pitroubb445a12010-02-05 17:05:54 +0000596}
597
Thomas Woutersc45251a2006-02-12 11:53:32 +0000598/* Refuse regular file I/O if there's data in the iteration-buffer.
599 * Mixing them would cause data to arrive out of order, as the read*
600 * methods don't use the iteration buffer. */
601static PyObject *
602err_iterbuffered(void)
603{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000604 PyErr_SetString(PyExc_ValueError,
605 "Mixing iteration and read methods would lose data");
606 return NULL;
Thomas Woutersc45251a2006-02-12 11:53:32 +0000607}
608
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000609static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000610
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611/* Methods */
612
613static void
Fred Drakefd99de62000-07-09 05:02:18 +0000614file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000615{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000616 PyObject *ret;
617 if (f->weakreflist != NULL)
618 PyObject_ClearWeakRefs((PyObject *) f);
619 ret = close_the_file(f);
620 if (!ret) {
621 PySys_WriteStderr("close failed in file object destructor:\n");
622 PyErr_Print();
623 }
624 else {
625 Py_DECREF(ret);
626 }
627 PyMem_Free(f->f_setbuf);
628 Py_XDECREF(f->f_name);
629 Py_XDECREF(f->f_mode);
630 Py_XDECREF(f->f_encoding);
631 Py_XDECREF(f->f_errors);
632 drop_readahead(f);
633 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000634}
635
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000636static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000637file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638{
Ezio Melotti11f8b682012-03-12 01:17:02 +0200639 PyObject *ret = NULL;
640 PyObject *name = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000641 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000642#ifdef Py_USING_UNICODE
Ezio Melottieace3a72012-03-12 01:28:45 +0200643 const char *name_str;
Ezio Melotti11f8b682012-03-12 01:17:02 +0200644 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Ezio Melottieace3a72012-03-12 01:28:45 +0200645 name_str = name ? PyString_AsString(name) : "?";
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000646 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
647 f->f_fp == NULL ? "closed" : "open",
648 name_str,
649 PyString_AsString(f->f_mode),
650 f);
651 Py_XDECREF(name);
652 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000653#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000654 } else {
Ezio Melotti11f8b682012-03-12 01:17:02 +0200655 name = PyObject_Repr(f->f_name);
656 if (name == NULL)
657 return NULL;
658 ret = PyString_FromFormat("<%s file %s, mode '%s' at %p>",
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 f->f_fp == NULL ? "closed" : "open",
Ezio Melotti11f8b682012-03-12 01:17:02 +0200660 PyString_AsString(name),
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000661 PyString_AsString(f->f_mode),
662 f);
Ezio Melotti11f8b682012-03-12 01:17:02 +0200663 Py_XDECREF(name);
664 return ret;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000665 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000666}
667
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000668static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000669file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000670{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000671 PyObject *sts = close_the_file(f);
Antoine Pitrou83137c22010-05-17 19:56:59 +0000672 if (sts) {
673 PyMem_Free(f->f_setbuf);
674 f->f_setbuf = NULL;
675 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000676 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000677}
678
Trent Mickf29f47b2000-08-11 19:02:59 +0000679
Guido van Rossumb8552162001-09-05 14:58:11 +0000680/* Our very own off_t-like type, 64-bit if possible */
681#if !defined(HAVE_LARGEFILE_SUPPORT)
682typedef off_t Py_off_t;
683#elif SIZEOF_OFF_T >= 8
684typedef off_t Py_off_t;
685#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000686typedef fpos_t Py_off_t;
687#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000688#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000689#endif
690
691
Trent Mickf29f47b2000-08-11 19:02:59 +0000692/* a portable fseek() function
693 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000694static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000695_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000696{
Guido van Rossumb8552162001-09-05 14:58:11 +0000697#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000698 return fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000699#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000700 return fseeko(fp, offset, whence);
Trent Mickf29f47b2000-08-11 19:02:59 +0000701#elif defined(HAVE_FSEEK64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000703#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000704 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000705#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
707 and fgetpos() to implement fseek()*/
708 fpos_t pos;
709 switch (whence) {
710 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000711#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000712 fflush(fp);
713 if (_lseeki64(fileno(fp), 0, 2) == -1)
714 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000715#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000716 if (fseek(fp, 0, SEEK_END) != 0)
717 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000718#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000719 /* fall through */
720 case SEEK_CUR:
721 if (fgetpos(fp, &pos) != 0)
722 return -1;
723 offset += pos;
724 break;
725 /* case SEEK_SET: break; */
726 }
727 return fsetpos(fp, &offset);
Trent Mickf29f47b2000-08-11 19:02:59 +0000728#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000729#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000730#endif
731}
732
733
734/* a portable ftell() function
735 Return -1 on failure with errno set appropriately, current file
736 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000737static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000738_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000739{
Guido van Rossumb8552162001-09-05 14:58:11 +0000740#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 return ftell(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000742#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 return ftello(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000744#elif defined(HAVE_FTELL64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 return ftell64(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000746#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000747 fpos_t pos;
748 if (fgetpos(fp, &pos) != 0)
749 return -1;
750 return pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000751#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000752#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000753#endif
754}
755
756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000758file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000760 int whence;
761 int ret;
762 Py_off_t offset;
763 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000764
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000765 if (f->f_fp == NULL)
766 return err_closed();
767 drop_readahead(f);
768 whence = 0;
769 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
770 return NULL;
771 off_index = PyNumber_Index(offobj);
772 if (!off_index) {
773 if (!PyFloat_Check(offobj))
774 return NULL;
775 /* Deprecated in 2.6 */
776 PyErr_Clear();
777 if (PyErr_WarnEx(PyExc_DeprecationWarning,
778 "integer argument expected, got float",
779 1) < 0)
780 return NULL;
781 off_index = offobj;
782 Py_INCREF(offobj);
783 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000784#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000786#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 offset = PyLong_Check(off_index) ?
788 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000789#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 Py_DECREF(off_index);
791 if (PyErr_Occurred())
792 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000793
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000794 FILE_BEGIN_ALLOW_THREADS(f)
795 errno = 0;
796 ret = _portable_fseek(f->f_fp, offset, whence);
797 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000798
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000799 if (ret != 0) {
800 PyErr_SetFromErrno(PyExc_IOError);
801 clearerr(f->f_fp);
802 return NULL;
803 }
804 f->f_skipnextlf = 0;
805 Py_INCREF(Py_None);
806 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000807}
808
Trent Mickf29f47b2000-08-11 19:02:59 +0000809
Guido van Rossumd7047b31995-01-02 19:07:15 +0000810#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000812file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000813{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000814 Py_off_t newsize;
815 PyObject *newsizeobj = NULL;
816 Py_off_t initialpos;
817 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000818
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000819 if (f->f_fp == NULL)
820 return err_closed();
821 if (!f->writable)
822 return err_mode("writing");
823 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
824 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000825
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000826 /* Get current file position. If the file happens to be open for
827 * update and the last operation was an input operation, C doesn't
828 * define what the later fflush() will do, but we promise truncate()
829 * won't change the current position (and fflush() *does* change it
830 * then at least on Windows). The easiest thing is to capture
831 * current pos now and seek back to it at the end.
832 */
833 FILE_BEGIN_ALLOW_THREADS(f)
834 errno = 0;
835 initialpos = _portable_ftell(f->f_fp);
836 FILE_END_ALLOW_THREADS(f)
837 if (initialpos == -1)
838 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000839
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000840 /* Set newsize to current postion if newsizeobj NULL, else to the
841 * specified value.
842 */
843 if (newsizeobj != NULL) {
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000844#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000845 newsize = PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000846#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000847 newsize = PyLong_Check(newsizeobj) ?
848 PyLong_AsLongLong(newsizeobj) :
849 PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000850#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000851 if (PyErr_Occurred())
852 return NULL;
853 }
854 else /* default to current position */
855 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000856
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000857 /* Flush the stream. We're mixing stream-level I/O with lower-level
858 * I/O, and a flush may be necessary to synch both platform views
859 * of the current file state.
860 */
861 FILE_BEGIN_ALLOW_THREADS(f)
862 errno = 0;
863 ret = fflush(f->f_fp);
864 FILE_END_ALLOW_THREADS(f)
865 if (ret != 0)
866 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000867
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000868#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000869 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
870 so don't even try using it. */
871 {
872 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 /* Have to move current pos to desired endpoint on Windows. */
875 FILE_BEGIN_ALLOW_THREADS(f)
876 errno = 0;
877 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
878 FILE_END_ALLOW_THREADS(f)
879 if (ret)
880 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000881
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000882 /* Truncate. Note that this may grow the file! */
883 FILE_BEGIN_ALLOW_THREADS(f)
884 errno = 0;
885 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
886 ret = hFile == (HANDLE)-1;
887 if (ret == 0) {
888 ret = SetEndOfFile(hFile) == 0;
889 if (ret)
890 errno = EACCES;
891 }
892 FILE_END_ALLOW_THREADS(f)
893 if (ret)
894 goto onioerror;
895 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000896#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 FILE_BEGIN_ALLOW_THREADS(f)
898 errno = 0;
899 ret = ftruncate(fileno(f->f_fp), newsize);
900 FILE_END_ALLOW_THREADS(f)
901 if (ret != 0)
902 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000903#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000904
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000905 /* Restore original file position. */
906 FILE_BEGIN_ALLOW_THREADS(f)
907 errno = 0;
908 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
909 FILE_END_ALLOW_THREADS(f)
910 if (ret)
911 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000912
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 Py_INCREF(Py_None);
914 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000915
916onioerror:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000917 PyErr_SetFromErrno(PyExc_IOError);
918 clearerr(f->f_fp);
919 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000920}
921#endif /* HAVE_FTRUNCATE */
922
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000923static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000924file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000927
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 if (f->f_fp == NULL)
929 return err_closed();
930 FILE_BEGIN_ALLOW_THREADS(f)
931 errno = 0;
932 pos = _portable_ftell(f->f_fp);
933 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000934
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000935 if (pos == -1) {
936 PyErr_SetFromErrno(PyExc_IOError);
937 clearerr(f->f_fp);
938 return NULL;
939 }
940 if (f->f_skipnextlf) {
941 int c;
942 c = GETC(f->f_fp);
943 if (c == '\n') {
944 f->f_newlinetypes |= NEWLINE_CRLF;
945 pos++;
946 f->f_skipnextlf = 0;
947 } else if (c != EOF) ungetc(c, f->f_fp);
948 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000949#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000951#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000952 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000953#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000954}
955
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000956static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000957file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000958{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000959 if (f->f_fp == NULL)
960 return err_closed();
961 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000962}
963
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000964static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000965file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000966{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000968
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000969 if (f->f_fp == NULL)
970 return err_closed();
971 FILE_BEGIN_ALLOW_THREADS(f)
972 errno = 0;
973 res = fflush(f->f_fp);
974 FILE_END_ALLOW_THREADS(f)
975 if (res != 0) {
976 PyErr_SetFromErrno(PyExc_IOError);
977 clearerr(f->f_fp);
978 return NULL;
979 }
980 Py_INCREF(Py_None);
981 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000982}
983
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000985file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000986{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000987 long res;
988 if (f->f_fp == NULL)
989 return err_closed();
990 FILE_BEGIN_ALLOW_THREADS(f)
991 res = isatty((int)fileno(f->f_fp));
992 FILE_END_ALLOW_THREADS(f)
993 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000994}
995
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000996
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000997#if BUFSIZ < 8192
998#define SMALLCHUNK 8192
999#else
1000#define SMALLCHUNK BUFSIZ
1001#endif
1002
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001003static size_t
Fred Drakefd99de62000-07-09 05:02:18 +00001004new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001005{
1006#ifdef HAVE_FSTAT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001007 off_t pos, end;
1008 struct stat st;
1009 if (fstat(fileno(f->f_fp), &st) == 0) {
1010 end = st.st_size;
1011 /* The following is not a bug: we really need to call lseek()
1012 *and* ftell(). The reason is that some stdio libraries
1013 mistakenly flush their buffer when ftell() is called and
1014 the lseek() call it makes fails, thereby throwing away
1015 data that cannot be recovered in any way. To avoid this,
1016 we first test lseek(), and only call ftell() if lseek()
1017 works. We can't use the lseek() value either, because we
1018 need to take the amount of buffered data into account.
1019 (Yet another reason why stdio stinks. :-) */
1020 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
1021 if (pos >= 0) {
1022 pos = ftell(f->f_fp);
1023 }
1024 if (pos < 0)
1025 clearerr(f->f_fp);
1026 if (end > pos && pos >= 0)
1027 return currentsize + end - pos + 1;
1028 /* Add 1 so if the file were to grow we'd notice. */
1029 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001030#endif
Nadeem Vawda36248152011-10-13 13:52:46 +02001031 /* Expand the buffer by an amount proportional to the current size,
1032 giving us amortized linear-time behavior. Use a less-than-double
1033 growth factor to avoid excessive allocation. */
1034 return currentsize + (currentsize >> 3) + 6;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001035}
1036
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001037#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1038#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1039#else
1040#ifdef EWOULDBLOCK
1041#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1042#else
1043#ifdef EAGAIN
1044#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1045#else
1046#define BLOCKED_ERRNO(x) 0
1047#endif
1048#endif
1049#endif
1050
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001051static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001052file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001053{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001054 long bytesrequested = -1;
1055 size_t bytesread, buffersize, chunksize;
1056 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001057
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 if (f->f_fp == NULL)
1059 return err_closed();
1060 if (!f->readable)
1061 return err_mode("reading");
1062 /* refuse to mix with f.next() */
1063 if (f->f_buf != NULL &&
1064 (f->f_bufend - f->f_bufptr) > 0 &&
1065 f->f_buf[0] != '\0')
1066 return err_iterbuffered();
1067 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
1068 return NULL;
1069 if (bytesrequested < 0)
1070 buffersize = new_buffersize(f, (size_t)0);
1071 else
1072 buffersize = bytesrequested;
1073 if (buffersize > PY_SSIZE_T_MAX) {
1074 PyErr_SetString(PyExc_OverflowError,
1075 "requested number of bytes is more than a Python string can hold");
1076 return NULL;
1077 }
1078 v = PyString_FromStringAndSize((char *)NULL, buffersize);
1079 if (v == NULL)
1080 return NULL;
1081 bytesread = 0;
1082 for (;;) {
1083 FILE_BEGIN_ALLOW_THREADS(f)
1084 errno = 0;
1085 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
1086 buffersize - bytesread, f->f_fp, (PyObject *)f);
1087 FILE_END_ALLOW_THREADS(f)
1088 if (chunksize == 0) {
1089 if (!ferror(f->f_fp))
1090 break;
1091 clearerr(f->f_fp);
1092 /* When in non-blocking mode, data shouldn't
1093 * be discarded if a blocking signal was
1094 * received. That will also happen if
1095 * chunksize != 0, but bytesread < buffersize. */
1096 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1097 break;
1098 PyErr_SetFromErrno(PyExc_IOError);
1099 Py_DECREF(v);
1100 return NULL;
1101 }
1102 bytesread += chunksize;
1103 if (bytesread < buffersize) {
1104 clearerr(f->f_fp);
1105 break;
1106 }
1107 if (bytesrequested < 0) {
1108 buffersize = new_buffersize(f, buffersize);
1109 if (_PyString_Resize(&v, buffersize) < 0)
1110 return NULL;
1111 } else {
1112 /* Got what was requested. */
1113 break;
1114 }
1115 }
1116 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1117 return NULL;
1118 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001119}
1120
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001121static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001122file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001123{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001124 char *ptr;
1125 Py_ssize_t ntodo;
1126 Py_ssize_t ndone, nnow;
1127 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001129 if (f->f_fp == NULL)
1130 return err_closed();
1131 if (!f->readable)
1132 return err_mode("reading");
1133 /* refuse to mix with f.next() */
1134 if (f->f_buf != NULL &&
1135 (f->f_bufend - f->f_bufptr) > 0 &&
1136 f->f_buf[0] != '\0')
1137 return err_iterbuffered();
1138 if (!PyArg_ParseTuple(args, "w*", &pbuf))
1139 return NULL;
1140 ptr = pbuf.buf;
1141 ntodo = pbuf.len;
1142 ndone = 0;
1143 while (ntodo > 0) {
1144 FILE_BEGIN_ALLOW_THREADS(f)
1145 errno = 0;
1146 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
1147 (PyObject *)f);
1148 FILE_END_ALLOW_THREADS(f)
1149 if (nnow == 0) {
1150 if (!ferror(f->f_fp))
1151 break;
1152 PyErr_SetFromErrno(PyExc_IOError);
1153 clearerr(f->f_fp);
1154 PyBuffer_Release(&pbuf);
1155 return NULL;
1156 }
1157 ndone += nnow;
1158 ntodo -= nnow;
1159 }
1160 PyBuffer_Release(&pbuf);
1161 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001162}
1163
Tim Peters86821b22001-01-07 21:19:34 +00001164/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001165Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001166
1167Under MSVC 6:
1168
Tim Peters1c733232001-01-08 04:02:07 +00001169+ MS threadsafe getc is very slow (multiple layers of function calls before+
1170 after each character, to lock+unlock the stream).
1171+ The stream-locking functions are MS-internal -- can't access them from user
1172 code.
1173+ There's nothing Tim could find in the MS C or platform SDK libraries that
1174 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001175+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1176
1177So we use fgets for speed(!), despite that it's painful.
1178
1179MS realloc is also slow.
1180
Tim Petersf29b64d2001-01-15 06:33:19 +00001181Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1182have):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001183 Linux a wash
1184 Solaris a wash
1185 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001186
Tim Petersf29b64d2001-01-15 06:33:19 +00001187CAUTION: The C std isn't clear about this: in those cases where fgets
1188writes something into the buffer, can it write into any position beyond the
1189required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1190known on which it does; and it would be a strange way to code fgets. Still,
1191getline_via_fgets may not work correctly if it does. The std test
1192test_bufio.py should fail if platform fgets() routinely writes beyond the
1193trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001194**************************************************************************/
1195
Tim Petersf29b64d2001-01-15 06:33:19 +00001196/* Use this routine if told to, or by default on non-get_unlocked()
1197 * platforms unless told not to. Yikes! Let's spell that out:
1198 * On a platform with getc_unlocked():
1199 * By default, use getc_unlocked().
1200 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1201 * On a platform without getc_unlocked():
1202 * By default, use fgets().
1203 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1204 */
1205#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1206#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001207#endif
1208
Tim Petersf29b64d2001-01-15 06:33:19 +00001209#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1210#undef USE_FGETS_IN_GETLINE
1211#endif
1212
1213#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001214static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001215getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001216{
Tim Peters15b83852001-01-08 00:53:12 +00001217/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001218 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1219 * to fill this much of the buffer with a known value in order to figure out
1220 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1221 * than "most" lines, we waste time filling unused buffer slots. 100 is
1222 * surely adequate for most peoples' email archives, chewing over source code,
1223 * etc -- "regular old text files".
1224 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1225 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1226 * cautions about boosting that. 300 was chosen because the worst real-life
1227 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1228 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001229 */
Tim Peters142297a2001-01-15 10:36:56 +00001230#define INITBUFSIZE 100
1231#define MAXBUFSIZE 300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001232 char* p; /* temp */
1233 char buf[MAXBUFSIZE];
1234 PyObject* v; /* the string object result */
1235 char* pvfree; /* address of next free slot */
1236 char* pvend; /* address one beyond last free slot */
1237 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1238 size_t total_v_size; /* total # of slots in buffer */
1239 size_t increment; /* amount to increment the buffer */
1240 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001241
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001242 /* Optimize for normal case: avoid _PyString_Resize if at all
1243 * possible via first reading into stack buffer "buf".
1244 */
1245 total_v_size = INITBUFSIZE; /* start small and pray */
1246 pvfree = buf;
1247 for (;;) {
1248 FILE_BEGIN_ALLOW_THREADS(f)
1249 pvend = buf + total_v_size;
1250 nfree = pvend - pvfree;
1251 memset(pvfree, '\n', nfree);
1252 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1253 p = fgets(pvfree, (int)nfree, fp);
1254 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 if (p == NULL) {
1257 clearerr(fp);
1258 if (PyErr_CheckSignals())
1259 return NULL;
1260 v = PyString_FromStringAndSize(buf, pvfree - buf);
1261 return v;
1262 }
1263 /* fgets read *something* */
1264 p = memchr(pvfree, '\n', nfree);
1265 if (p != NULL) {
1266 /* Did the \n come from fgets or from us?
1267 * Since fgets stops at the first \n, and then writes
1268 * \0, if it's from fgets a \0 must be next. But if
1269 * that's so, it could not have come from us, since
1270 * the \n's we filled the buffer with have only more
1271 * \n's to the right.
1272 */
1273 if (p+1 < pvend && *(p+1) == '\0') {
1274 /* It's from fgets: we win! In particular,
1275 * we haven't done any mallocs yet, and can
1276 * build the final result on the first try.
1277 */
1278 ++p; /* include \n from fgets */
1279 }
1280 else {
1281 /* Must be from us: fgets didn't fill the
1282 * buffer and didn't find a newline, so it
1283 * must be the last and newline-free line of
1284 * the file.
1285 */
1286 assert(p > pvfree && *(p-1) == '\0');
1287 --p; /* don't include \0 from fgets */
1288 }
1289 v = PyString_FromStringAndSize(buf, p - buf);
1290 return v;
1291 }
1292 /* yuck: fgets overwrote all the newlines, i.e. the entire
1293 * buffer. So this line isn't over yet, or maybe it is but
1294 * we're exactly at EOF. If we haven't already, try using the
1295 * rest of the stack buffer.
1296 */
1297 assert(*(pvend-1) == '\0');
1298 if (pvfree == buf) {
1299 pvfree = pvend - 1; /* overwrite trailing null */
1300 total_v_size = MAXBUFSIZE;
1301 }
1302 else
1303 break;
1304 }
Tim Peters142297a2001-01-15 10:36:56 +00001305
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001306 /* The stack buffer isn't big enough; malloc a string object and read
1307 * into its buffer.
1308 */
1309 total_v_size = MAXBUFSIZE << 1;
1310 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
1311 if (v == NULL)
1312 return v;
1313 /* copy over everything except the last null byte */
1314 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1315 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001316
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001317 /* Keep reading stuff into v; if it ever ends successfully, break
1318 * after setting p one beyond the end of the line. The code here is
1319 * very much like the code above, except reads into v's buffer; see
1320 * the code above for detailed comments about the logic.
1321 */
1322 for (;;) {
1323 FILE_BEGIN_ALLOW_THREADS(f)
1324 pvend = BUF(v) + total_v_size;
1325 nfree = pvend - pvfree;
1326 memset(pvfree, '\n', nfree);
1327 assert(nfree < INT_MAX);
1328 p = fgets(pvfree, (int)nfree, fp);
1329 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001330
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001331 if (p == NULL) {
1332 clearerr(fp);
1333 if (PyErr_CheckSignals()) {
1334 Py_DECREF(v);
1335 return NULL;
1336 }
1337 p = pvfree;
1338 break;
1339 }
1340 p = memchr(pvfree, '\n', nfree);
1341 if (p != NULL) {
1342 if (p+1 < pvend && *(p+1) == '\0') {
1343 /* \n came from fgets */
1344 ++p;
1345 break;
1346 }
1347 /* \n came from us; last line of file, no newline */
1348 assert(p > pvfree && *(p-1) == '\0');
1349 --p;
1350 break;
1351 }
1352 /* expand buffer and try again */
1353 assert(*(pvend-1) == '\0');
1354 increment = total_v_size >> 2; /* mild exponential growth */
1355 prev_v_size = total_v_size;
1356 total_v_size += increment;
1357 /* check for overflow */
1358 if (total_v_size <= prev_v_size ||
1359 total_v_size > PY_SSIZE_T_MAX) {
1360 PyErr_SetString(PyExc_OverflowError,
1361 "line is longer than a Python string can hold");
1362 Py_DECREF(v);
1363 return NULL;
1364 }
1365 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1366 return NULL;
1367 /* overwrite the trailing null byte */
1368 pvfree = BUF(v) + (prev_v_size - 1);
1369 }
1370 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1371 return NULL;
1372 return v;
Tim Peters86821b22001-01-07 21:19:34 +00001373#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001374#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001375}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001376#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001377
Guido van Rossum0bd24411991-04-04 15:21:57 +00001378/* Internal routine to get a line.
1379 Size argument interpretation:
1380 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001381 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001382*/
1383
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001384static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001385get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001386{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001387 FILE *fp = f->f_fp;
1388 int c;
1389 char *buf, *end;
1390 size_t total_v_size; /* total # of slots in buffer */
1391 size_t used_v_size; /* # used slots in buffer */
1392 size_t increment; /* amount to increment the buffer */
1393 PyObject *v;
1394 int newlinetypes = f->f_newlinetypes;
1395 int skipnextlf = f->f_skipnextlf;
1396 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001397
Jack Jansen7b8c7542002-04-14 20:12:41 +00001398#if defined(USE_FGETS_IN_GETLINE)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001399 if (n <= 0 && !univ_newline )
1400 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001401#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001402 total_v_size = n > 0 ? n : 100;
1403 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
1404 if (v == NULL)
1405 return NULL;
1406 buf = BUF(v);
1407 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001408
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001409 for (;;) {
1410 FILE_BEGIN_ALLOW_THREADS(f)
1411 FLOCKFILE(fp);
1412 if (univ_newline) {
1413 c = 'x'; /* Shut up gcc warning */
1414 while ( buf != end && (c = GETC(fp)) != EOF ) {
1415 if (skipnextlf ) {
1416 skipnextlf = 0;
1417 if (c == '\n') {
1418 /* Seeing a \n here with
1419 * skipnextlf true means we
1420 * saw a \r before.
1421 */
1422 newlinetypes |= NEWLINE_CRLF;
1423 c = GETC(fp);
1424 if (c == EOF) break;
1425 } else {
1426 newlinetypes |= NEWLINE_CR;
1427 }
1428 }
1429 if (c == '\r') {
1430 skipnextlf = 1;
1431 c = '\n';
1432 } else if ( c == '\n')
1433 newlinetypes |= NEWLINE_LF;
1434 *buf++ = c;
1435 if (c == '\n') break;
1436 }
1437 if ( c == EOF && skipnextlf )
1438 newlinetypes |= NEWLINE_CR;
1439 } else /* If not universal newlines use the normal loop */
1440 while ((c = GETC(fp)) != EOF &&
1441 (*buf++ = c) != '\n' &&
1442 buf != end)
1443 ;
1444 FUNLOCKFILE(fp);
1445 FILE_END_ALLOW_THREADS(f)
1446 f->f_newlinetypes = newlinetypes;
1447 f->f_skipnextlf = skipnextlf;
1448 if (c == '\n')
1449 break;
1450 if (c == EOF) {
1451 if (ferror(fp)) {
1452 PyErr_SetFromErrno(PyExc_IOError);
1453 clearerr(fp);
1454 Py_DECREF(v);
1455 return NULL;
1456 }
1457 clearerr(fp);
1458 if (PyErr_CheckSignals()) {
1459 Py_DECREF(v);
1460 return NULL;
1461 }
1462 break;
1463 }
1464 /* Must be because buf == end */
1465 if (n > 0)
1466 break;
1467 used_v_size = total_v_size;
1468 increment = total_v_size >> 2; /* mild exponential growth */
1469 total_v_size += increment;
1470 if (total_v_size > PY_SSIZE_T_MAX) {
1471 PyErr_SetString(PyExc_OverflowError,
1472 "line is longer than a Python string can hold");
1473 Py_DECREF(v);
1474 return NULL;
1475 }
1476 if (_PyString_Resize(&v, total_v_size) < 0)
1477 return NULL;
1478 buf = BUF(v) + used_v_size;
1479 end = BUF(v) + total_v_size;
1480 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001481
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001482 used_v_size = buf - BUF(v);
1483 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1484 return NULL;
1485 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001486}
1487
Guido van Rossum0bd24411991-04-04 15:21:57 +00001488/* External C interface */
1489
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001491PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001492{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001493 PyObject *result;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001494
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001495 if (f == NULL) {
1496 PyErr_BadInternalCall();
1497 return NULL;
1498 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 if (PyFile_Check(f)) {
1501 PyFileObject *fo = (PyFileObject *)f;
1502 if (fo->f_fp == NULL)
1503 return err_closed();
1504 if (!fo->readable)
1505 return err_mode("reading");
1506 /* refuse to mix with f.next() */
1507 if (fo->f_buf != NULL &&
1508 (fo->f_bufend - fo->f_bufptr) > 0 &&
1509 fo->f_buf[0] != '\0')
1510 return err_iterbuffered();
1511 result = get_line(fo, n);
1512 }
1513 else {
1514 PyObject *reader;
1515 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001516
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001517 reader = PyObject_GetAttrString(f, "readline");
1518 if (reader == NULL)
1519 return NULL;
1520 if (n <= 0)
1521 args = PyTuple_New(0);
1522 else
1523 args = Py_BuildValue("(i)", n);
1524 if (args == NULL) {
1525 Py_DECREF(reader);
1526 return NULL;
1527 }
1528 result = PyEval_CallObject(reader, args);
1529 Py_DECREF(reader);
1530 Py_DECREF(args);
1531 if (result != NULL && !PyString_Check(result) &&
1532 !PyUnicode_Check(result)) {
1533 Py_DECREF(result);
1534 result = NULL;
1535 PyErr_SetString(PyExc_TypeError,
1536 "object.readline() returned non-string");
1537 }
1538 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001539
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001540 if (n < 0 && result != NULL && PyString_Check(result)) {
1541 char *s = PyString_AS_STRING(result);
1542 Py_ssize_t len = PyString_GET_SIZE(result);
1543 if (len == 0) {
1544 Py_DECREF(result);
1545 result = NULL;
1546 PyErr_SetString(PyExc_EOFError,
1547 "EOF when reading a line");
1548 }
1549 else if (s[len-1] == '\n') {
1550 if (result->ob_refcnt == 1) {
1551 if (_PyString_Resize(&result, len-1))
1552 return NULL;
1553 }
1554 else {
1555 PyObject *v;
1556 v = PyString_FromStringAndSize(s, len-1);
1557 Py_DECREF(result);
1558 result = v;
1559 }
1560 }
1561 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001562#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001563 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1564 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1565 Py_ssize_t len = PyUnicode_GET_SIZE(result);
1566 if (len == 0) {
1567 Py_DECREF(result);
1568 result = NULL;
1569 PyErr_SetString(PyExc_EOFError,
1570 "EOF when reading a line");
1571 }
1572 else if (s[len-1] == '\n') {
1573 if (result->ob_refcnt == 1)
1574 PyUnicode_Resize(&result, len-1);
1575 else {
1576 PyObject *v;
1577 v = PyUnicode_FromUnicode(s, len-1);
1578 Py_DECREF(result);
1579 result = v;
1580 }
1581 }
1582 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001583#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001584 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001585}
1586
1587/* Python method */
1588
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001589static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001590file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001591{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001592 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001593
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001594 if (f->f_fp == NULL)
1595 return err_closed();
1596 if (!f->readable)
1597 return err_mode("reading");
1598 /* refuse to mix with f.next() */
1599 if (f->f_buf != NULL &&
1600 (f->f_bufend - f->f_bufptr) > 0 &&
1601 f->f_buf[0] != '\0')
1602 return err_iterbuffered();
1603 if (!PyArg_ParseTuple(args, "|i:readline", &n))
1604 return NULL;
1605 if (n == 0)
1606 return PyString_FromString("");
1607 if (n < 0)
1608 n = 0;
1609 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001610}
1611
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001612static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001613file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001614{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001615 long sizehint = 0;
1616 PyObject *list = NULL;
1617 PyObject *line;
1618 char small_buffer[SMALLCHUNK];
1619 char *buffer = small_buffer;
1620 size_t buffersize = SMALLCHUNK;
1621 PyObject *big_buffer = NULL;
1622 size_t nfilled = 0;
1623 size_t nread;
1624 size_t totalread = 0;
1625 char *p, *q, *end;
1626 int err;
1627 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001628
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001629 if (f->f_fp == NULL)
1630 return err_closed();
1631 if (!f->readable)
1632 return err_mode("reading");
1633 /* refuse to mix with f.next() */
1634 if (f->f_buf != NULL &&
1635 (f->f_bufend - f->f_bufptr) > 0 &&
1636 f->f_buf[0] != '\0')
1637 return err_iterbuffered();
1638 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
1639 return NULL;
1640 if ((list = PyList_New(0)) == NULL)
1641 return NULL;
1642 for (;;) {
1643 if (shortread)
1644 nread = 0;
1645 else {
1646 FILE_BEGIN_ALLOW_THREADS(f)
1647 errno = 0;
1648 nread = Py_UniversalNewlineFread(buffer+nfilled,
1649 buffersize-nfilled, f->f_fp, (PyObject *)f);
1650 FILE_END_ALLOW_THREADS(f)
1651 shortread = (nread < buffersize-nfilled);
1652 }
1653 if (nread == 0) {
1654 sizehint = 0;
1655 if (!ferror(f->f_fp))
1656 break;
1657 PyErr_SetFromErrno(PyExc_IOError);
1658 clearerr(f->f_fp);
1659 goto error;
1660 }
1661 totalread += nread;
1662 p = (char *)memchr(buffer+nfilled, '\n', nread);
1663 if (p == NULL) {
1664 /* Need a larger buffer to fit this line */
1665 nfilled += nread;
1666 buffersize *= 2;
1667 if (buffersize > PY_SSIZE_T_MAX) {
1668 PyErr_SetString(PyExc_OverflowError,
1669 "line is longer than a Python string can hold");
1670 goto error;
1671 }
1672 if (big_buffer == NULL) {
1673 /* Create the big buffer */
1674 big_buffer = PyString_FromStringAndSize(
1675 NULL, buffersize);
1676 if (big_buffer == NULL)
1677 goto error;
1678 buffer = PyString_AS_STRING(big_buffer);
1679 memcpy(buffer, small_buffer, nfilled);
1680 }
1681 else {
1682 /* Grow the big buffer */
1683 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1684 goto error;
1685 buffer = PyString_AS_STRING(big_buffer);
1686 }
1687 continue;
1688 }
1689 end = buffer+nfilled+nread;
1690 q = buffer;
1691 do {
1692 /* Process complete lines */
1693 p++;
1694 line = PyString_FromStringAndSize(q, p-q);
1695 if (line == NULL)
1696 goto error;
1697 err = PyList_Append(list, line);
1698 Py_DECREF(line);
1699 if (err != 0)
1700 goto error;
1701 q = p;
1702 p = (char *)memchr(q, '\n', end-q);
1703 } while (p != NULL);
1704 /* Move the remaining incomplete line to the start */
1705 nfilled = end-q;
1706 memmove(buffer, q, nfilled);
1707 if (sizehint > 0)
1708 if (totalread >= (size_t)sizehint)
1709 break;
1710 }
1711 if (nfilled != 0) {
1712 /* Partial last line */
1713 line = PyString_FromStringAndSize(buffer, nfilled);
1714 if (line == NULL)
1715 goto error;
1716 if (sizehint > 0) {
1717 /* Need to complete the last line */
1718 PyObject *rest = get_line(f, 0);
1719 if (rest == NULL) {
1720 Py_DECREF(line);
1721 goto error;
1722 }
1723 PyString_Concat(&line, rest);
1724 Py_DECREF(rest);
1725 if (line == NULL)
1726 goto error;
1727 }
1728 err = PyList_Append(list, line);
1729 Py_DECREF(line);
1730 if (err != 0)
1731 goto error;
1732 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001733
1734cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001735 Py_XDECREF(big_buffer);
1736 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001737
1738error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001739 Py_CLEAR(list);
1740 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001741}
1742
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001743static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001744file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001745{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001746 Py_buffer pbuf;
Victor Stinnercaafd772010-09-08 10:51:01 +00001747 const char *s;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001748 Py_ssize_t n, n2;
Victor Stinnercaafd772010-09-08 10:51:01 +00001749 PyObject *encoded = NULL;
1750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001751 if (f->f_fp == NULL)
1752 return err_closed();
1753 if (!f->writable)
1754 return err_mode("writing");
1755 if (f->f_binary) {
1756 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1757 return NULL;
1758 s = pbuf.buf;
1759 n = pbuf.len;
Victor Stinnercaafd772010-09-08 10:51:01 +00001760 }
1761 else {
1762 const char *encoding, *errors;
1763 PyObject *text;
1764 if (!PyArg_ParseTuple(args, "O", &text))
1765 return NULL;
1766
1767 if (PyString_Check(text)) {
1768 s = PyString_AS_STRING(text);
1769 n = PyString_GET_SIZE(text);
1770 } else if (PyUnicode_Check(text)) {
1771 if (f->f_encoding != Py_None)
1772 encoding = PyString_AS_STRING(f->f_encoding);
1773 else
1774 encoding = PyUnicode_GetDefaultEncoding();
1775 if (f->f_errors != Py_None)
1776 errors = PyString_AS_STRING(f->f_errors);
1777 else
1778 errors = "strict";
1779 encoded = PyUnicode_AsEncodedString(text, encoding, errors);
1780 if (encoded == NULL)
1781 return NULL;
1782 s = PyString_AS_STRING(encoded);
1783 n = PyString_GET_SIZE(encoded);
1784 } else {
1785 if (PyObject_AsCharBuffer(text, &s, &n))
1786 return NULL;
1787 }
1788 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001789 f->f_softspace = 0;
1790 FILE_BEGIN_ALLOW_THREADS(f)
1791 errno = 0;
1792 n2 = fwrite(s, 1, n, f->f_fp);
1793 FILE_END_ALLOW_THREADS(f)
Victor Stinnercaafd772010-09-08 10:51:01 +00001794 Py_XDECREF(encoded);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001795 if (f->f_binary)
1796 PyBuffer_Release(&pbuf);
1797 if (n2 != n) {
1798 PyErr_SetFromErrno(PyExc_IOError);
1799 clearerr(f->f_fp);
1800 return NULL;
1801 }
1802 Py_INCREF(Py_None);
1803 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001804}
1805
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001806static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001807file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001808{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001809#define CHUNKSIZE 1000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001810 PyObject *list, *line;
1811 PyObject *it; /* iter(seq) */
1812 PyObject *result;
1813 int index, islist;
1814 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001815
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 assert(seq != NULL);
1817 if (f->f_fp == NULL)
1818 return err_closed();
1819 if (!f->writable)
1820 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001821
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001822 result = NULL;
1823 list = NULL;
1824 islist = PyList_Check(seq);
1825 if (islist)
1826 it = NULL;
1827 else {
1828 it = PyObject_GetIter(seq);
1829 if (it == NULL) {
1830 PyErr_SetString(PyExc_TypeError,
1831 "writelines() requires an iterable argument");
1832 return NULL;
1833 }
1834 /* From here on, fail by going to error, to reclaim "it". */
1835 list = PyList_New(CHUNKSIZE);
1836 if (list == NULL)
1837 goto error;
1838 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001839
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001840 /* Strategy: slurp CHUNKSIZE lines into a private list,
1841 checking that they are all strings, then write that list
1842 without holding the interpreter lock, then come back for more. */
1843 for (index = 0; ; index += CHUNKSIZE) {
1844 if (islist) {
1845 Py_XDECREF(list);
1846 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
1847 if (list == NULL)
1848 goto error;
1849 j = PyList_GET_SIZE(list);
1850 }
1851 else {
1852 for (j = 0; j < CHUNKSIZE; j++) {
1853 line = PyIter_Next(it);
1854 if (line == NULL) {
1855 if (PyErr_Occurred())
1856 goto error;
1857 break;
1858 }
1859 PyList_SetItem(list, j, line);
1860 }
Benjamin Petersonbf775542010-10-16 19:20:12 +00001861 /* The iterator might have closed the file on us. */
1862 if (f->f_fp == NULL) {
1863 err_closed();
1864 goto error;
1865 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001866 }
1867 if (j == 0)
1868 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001869
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001870 /* Check that all entries are indeed strings. If not,
1871 apply the same rules as for file.write() and
1872 convert the results to strings. This is slow, but
1873 seems to be the only way since all conversion APIs
1874 could potentially execute Python code. */
1875 for (i = 0; i < j; i++) {
1876 PyObject *v = PyList_GET_ITEM(list, i);
1877 if (!PyString_Check(v)) {
1878 const char *buffer;
1879 if (((f->f_binary &&
1880 PyObject_AsReadBuffer(v,
1881 (const void**)&buffer,
1882 &len)) ||
1883 PyObject_AsCharBuffer(v,
1884 &buffer,
1885 &len))) {
1886 PyErr_SetString(PyExc_TypeError,
1887 "writelines() argument must be a sequence of strings");
1888 goto error;
1889 }
1890 line = PyString_FromStringAndSize(buffer,
1891 len);
1892 if (line == NULL)
1893 goto error;
1894 Py_DECREF(v);
1895 PyList_SET_ITEM(list, i, line);
1896 }
1897 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001898
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001899 /* Since we are releasing the global lock, the
1900 following code may *not* execute Python code. */
1901 f->f_softspace = 0;
1902 FILE_BEGIN_ALLOW_THREADS(f)
1903 errno = 0;
1904 for (i = 0; i < j; i++) {
1905 line = PyList_GET_ITEM(list, i);
1906 len = PyString_GET_SIZE(line);
1907 nwritten = fwrite(PyString_AS_STRING(line),
1908 1, len, f->f_fp);
1909 if (nwritten != len) {
1910 FILE_ABORT_ALLOW_THREADS(f)
1911 PyErr_SetFromErrno(PyExc_IOError);
1912 clearerr(f->f_fp);
1913 goto error;
1914 }
1915 }
1916 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001918 if (j < CHUNKSIZE)
1919 break;
1920 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001921
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001922 Py_INCREF(Py_None);
1923 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001924 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001925 Py_XDECREF(list);
1926 Py_XDECREF(it);
1927 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001928#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001929}
1930
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001931static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001932file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001933{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001934 if (f->f_fp == NULL)
1935 return err_closed();
1936 Py_INCREF(f);
1937 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001938}
1939
Georg Brandl98b40ad2006-06-08 14:50:21 +00001940static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001941file_xreadlines(PyFileObject *f)
1942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001943 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1944 "try 'for line in f' instead", 1) < 0)
1945 return NULL;
1946 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00001947}
1948
1949static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001950file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001951{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001952 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
1953 if (!ret)
1954 /* If error occurred, pass through */
1955 return NULL;
1956 Py_DECREF(ret);
1957 /* We cannot return the result of close since a true
1958 * value will be interpreted as "yes, swallow the
1959 * exception if one was raised inside the with block". */
1960 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00001961}
1962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001963PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001964"readline([size]) -> next line from the file, as a string.\n"
1965"\n"
1966"Retain newline. A non-negative size argument limits the maximum\n"
1967"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001968"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001970PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001971"read([size]) -> read at most size bytes, returned as a string.\n"
1972"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001973"If the size argument is negative or omitted, read until EOF is reached.\n"
1974"Notice that when in non-blocking mode, less data than what was requested\n"
1975"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001976
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001977PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001978"write(str) -> None. Write string str to file.\n"
1979"\n"
1980"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001981"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001982
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001983PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001984"fileno() -> integer \"file descriptor\".\n"
1985"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001987
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001988PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001989"seek(offset[, whence]) -> None. Move to new file position.\n"
1990"\n"
1991"Argument offset is a byte count. Optional argument whence defaults to\n"
1992"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1993"(move relative to current position, positive or negative), and 2 (move\n"
1994"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001995"seeking beyond the end of a file). If the file is opened in text mode,\n"
1996"only offsets returned by tell() are legal. Use of other offsets causes\n"
1997"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001998"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001999"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002000
Guido van Rossumd7047b31995-01-02 19:07:15 +00002001#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002002PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002003"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
2004"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002005"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00002006#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00002007
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002008PyDoc_STRVAR(tell_doc,
2009"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002010
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002011PyDoc_STRVAR(readinto_doc,
2012"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002014PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002015"readlines([size]) -> list of strings, each a line from the file.\n"
2016"\n"
2017"Call readline() repeatedly and return a list of the lines so read.\n"
2018"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002019"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002021PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002022"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002023"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002024"For backward compatibility. File objects now include the performance\n"
2025"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002026
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002028"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002029"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002030"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002032
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002033PyDoc_STRVAR(flush_doc,
2034"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002036PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002037"close() -> None or (perhaps) an integer. Close the file.\n"
2038"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00002039"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002040"further I/O operations. close() may be called more than once without\n"
2041"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002042"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002043
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002044PyDoc_STRVAR(isatty_doc,
2045"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002046
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002047PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002048 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002049
Georg Brandl98b40ad2006-06-08 14:50:21 +00002050PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002051 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002052
Tim Petersefc3a3a2001-09-20 07:55:22 +00002053static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002054 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2055 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2056 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2057 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2058 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002059#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002060 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002061#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002062 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2063 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2064 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2065 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2066 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2067 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2068 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2069 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2070 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2071 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2072 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002073};
2074
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002075#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002076
Guido van Rossum6f799372001-09-20 20:46:19 +00002077static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002078 {"mode", T_OBJECT, OFF(f_mode), RO,
2079 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2080 {"name", T_OBJECT, OFF(f_name), RO,
2081 "file name"},
2082 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2083 "file encoding"},
2084 {"errors", T_OBJECT, OFF(f_errors), RO,
2085 "Unicode error handler"},
2086 /* getattr(f, "closed") is implemented without this table */
2087 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002088};
2089
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002090static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002092{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002093 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002094}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002095static PyObject *
2096get_newlines(PyFileObject *f, void *closure)
2097{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002098 switch (f->f_newlinetypes) {
2099 case NEWLINE_UNKNOWN:
2100 Py_INCREF(Py_None);
2101 return Py_None;
2102 case NEWLINE_CR:
2103 return PyString_FromString("\r");
2104 case NEWLINE_LF:
2105 return PyString_FromString("\n");
2106 case NEWLINE_CR|NEWLINE_LF:
2107 return Py_BuildValue("(ss)", "\r", "\n");
2108 case NEWLINE_CRLF:
2109 return PyString_FromString("\r\n");
2110 case NEWLINE_CR|NEWLINE_CRLF:
2111 return Py_BuildValue("(ss)", "\r", "\r\n");
2112 case NEWLINE_LF|NEWLINE_CRLF:
2113 return Py_BuildValue("(ss)", "\n", "\r\n");
2114 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2115 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2116 default:
2117 PyErr_Format(PyExc_SystemError,
2118 "Unknown newlines value 0x%x\n",
2119 f->f_newlinetypes);
2120 return NULL;
2121 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002122}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002123
Georg Brandl65bb42d2008-03-21 20:38:24 +00002124static PyObject *
2125get_softspace(PyFileObject *f, void *closure)
2126{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002127 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2128 return NULL;
2129 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002130}
2131
2132static int
2133set_softspace(PyFileObject *f, PyObject *value)
2134{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002135 int new;
2136 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2137 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002138
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002139 if (value == NULL) {
2140 PyErr_SetString(PyExc_TypeError,
2141 "can't delete softspace attribute");
2142 return -1;
2143 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002144
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002145 new = PyInt_AsLong(value);
2146 if (new == -1 && PyErr_Occurred())
2147 return -1;
2148 f->f_softspace = new;
2149 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002150}
2151
Guido van Rossum32d34c82001-09-20 21:45:26 +00002152static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002153 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2154 {"newlines", (getter)get_newlines, NULL,
2155 "end-of-line convention used in this file"},
2156 {"softspace", (getter)get_softspace, (setter)set_softspace,
2157 "flag indicating that a space needs to be printed; used by print"},
2158 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002159};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002160
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002161static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002162drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002163{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002164 if (f->f_buf != NULL) {
2165 PyMem_Free(f->f_buf);
2166 f->f_buf = NULL;
2167 }
Guido van Rossum65967252001-04-21 13:20:18 +00002168}
2169
Tim Petersf1827cf2003-09-07 03:30:18 +00002170/* Make sure that file has a readahead buffer with at least one byte
2171 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002172 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002173static int
2174readahead(PyFileObject *f, int bufsize)
2175{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002176 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002177
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002178 if (f->f_buf != NULL) {
2179 if( (f->f_bufend - f->f_bufptr) >= 1)
2180 return 0;
2181 else
2182 drop_readahead(f);
2183 }
2184 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
2185 PyErr_NoMemory();
2186 return -1;
2187 }
2188 FILE_BEGIN_ALLOW_THREADS(f)
2189 errno = 0;
2190 chunksize = Py_UniversalNewlineFread(
2191 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
2192 FILE_END_ALLOW_THREADS(f)
2193 if (chunksize == 0) {
2194 if (ferror(f->f_fp)) {
2195 PyErr_SetFromErrno(PyExc_IOError);
2196 clearerr(f->f_fp);
2197 drop_readahead(f);
2198 return -1;
2199 }
2200 }
2201 f->f_bufptr = f->f_buf;
2202 f->f_bufend = f->f_buf + chunksize;
2203 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002204}
2205
2206/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002207 uninitialized bytes followed by the remainder of the line. Don't be
2208 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002209 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2210
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002211static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002212readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2213{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002214 PyStringObject* s;
2215 char *bufptr;
2216 char *buf;
2217 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002218
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002219 if (f->f_buf == NULL)
2220 if (readahead(f, bufsize) < 0)
2221 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002223 len = f->f_bufend - f->f_bufptr;
2224 if (len == 0)
2225 return (PyStringObject *)
2226 PyString_FromStringAndSize(NULL, skip);
2227 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
2228 if (bufptr != NULL) {
2229 bufptr++; /* Count the '\n' */
2230 len = bufptr - f->f_bufptr;
2231 s = (PyStringObject *)
2232 PyString_FromStringAndSize(NULL, skip+len);
2233 if (s == NULL)
2234 return NULL;
2235 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2236 f->f_bufptr = bufptr;
2237 if (bufptr == f->f_bufend)
2238 drop_readahead(f);
2239 } else {
2240 bufptr = f->f_bufptr;
2241 buf = f->f_buf;
2242 f->f_buf = NULL; /* Force new readahead buffer */
2243 assert(skip+len < INT_MAX);
2244 s = readahead_get_line_skip(
2245 f, (int)(skip+len), bufsize + (bufsize>>2) );
2246 if (s == NULL) {
2247 PyMem_Free(buf);
2248 return NULL;
2249 }
2250 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2251 PyMem_Free(buf);
2252 }
2253 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002254}
2255
2256/* A larger buffer size may actually decrease performance. */
2257#define READAHEAD_BUFSIZE 8192
2258
2259static PyObject *
2260file_iternext(PyFileObject *f)
2261{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002262 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002263
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002264 if (f->f_fp == NULL)
2265 return err_closed();
2266 if (!f->readable)
2267 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002268
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002269 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2270 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2271 Py_XDECREF(l);
2272 return NULL;
2273 }
2274 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002275}
2276
2277
Tim Peters59c9a642001-09-13 05:38:56 +00002278static PyObject *
2279file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2280{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002281 PyObject *self;
2282 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002283
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002284 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002285
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002286 if (not_yet_string == NULL) {
2287 not_yet_string = PyString_InternFromString("<uninitialized file>");
2288 if (not_yet_string == NULL)
2289 return NULL;
2290 }
Tim Peters44410012001-09-14 03:26:08 +00002291
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002292 self = type->tp_alloc(type, 0);
2293 if (self != NULL) {
2294 /* Always fill in the name and mode, so that nobody else
2295 needs to special-case NULLs there. */
2296 Py_INCREF(not_yet_string);
2297 ((PyFileObject *)self)->f_name = not_yet_string;
2298 Py_INCREF(not_yet_string);
2299 ((PyFileObject *)self)->f_mode = not_yet_string;
2300 Py_INCREF(Py_None);
2301 ((PyFileObject *)self)->f_encoding = Py_None;
2302 Py_INCREF(Py_None);
2303 ((PyFileObject *)self)->f_errors = Py_None;
2304 ((PyFileObject *)self)->weakreflist = NULL;
2305 ((PyFileObject *)self)->unlocked_count = 0;
2306 }
2307 return self;
Tim Peters44410012001-09-14 03:26:08 +00002308}
2309
2310static int
2311file_init(PyObject *self, PyObject *args, PyObject *kwds)
2312{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 PyFileObject *foself = (PyFileObject *)self;
2314 int ret = 0;
2315 static char *kwlist[] = {"name", "mode", "buffering", 0};
2316 char *name = NULL;
2317 char *mode = "r";
2318 int bufsize = -1;
2319 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002320#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002322#endif
Tim Peters44410012001-09-14 03:26:08 +00002323
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002324 assert(PyFile_Check(self));
2325 if (foself->f_fp != NULL) {
2326 /* Have to close the existing file first. */
2327 PyObject *closeresult = file_close(foself);
2328 if (closeresult == NULL)
2329 return -1;
2330 Py_DECREF(closeresult);
2331 }
Tim Peters59c9a642001-09-13 05:38:56 +00002332
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002333#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002334 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2335 kwlist, &po, &mode, &bufsize)) {
2336 wideargument = 1;
2337 if (fill_file_fields(foself, NULL, po, mode,
2338 fclose) == NULL)
2339 goto Error;
2340 } else {
2341 /* Drop the argument parsing error as narrow
2342 strings are also valid. */
2343 PyErr_Clear();
2344 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002345#endif
2346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002347 if (!wideargument) {
2348 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002350 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2351 Py_FileSystemDefaultEncoding,
2352 &name,
2353 &mode, &bufsize))
2354 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002356 /* We parse again to get the name as a PyObject */
2357 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2358 kwlist, &o_name, &mode,
2359 &bufsize))
2360 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002361
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002362 if (fill_file_fields(foself, NULL, o_name, mode,
2363 fclose) == NULL)
2364 goto Error;
2365 }
2366 if (open_the_file(foself, name, mode) == NULL)
2367 goto Error;
2368 foself->f_setbuf = NULL;
2369 PyFile_SetBufSize(self, bufsize);
2370 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002371
2372Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002373 ret = -1;
2374 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002375Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 PyMem_Free(name); /* free the encoded string */
2377 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002378}
2379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002380PyDoc_VAR(file_doc) =
2381PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002382"file(name[, mode[, buffering]]) -> file object\n"
2383"\n"
2384"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2385"writing or appending. The file will be created if it doesn't exist\n"
2386"when opened for writing or appending; it will be truncated when\n"
2387"opened for writing. Add a 'b' to the mode for binary files.\n"
2388"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2389"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002390"buffered, and larger numbers specify the buffer size. The preferred way\n"
2391"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002392)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002393PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002394"Add a 'U' to mode to open the file for input with universal newline\n"
2395"support. Any line ending in the input file will be seen as a '\\n'\n"
2396"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2397"the value for this attribute is one of None (no newline read yet),\n"
2398"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2399"\n"
2400"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002401);
Tim Peters59c9a642001-09-13 05:38:56 +00002402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002403PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002404 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2405 "file",
2406 sizeof(PyFileObject),
2407 0,
2408 (destructor)file_dealloc, /* tp_dealloc */
2409 0, /* tp_print */
2410 0, /* tp_getattr */
2411 0, /* tp_setattr */
2412 0, /* tp_compare */
2413 (reprfunc)file_repr, /* tp_repr */
2414 0, /* tp_as_number */
2415 0, /* tp_as_sequence */
2416 0, /* tp_as_mapping */
2417 0, /* tp_hash */
2418 0, /* tp_call */
2419 0, /* tp_str */
2420 PyObject_GenericGetAttr, /* tp_getattro */
2421 /* softspace is writable: we must supply tp_setattro */
2422 PyObject_GenericSetAttr, /* tp_setattro */
2423 0, /* tp_as_buffer */
2424 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2425 file_doc, /* tp_doc */
2426 0, /* tp_traverse */
2427 0, /* tp_clear */
2428 0, /* tp_richcompare */
2429 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2430 (getiterfunc)file_self, /* tp_iter */
2431 (iternextfunc)file_iternext, /* tp_iternext */
2432 file_methods, /* tp_methods */
2433 file_memberlist, /* tp_members */
2434 file_getsetlist, /* tp_getset */
2435 0, /* tp_base */
2436 0, /* tp_dict */
2437 0, /* tp_descr_get */
2438 0, /* tp_descr_set */
2439 0, /* tp_dictoffset */
2440 file_init, /* tp_init */
2441 PyType_GenericAlloc, /* tp_alloc */
2442 file_new, /* tp_new */
2443 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002444};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002445
2446/* Interface for the 'soft space' between print items. */
2447
2448int
Fred Drakefd99de62000-07-09 05:02:18 +00002449PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002450{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002451 long oldflag = 0;
2452 if (f == NULL) {
2453 /* Do nothing */
2454 }
2455 else if (PyFile_Check(f)) {
2456 oldflag = ((PyFileObject *)f)->f_softspace;
2457 ((PyFileObject *)f)->f_softspace = newflag;
2458 }
2459 else {
2460 PyObject *v;
2461 v = PyObject_GetAttrString(f, "softspace");
2462 if (v == NULL)
2463 PyErr_Clear();
2464 else {
2465 if (PyInt_Check(v))
2466 oldflag = PyInt_AsLong(v);
2467 assert(oldflag < INT_MAX);
2468 Py_DECREF(v);
2469 }
2470 v = PyInt_FromLong((long)newflag);
2471 if (v == NULL)
2472 PyErr_Clear();
2473 else {
2474 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2475 PyErr_Clear();
2476 Py_DECREF(v);
2477 }
2478 }
2479 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002480}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002481
2482/* Interfaces to write objects/strings to file-like objects */
2483
2484int
Fred Drakefd99de62000-07-09 05:02:18 +00002485PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002486{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002487 PyObject *writer, *value, *args, *result;
2488 if (f == NULL) {
2489 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2490 return -1;
2491 }
2492 else if (PyFile_Check(f)) {
2493 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002494#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002495 PyObject *enc = fobj->f_encoding;
2496 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002497#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002498 if (fobj->f_fp == NULL) {
2499 err_closed();
2500 return -1;
2501 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002502#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002503 if ((flags & Py_PRINT_RAW) &&
2504 PyUnicode_Check(v) && enc != Py_None) {
2505 char *cenc = PyString_AS_STRING(enc);
2506 char *errors = fobj->f_errors == Py_None ?
2507 "strict" : PyString_AS_STRING(fobj->f_errors);
2508 value = PyUnicode_AsEncodedString(v, cenc, errors);
2509 if (value == NULL)
2510 return -1;
2511 } else {
2512 value = v;
2513 Py_INCREF(value);
2514 }
2515 result = file_PyObject_Print(value, fobj, flags);
2516 Py_DECREF(value);
2517 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002518#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002519 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002520#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002521 }
2522 writer = PyObject_GetAttrString(f, "write");
2523 if (writer == NULL)
2524 return -1;
2525 if (flags & Py_PRINT_RAW) {
2526 if (PyUnicode_Check(v)) {
2527 value = v;
2528 Py_INCREF(value);
2529 } else
2530 value = PyObject_Str(v);
2531 }
2532 else
2533 value = PyObject_Repr(v);
2534 if (value == NULL) {
2535 Py_DECREF(writer);
2536 return -1;
2537 }
2538 args = PyTuple_Pack(1, value);
2539 if (args == NULL) {
2540 Py_DECREF(value);
2541 Py_DECREF(writer);
2542 return -1;
2543 }
2544 result = PyEval_CallObject(writer, args);
2545 Py_DECREF(args);
2546 Py_DECREF(value);
2547 Py_DECREF(writer);
2548 if (result == NULL)
2549 return -1;
2550 Py_DECREF(result);
2551 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002552}
2553
Guido van Rossum27a60b11997-05-22 22:25:11 +00002554int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002555PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002556{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002557
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002558 if (f == NULL) {
2559 /* Should be caused by a pre-existing error */
2560 if (!PyErr_Occurred())
2561 PyErr_SetString(PyExc_SystemError,
2562 "null file for PyFile_WriteString");
2563 return -1;
2564 }
2565 else if (PyFile_Check(f)) {
2566 PyFileObject *fobj = (PyFileObject *) f;
2567 FILE *fp = PyFile_AsFile(f);
2568 if (fp == NULL) {
2569 err_closed();
2570 return -1;
2571 }
2572 FILE_BEGIN_ALLOW_THREADS(fobj)
2573 fputs(s, fp);
2574 FILE_END_ALLOW_THREADS(fobj)
2575 return 0;
2576 }
2577 else if (!PyErr_Occurred()) {
2578 PyObject *v = PyString_FromString(s);
2579 int err;
2580 if (v == NULL)
2581 return -1;
2582 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2583 Py_DECREF(v);
2584 return err;
2585 }
2586 else
2587 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002588}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002589
2590/* Try to get a file-descriptor from a Python object. If the object
2591 is an integer or long integer, its value is returned. If not, the
2592 object's fileno() method is called if it exists; the method must return
2593 an integer or long integer, which is returned as the file descriptor value.
2594 -1 is returned on failure.
2595*/
2596
2597int PyObject_AsFileDescriptor(PyObject *o)
2598{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002599 int fd;
2600 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002601
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002602 if (PyInt_Check(o)) {
2603 fd = PyInt_AsLong(o);
2604 }
2605 else if (PyLong_Check(o)) {
2606 fd = PyLong_AsLong(o);
2607 }
2608 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2609 {
2610 PyObject *fno = PyEval_CallObject(meth, NULL);
2611 Py_DECREF(meth);
2612 if (fno == NULL)
2613 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002614
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002615 if (PyInt_Check(fno)) {
2616 fd = PyInt_AsLong(fno);
2617 Py_DECREF(fno);
2618 }
2619 else if (PyLong_Check(fno)) {
2620 fd = PyLong_AsLong(fno);
2621 Py_DECREF(fno);
2622 }
2623 else {
2624 PyErr_SetString(PyExc_TypeError,
2625 "fileno() returned a non-integer");
2626 Py_DECREF(fno);
2627 return -1;
2628 }
2629 }
2630 else {
2631 PyErr_SetString(PyExc_TypeError,
2632 "argument must be an int, or have a fileno() method.");
2633 return -1;
2634 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002635
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002636 if (fd < 0) {
2637 PyErr_Format(PyExc_ValueError,
2638 "file descriptor cannot be a negative integer (%i)",
2639 fd);
2640 return -1;
2641 }
2642 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002643}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002644
Jack Jansen7b8c7542002-04-14 20:12:41 +00002645/* From here on we need access to the real fgets and fread */
2646#undef fgets
2647#undef fread
2648
2649/*
2650** Py_UniversalNewlineFgets is an fgets variation that understands
2651** all of \r, \n and \r\n conventions.
2652** The stream should be opened in binary mode.
2653** If fobj is NULL the routine always does newline conversion, and
2654** it may peek one char ahead to gobble the second char in \r\n.
2655** If fobj is non-NULL it must be a PyFileObject. In this case there
2656** is no readahead but in stead a flag is used to skip a following
2657** \n on the next read. Also, if the file is open in binary mode
2658** the whole conversion is skipped. Finally, the routine keeps track of
2659** the different types of newlines seen.
2660** Note that we need no error handling: fgets() treats error and eof
2661** identically.
2662*/
2663char *
2664Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2665{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002666 char *p = buf;
2667 int c;
2668 int newlinetypes = 0;
2669 int skipnextlf = 0;
2670 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002671
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002672 if (fobj) {
2673 if (!PyFile_Check(fobj)) {
2674 errno = ENXIO; /* What can you do... */
2675 return NULL;
2676 }
2677 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2678 if ( !univ_newline )
2679 return fgets(buf, n, stream);
2680 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2681 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2682 }
2683 FLOCKFILE(stream);
2684 c = 'x'; /* Shut up gcc warning */
2685 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2686 if (skipnextlf ) {
2687 skipnextlf = 0;
2688 if (c == '\n') {
2689 /* Seeing a \n here with skipnextlf true
2690 ** means we saw a \r before.
2691 */
2692 newlinetypes |= NEWLINE_CRLF;
2693 c = GETC(stream);
2694 if (c == EOF) break;
2695 } else {
2696 /*
2697 ** Note that c == EOF also brings us here,
2698 ** so we're okay if the last char in the file
2699 ** is a CR.
2700 */
2701 newlinetypes |= NEWLINE_CR;
2702 }
2703 }
2704 if (c == '\r') {
2705 /* A \r is translated into a \n, and we skip
2706 ** an adjacent \n, if any. We don't set the
2707 ** newlinetypes flag until we've seen the next char.
2708 */
2709 skipnextlf = 1;
2710 c = '\n';
2711 } else if ( c == '\n') {
2712 newlinetypes |= NEWLINE_LF;
2713 }
2714 *p++ = c;
2715 if (c == '\n') break;
2716 }
2717 if ( c == EOF && skipnextlf )
2718 newlinetypes |= NEWLINE_CR;
2719 FUNLOCKFILE(stream);
2720 *p = '\0';
2721 if (fobj) {
2722 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2723 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2724 } else if ( skipnextlf ) {
2725 /* If we have no file object we cannot save the
2726 ** skipnextlf flag. We have to readahead, which
2727 ** will cause a pause if we're reading from an
2728 ** interactive stream, but that is very unlikely
2729 ** unless we're doing something silly like
2730 ** execfile("/dev/tty").
2731 */
2732 c = GETC(stream);
2733 if ( c != '\n' )
2734 ungetc(c, stream);
2735 }
2736 if (p == buf)
2737 return NULL;
2738 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002739}
2740
2741/*
2742** Py_UniversalNewlineFread is an fread variation that understands
2743** all of \r, \n and \r\n conventions.
2744** The stream should be opened in binary mode.
2745** fobj must be a PyFileObject. In this case there
2746** is no readahead but in stead a flag is used to skip a following
2747** \n on the next read. Also, if the file is open in binary mode
2748** the whole conversion is skipped. Finally, the routine keeps track of
2749** the different types of newlines seen.
2750*/
2751size_t
Tim Peters058b1412002-04-21 07:29:14 +00002752Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002753 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002754{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002755 char *dst = buf;
2756 PyFileObject *f = (PyFileObject *)fobj;
2757 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002759 assert(buf != NULL);
2760 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002762 if (!fobj || !PyFile_Check(fobj)) {
2763 errno = ENXIO; /* What can you do... */
2764 return 0;
2765 }
2766 if (!f->f_univ_newline)
2767 return fread(buf, 1, n, stream);
2768 newlinetypes = f->f_newlinetypes;
2769 skipnextlf = f->f_skipnextlf;
2770 /* Invariant: n is the number of bytes remaining to be filled
2771 * in the buffer.
2772 */
2773 while (n) {
2774 size_t nread;
2775 int shortread;
2776 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002778 nread = fread(dst, 1, n, stream);
2779 assert(nread <= n);
2780 if (nread == 0)
2781 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002782
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002783 n -= nread; /* assuming 1 byte out for each in; will adjust */
2784 shortread = n != 0; /* true iff EOF or error */
2785 while (nread--) {
2786 char c = *src++;
2787 if (c == '\r') {
2788 /* Save as LF and set flag to skip next LF. */
2789 *dst++ = '\n';
2790 skipnextlf = 1;
2791 }
2792 else if (skipnextlf && c == '\n') {
2793 /* Skip LF, and remember we saw CR LF. */
2794 skipnextlf = 0;
2795 newlinetypes |= NEWLINE_CRLF;
2796 ++n;
2797 }
2798 else {
2799 /* Normal char to be stored in buffer. Also
2800 * update the newlinetypes flag if either this
2801 * is an LF or the previous char was a CR.
2802 */
2803 if (c == '\n')
2804 newlinetypes |= NEWLINE_LF;
2805 else if (skipnextlf)
2806 newlinetypes |= NEWLINE_CR;
2807 *dst++ = c;
2808 skipnextlf = 0;
2809 }
2810 }
2811 if (shortread) {
2812 /* If this is EOF, update type flags. */
2813 if (skipnextlf && feof(stream))
2814 newlinetypes |= NEWLINE_CR;
2815 break;
2816 }
2817 }
2818 f->f_newlinetypes = newlinetypes;
2819 f->f_skipnextlf = skipnextlf;
2820 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002821}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002822
2823#ifdef __cplusplus
2824}
2825#endif