blob: edd839e8b0dfcb31e768ace4f51e9a778d95fdbf [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 Pitrouc83ea132010-05-09 14:46:46 +0000496 PyFileObject *f;
Tim Peters59c9a642001-09-13 05:38:56 +0000497
Victor Stinner63c22fa2011-09-23 19:37:03 +0200498 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, NULL);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 if (f != NULL) {
500 if (open_the_file(f, name, mode) == NULL) {
501 Py_DECREF(f);
502 f = NULL;
503 }
504 }
505 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000506}
507
Guido van Rossumb6775db1994-08-01 11:34:53 +0000508void
Fred Drakefd99de62000-07-09 05:02:18 +0000509PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000510{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 PyFileObject *file = (PyFileObject *)f;
512 if (bufsize >= 0) {
513 int type;
514 switch (bufsize) {
515 case 0:
516 type = _IONBF;
517 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000518#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 case 1:
520 type = _IOLBF;
521 bufsize = BUFSIZ;
522 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000523#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000524 default:
525 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000526#ifndef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000527 bufsize = BUFSIZ;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000528#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000529 break;
530 }
531 fflush(file->f_fp);
532 if (type == _IONBF) {
533 PyMem_Free(file->f_setbuf);
534 file->f_setbuf = NULL;
535 } else {
536 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
537 bufsize);
538 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000539#ifdef HAVE_SETVBUF
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000540 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000541#else /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000543#endif /* !HAVE_SETVBUF */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000544 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000545}
546
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000547/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000548 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000549
550int
551PyFile_SetEncoding(PyObject *f, const char *enc)
552{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000553 return PyFile_SetEncodingAndErrors(f, enc, NULL);
Martin v. Löwis99815892008-06-01 07:20:46 +0000554}
555
556int
557PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000559 PyFileObject *file = (PyFileObject*)f;
560 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000561
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000562 assert(PyFile_Check(f));
563 str = PyString_FromString(enc);
564 if (!str)
565 return 0;
566 if (errors) {
567 oerrors = PyString_FromString(errors);
568 if (!oerrors) {
569 Py_DECREF(str);
570 return 0;
571 }
572 } else {
573 oerrors = Py_None;
574 Py_INCREF(Py_None);
575 }
576 Py_DECREF(file->f_encoding);
577 file->f_encoding = str;
578 Py_DECREF(file->f_errors);
579 file->f_errors = oerrors;
580 return 1;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000584err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000585{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000586 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
587 return NULL;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000588}
589
Antoine Pitroubb445a12010-02-05 17:05:54 +0000590static PyObject *
591err_mode(char *action)
592{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000593 PyErr_Format(PyExc_IOError, "File not open for %s", action);
594 return NULL;
Antoine Pitroubb445a12010-02-05 17:05:54 +0000595}
596
Thomas Woutersc45251a2006-02-12 11:53:32 +0000597/* Refuse regular file I/O if there's data in the iteration-buffer.
598 * Mixing them would cause data to arrive out of order, as the read*
599 * methods don't use the iteration buffer. */
600static PyObject *
601err_iterbuffered(void)
602{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000603 PyErr_SetString(PyExc_ValueError,
604 "Mixing iteration and read methods would lose data");
605 return NULL;
Thomas Woutersc45251a2006-02-12 11:53:32 +0000606}
607
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000608static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000609
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000610/* Methods */
611
612static void
Fred Drakefd99de62000-07-09 05:02:18 +0000613file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000614{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000615 PyObject *ret;
616 if (f->weakreflist != NULL)
617 PyObject_ClearWeakRefs((PyObject *) f);
618 ret = close_the_file(f);
619 if (!ret) {
620 PySys_WriteStderr("close failed in file object destructor:\n");
621 PyErr_Print();
622 }
623 else {
624 Py_DECREF(ret);
625 }
626 PyMem_Free(f->f_setbuf);
627 Py_XDECREF(f->f_name);
628 Py_XDECREF(f->f_mode);
629 Py_XDECREF(f->f_encoding);
630 Py_XDECREF(f->f_errors);
631 drop_readahead(f);
632 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000633}
634
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000636file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000638 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000639#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000640 PyObject *ret = NULL;
641 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
642 const char *name_str = name ? PyString_AsString(name) : "?";
643 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
644 f->f_fp == NULL ? "closed" : "open",
645 name_str,
646 PyString_AsString(f->f_mode),
647 f);
648 Py_XDECREF(name);
649 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000650#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 } else {
652 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
653 f->f_fp == NULL ? "closed" : "open",
654 PyString_AsString(f->f_name),
655 PyString_AsString(f->f_mode),
656 f);
657 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000658}
659
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000661file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 PyObject *sts = close_the_file(f);
Antoine Pitrou83137c22010-05-17 19:56:59 +0000664 if (sts) {
665 PyMem_Free(f->f_setbuf);
666 f->f_setbuf = NULL;
667 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000668 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000669}
670
Trent Mickf29f47b2000-08-11 19:02:59 +0000671
Guido van Rossumb8552162001-09-05 14:58:11 +0000672/* Our very own off_t-like type, 64-bit if possible */
673#if !defined(HAVE_LARGEFILE_SUPPORT)
674typedef off_t Py_off_t;
675#elif SIZEOF_OFF_T >= 8
676typedef off_t Py_off_t;
677#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000678typedef fpos_t Py_off_t;
679#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000680#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000681#endif
682
683
Trent Mickf29f47b2000-08-11 19:02:59 +0000684/* a portable fseek() function
685 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000686static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000687_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000688{
Guido van Rossumb8552162001-09-05 14:58:11 +0000689#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 return fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000691#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000692 return fseeko(fp, offset, whence);
Trent Mickf29f47b2000-08-11 19:02:59 +0000693#elif defined(HAVE_FSEEK64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000694 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000695#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000696 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000697#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000698 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
699 and fgetpos() to implement fseek()*/
700 fpos_t pos;
701 switch (whence) {
702 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000703#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000704 fflush(fp);
705 if (_lseeki64(fileno(fp), 0, 2) == -1)
706 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000707#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000708 if (fseek(fp, 0, SEEK_END) != 0)
709 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000710#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000711 /* fall through */
712 case SEEK_CUR:
713 if (fgetpos(fp, &pos) != 0)
714 return -1;
715 offset += pos;
716 break;
717 /* case SEEK_SET: break; */
718 }
719 return fsetpos(fp, &offset);
Trent Mickf29f47b2000-08-11 19:02:59 +0000720#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000721#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000722#endif
723}
724
725
726/* a portable ftell() function
727 Return -1 on failure with errno set appropriately, current file
728 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000729static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000730_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000731{
Guido van Rossumb8552162001-09-05 14:58:11 +0000732#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 return ftell(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000734#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000735 return ftello(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000736#elif defined(HAVE_FTELL64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000737 return ftell64(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000738#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000739 fpos_t pos;
740 if (fgetpos(fp, &pos) != 0)
741 return -1;
742 return pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000743#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000744#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000745#endif
746}
747
748
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000749static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000750file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000751{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000752 int whence;
753 int ret;
754 Py_off_t offset;
755 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000756
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000757 if (f->f_fp == NULL)
758 return err_closed();
759 drop_readahead(f);
760 whence = 0;
761 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
762 return NULL;
763 off_index = PyNumber_Index(offobj);
764 if (!off_index) {
765 if (!PyFloat_Check(offobj))
766 return NULL;
767 /* Deprecated in 2.6 */
768 PyErr_Clear();
769 if (PyErr_WarnEx(PyExc_DeprecationWarning,
770 "integer argument expected, got float",
771 1) < 0)
772 return NULL;
773 off_index = offobj;
774 Py_INCREF(offobj);
775 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000776#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000777 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000778#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000779 offset = PyLong_Check(off_index) ?
780 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000781#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 Py_DECREF(off_index);
783 if (PyErr_Occurred())
784 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000785
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000786 FILE_BEGIN_ALLOW_THREADS(f)
787 errno = 0;
788 ret = _portable_fseek(f->f_fp, offset, whence);
789 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000790
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000791 if (ret != 0) {
792 PyErr_SetFromErrno(PyExc_IOError);
793 clearerr(f->f_fp);
794 return NULL;
795 }
796 f->f_skipnextlf = 0;
797 Py_INCREF(Py_None);
798 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000799}
800
Trent Mickf29f47b2000-08-11 19:02:59 +0000801
Guido van Rossumd7047b31995-01-02 19:07:15 +0000802#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000803static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000804file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000805{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000806 Py_off_t newsize;
807 PyObject *newsizeobj = NULL;
808 Py_off_t initialpos;
809 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000810
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 if (f->f_fp == NULL)
812 return err_closed();
813 if (!f->writable)
814 return err_mode("writing");
815 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
816 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000817
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000818 /* Get current file position. If the file happens to be open for
819 * update and the last operation was an input operation, C doesn't
820 * define what the later fflush() will do, but we promise truncate()
821 * won't change the current position (and fflush() *does* change it
822 * then at least on Windows). The easiest thing is to capture
823 * current pos now and seek back to it at the end.
824 */
825 FILE_BEGIN_ALLOW_THREADS(f)
826 errno = 0;
827 initialpos = _portable_ftell(f->f_fp);
828 FILE_END_ALLOW_THREADS(f)
829 if (initialpos == -1)
830 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000831
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000832 /* Set newsize to current postion if newsizeobj NULL, else to the
833 * specified value.
834 */
835 if (newsizeobj != NULL) {
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000836#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000837 newsize = PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000838#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000839 newsize = PyLong_Check(newsizeobj) ?
840 PyLong_AsLongLong(newsizeobj) :
841 PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000842#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000843 if (PyErr_Occurred())
844 return NULL;
845 }
846 else /* default to current position */
847 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000848
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 /* Flush the stream. We're mixing stream-level I/O with lower-level
850 * I/O, and a flush may be necessary to synch both platform views
851 * of the current file state.
852 */
853 FILE_BEGIN_ALLOW_THREADS(f)
854 errno = 0;
855 ret = fflush(f->f_fp);
856 FILE_END_ALLOW_THREADS(f)
857 if (ret != 0)
858 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000859
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000860#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000861 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
862 so don't even try using it. */
863 {
864 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000865
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000866 /* Have to move current pos to desired endpoint on Windows. */
867 FILE_BEGIN_ALLOW_THREADS(f)
868 errno = 0;
869 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
870 FILE_END_ALLOW_THREADS(f)
871 if (ret)
872 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 /* Truncate. Note that this may grow the file! */
875 FILE_BEGIN_ALLOW_THREADS(f)
876 errno = 0;
877 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
878 ret = hFile == (HANDLE)-1;
879 if (ret == 0) {
880 ret = SetEndOfFile(hFile) == 0;
881 if (ret)
882 errno = EACCES;
883 }
884 FILE_END_ALLOW_THREADS(f)
885 if (ret)
886 goto onioerror;
887 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000888#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000889 FILE_BEGIN_ALLOW_THREADS(f)
890 errno = 0;
891 ret = ftruncate(fileno(f->f_fp), newsize);
892 FILE_END_ALLOW_THREADS(f)
893 if (ret != 0)
894 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000895#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000896
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 /* Restore original file position. */
898 FILE_BEGIN_ALLOW_THREADS(f)
899 errno = 0;
900 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
901 FILE_END_ALLOW_THREADS(f)
902 if (ret)
903 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000904
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000905 Py_INCREF(Py_None);
906 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000907
908onioerror:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000909 PyErr_SetFromErrno(PyExc_IOError);
910 clearerr(f->f_fp);
911 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000912}
913#endif /* HAVE_FTRUNCATE */
914
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000915static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000916file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000917{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000918 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000919
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000920 if (f->f_fp == NULL)
921 return err_closed();
922 FILE_BEGIN_ALLOW_THREADS(f)
923 errno = 0;
924 pos = _portable_ftell(f->f_fp);
925 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000926
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000927 if (pos == -1) {
928 PyErr_SetFromErrno(PyExc_IOError);
929 clearerr(f->f_fp);
930 return NULL;
931 }
932 if (f->f_skipnextlf) {
933 int c;
934 c = GETC(f->f_fp);
935 if (c == '\n') {
936 f->f_newlinetypes |= NEWLINE_CRLF;
937 pos++;
938 f->f_skipnextlf = 0;
939 } else if (c != EOF) ungetc(c, f->f_fp);
940 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000941#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000942 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000943#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000945#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000946}
947
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000948static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000949file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000950{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000951 if (f->f_fp == NULL)
952 return err_closed();
953 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000954}
955
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000956static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000957file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000958{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000959 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000960
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 if (f->f_fp == NULL)
962 return err_closed();
963 FILE_BEGIN_ALLOW_THREADS(f)
964 errno = 0;
965 res = fflush(f->f_fp);
966 FILE_END_ALLOW_THREADS(f)
967 if (res != 0) {
968 PyErr_SetFromErrno(PyExc_IOError);
969 clearerr(f->f_fp);
970 return NULL;
971 }
972 Py_INCREF(Py_None);
973 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000974}
975
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000976static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000977file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000978{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000979 long res;
980 if (f->f_fp == NULL)
981 return err_closed();
982 FILE_BEGIN_ALLOW_THREADS(f)
983 res = isatty((int)fileno(f->f_fp));
984 FILE_END_ALLOW_THREADS(f)
985 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000986}
987
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000988
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000989#if BUFSIZ < 8192
990#define SMALLCHUNK 8192
991#else
992#define SMALLCHUNK BUFSIZ
993#endif
994
Guido van Rossum3c259041999-01-14 19:00:14 +0000995#if SIZEOF_INT < 4
996#define BIGCHUNK (512 * 32)
997#else
998#define BIGCHUNK (512 * 1024)
999#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001000
1001static size_t
Fred Drakefd99de62000-07-09 05:02:18 +00001002new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001003{
1004#ifdef HAVE_FSTAT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001005 off_t pos, end;
1006 struct stat st;
1007 if (fstat(fileno(f->f_fp), &st) == 0) {
1008 end = st.st_size;
1009 /* The following is not a bug: we really need to call lseek()
1010 *and* ftell(). The reason is that some stdio libraries
1011 mistakenly flush their buffer when ftell() is called and
1012 the lseek() call it makes fails, thereby throwing away
1013 data that cannot be recovered in any way. To avoid this,
1014 we first test lseek(), and only call ftell() if lseek()
1015 works. We can't use the lseek() value either, because we
1016 need to take the amount of buffered data into account.
1017 (Yet another reason why stdio stinks. :-) */
1018 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
1019 if (pos >= 0) {
1020 pos = ftell(f->f_fp);
1021 }
1022 if (pos < 0)
1023 clearerr(f->f_fp);
1024 if (end > pos && pos >= 0)
1025 return currentsize + end - pos + 1;
1026 /* Add 1 so if the file were to grow we'd notice. */
1027 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001028#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 if (currentsize > SMALLCHUNK) {
1030 /* Keep doubling until we reach BIGCHUNK;
1031 then keep adding BIGCHUNK. */
1032 if (currentsize <= BIGCHUNK)
1033 return currentsize + currentsize;
1034 else
1035 return currentsize + BIGCHUNK;
1036 }
1037 return currentsize + SMALLCHUNK;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001038}
1039
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001040#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1041#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1042#else
1043#ifdef EWOULDBLOCK
1044#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1045#else
1046#ifdef EAGAIN
1047#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1048#else
1049#define BLOCKED_ERRNO(x) 0
1050#endif
1051#endif
1052#endif
1053
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001054static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001055file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001056{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001057 long bytesrequested = -1;
1058 size_t bytesread, buffersize, chunksize;
1059 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001060
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001061 if (f->f_fp == NULL)
1062 return err_closed();
1063 if (!f->readable)
1064 return err_mode("reading");
1065 /* refuse to mix with f.next() */
1066 if (f->f_buf != NULL &&
1067 (f->f_bufend - f->f_bufptr) > 0 &&
1068 f->f_buf[0] != '\0')
1069 return err_iterbuffered();
1070 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
1071 return NULL;
1072 if (bytesrequested < 0)
1073 buffersize = new_buffersize(f, (size_t)0);
1074 else
1075 buffersize = bytesrequested;
1076 if (buffersize > PY_SSIZE_T_MAX) {
1077 PyErr_SetString(PyExc_OverflowError,
1078 "requested number of bytes is more than a Python string can hold");
1079 return NULL;
1080 }
1081 v = PyString_FromStringAndSize((char *)NULL, buffersize);
1082 if (v == NULL)
1083 return NULL;
1084 bytesread = 0;
1085 for (;;) {
1086 FILE_BEGIN_ALLOW_THREADS(f)
1087 errno = 0;
1088 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
1089 buffersize - bytesread, f->f_fp, (PyObject *)f);
1090 FILE_END_ALLOW_THREADS(f)
1091 if (chunksize == 0) {
1092 if (!ferror(f->f_fp))
1093 break;
1094 clearerr(f->f_fp);
1095 /* When in non-blocking mode, data shouldn't
1096 * be discarded if a blocking signal was
1097 * received. That will also happen if
1098 * chunksize != 0, but bytesread < buffersize. */
1099 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1100 break;
1101 PyErr_SetFromErrno(PyExc_IOError);
1102 Py_DECREF(v);
1103 return NULL;
1104 }
1105 bytesread += chunksize;
1106 if (bytesread < buffersize) {
1107 clearerr(f->f_fp);
1108 break;
1109 }
1110 if (bytesrequested < 0) {
1111 buffersize = new_buffersize(f, buffersize);
1112 if (_PyString_Resize(&v, buffersize) < 0)
1113 return NULL;
1114 } else {
1115 /* Got what was requested. */
1116 break;
1117 }
1118 }
1119 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1120 return NULL;
1121 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001122}
1123
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001124static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001125file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001126{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 char *ptr;
1128 Py_ssize_t ntodo;
1129 Py_ssize_t ndone, nnow;
1130 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001131
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001132 if (f->f_fp == NULL)
1133 return err_closed();
1134 if (!f->readable)
1135 return err_mode("reading");
1136 /* refuse to mix with f.next() */
1137 if (f->f_buf != NULL &&
1138 (f->f_bufend - f->f_bufptr) > 0 &&
1139 f->f_buf[0] != '\0')
1140 return err_iterbuffered();
1141 if (!PyArg_ParseTuple(args, "w*", &pbuf))
1142 return NULL;
1143 ptr = pbuf.buf;
1144 ntodo = pbuf.len;
1145 ndone = 0;
1146 while (ntodo > 0) {
1147 FILE_BEGIN_ALLOW_THREADS(f)
1148 errno = 0;
1149 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
1150 (PyObject *)f);
1151 FILE_END_ALLOW_THREADS(f)
1152 if (nnow == 0) {
1153 if (!ferror(f->f_fp))
1154 break;
1155 PyErr_SetFromErrno(PyExc_IOError);
1156 clearerr(f->f_fp);
1157 PyBuffer_Release(&pbuf);
1158 return NULL;
1159 }
1160 ndone += nnow;
1161 ntodo -= nnow;
1162 }
1163 PyBuffer_Release(&pbuf);
1164 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001165}
1166
Tim Peters86821b22001-01-07 21:19:34 +00001167/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001168Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001169
1170Under MSVC 6:
1171
Tim Peters1c733232001-01-08 04:02:07 +00001172+ MS threadsafe getc is very slow (multiple layers of function calls before+
1173 after each character, to lock+unlock the stream).
1174+ The stream-locking functions are MS-internal -- can't access them from user
1175 code.
1176+ There's nothing Tim could find in the MS C or platform SDK libraries that
1177 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001178+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1179
1180So we use fgets for speed(!), despite that it's painful.
1181
1182MS realloc is also slow.
1183
Tim Petersf29b64d2001-01-15 06:33:19 +00001184Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1185have):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001186 Linux a wash
1187 Solaris a wash
1188 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001189
Tim Petersf29b64d2001-01-15 06:33:19 +00001190CAUTION: The C std isn't clear about this: in those cases where fgets
1191writes something into the buffer, can it write into any position beyond the
1192required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1193known on which it does; and it would be a strange way to code fgets. Still,
1194getline_via_fgets may not work correctly if it does. The std test
1195test_bufio.py should fail if platform fgets() routinely writes beyond the
1196trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001197**************************************************************************/
1198
Tim Petersf29b64d2001-01-15 06:33:19 +00001199/* Use this routine if told to, or by default on non-get_unlocked()
1200 * platforms unless told not to. Yikes! Let's spell that out:
1201 * On a platform with getc_unlocked():
1202 * By default, use getc_unlocked().
1203 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1204 * On a platform without getc_unlocked():
1205 * By default, use fgets().
1206 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1207 */
1208#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1209#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001210#endif
1211
Tim Petersf29b64d2001-01-15 06:33:19 +00001212#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1213#undef USE_FGETS_IN_GETLINE
1214#endif
1215
1216#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001217static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001218getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001219{
Tim Peters15b83852001-01-08 00:53:12 +00001220/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001221 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1222 * to fill this much of the buffer with a known value in order to figure out
1223 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1224 * than "most" lines, we waste time filling unused buffer slots. 100 is
1225 * surely adequate for most peoples' email archives, chewing over source code,
1226 * etc -- "regular old text files".
1227 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1228 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1229 * cautions about boosting that. 300 was chosen because the worst real-life
1230 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1231 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001232 */
Tim Peters142297a2001-01-15 10:36:56 +00001233#define INITBUFSIZE 100
1234#define MAXBUFSIZE 300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001235 char* p; /* temp */
1236 char buf[MAXBUFSIZE];
1237 PyObject* v; /* the string object result */
1238 char* pvfree; /* address of next free slot */
1239 char* pvend; /* address one beyond last free slot */
1240 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1241 size_t total_v_size; /* total # of slots in buffer */
1242 size_t increment; /* amount to increment the buffer */
1243 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001244
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001245 /* Optimize for normal case: avoid _PyString_Resize if at all
1246 * possible via first reading into stack buffer "buf".
1247 */
1248 total_v_size = INITBUFSIZE; /* start small and pray */
1249 pvfree = buf;
1250 for (;;) {
1251 FILE_BEGIN_ALLOW_THREADS(f)
1252 pvend = buf + total_v_size;
1253 nfree = pvend - pvfree;
1254 memset(pvfree, '\n', nfree);
1255 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1256 p = fgets(pvfree, (int)nfree, fp);
1257 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001258
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001259 if (p == NULL) {
1260 clearerr(fp);
1261 if (PyErr_CheckSignals())
1262 return NULL;
1263 v = PyString_FromStringAndSize(buf, pvfree - buf);
1264 return v;
1265 }
1266 /* fgets read *something* */
1267 p = memchr(pvfree, '\n', nfree);
1268 if (p != NULL) {
1269 /* Did the \n come from fgets or from us?
1270 * Since fgets stops at the first \n, and then writes
1271 * \0, if it's from fgets a \0 must be next. But if
1272 * that's so, it could not have come from us, since
1273 * the \n's we filled the buffer with have only more
1274 * \n's to the right.
1275 */
1276 if (p+1 < pvend && *(p+1) == '\0') {
1277 /* It's from fgets: we win! In particular,
1278 * we haven't done any mallocs yet, and can
1279 * build the final result on the first try.
1280 */
1281 ++p; /* include \n from fgets */
1282 }
1283 else {
1284 /* Must be from us: fgets didn't fill the
1285 * buffer and didn't find a newline, so it
1286 * must be the last and newline-free line of
1287 * the file.
1288 */
1289 assert(p > pvfree && *(p-1) == '\0');
1290 --p; /* don't include \0 from fgets */
1291 }
1292 v = PyString_FromStringAndSize(buf, p - buf);
1293 return v;
1294 }
1295 /* yuck: fgets overwrote all the newlines, i.e. the entire
1296 * buffer. So this line isn't over yet, or maybe it is but
1297 * we're exactly at EOF. If we haven't already, try using the
1298 * rest of the stack buffer.
1299 */
1300 assert(*(pvend-1) == '\0');
1301 if (pvfree == buf) {
1302 pvfree = pvend - 1; /* overwrite trailing null */
1303 total_v_size = MAXBUFSIZE;
1304 }
1305 else
1306 break;
1307 }
Tim Peters142297a2001-01-15 10:36:56 +00001308
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001309 /* The stack buffer isn't big enough; malloc a string object and read
1310 * into its buffer.
1311 */
1312 total_v_size = MAXBUFSIZE << 1;
1313 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
1314 if (v == NULL)
1315 return v;
1316 /* copy over everything except the last null byte */
1317 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1318 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001319
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001320 /* Keep reading stuff into v; if it ever ends successfully, break
1321 * after setting p one beyond the end of the line. The code here is
1322 * very much like the code above, except reads into v's buffer; see
1323 * the code above for detailed comments about the logic.
1324 */
1325 for (;;) {
1326 FILE_BEGIN_ALLOW_THREADS(f)
1327 pvend = BUF(v) + total_v_size;
1328 nfree = pvend - pvfree;
1329 memset(pvfree, '\n', nfree);
1330 assert(nfree < INT_MAX);
1331 p = fgets(pvfree, (int)nfree, fp);
1332 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001333
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001334 if (p == NULL) {
1335 clearerr(fp);
1336 if (PyErr_CheckSignals()) {
1337 Py_DECREF(v);
1338 return NULL;
1339 }
1340 p = pvfree;
1341 break;
1342 }
1343 p = memchr(pvfree, '\n', nfree);
1344 if (p != NULL) {
1345 if (p+1 < pvend && *(p+1) == '\0') {
1346 /* \n came from fgets */
1347 ++p;
1348 break;
1349 }
1350 /* \n came from us; last line of file, no newline */
1351 assert(p > pvfree && *(p-1) == '\0');
1352 --p;
1353 break;
1354 }
1355 /* expand buffer and try again */
1356 assert(*(pvend-1) == '\0');
1357 increment = total_v_size >> 2; /* mild exponential growth */
1358 prev_v_size = total_v_size;
1359 total_v_size += increment;
1360 /* check for overflow */
1361 if (total_v_size <= prev_v_size ||
1362 total_v_size > PY_SSIZE_T_MAX) {
1363 PyErr_SetString(PyExc_OverflowError,
1364 "line is longer than a Python string can hold");
1365 Py_DECREF(v);
1366 return NULL;
1367 }
1368 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1369 return NULL;
1370 /* overwrite the trailing null byte */
1371 pvfree = BUF(v) + (prev_v_size - 1);
1372 }
1373 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1374 return NULL;
1375 return v;
Tim Peters86821b22001-01-07 21:19:34 +00001376#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001377#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001378}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001380
Guido van Rossum0bd24411991-04-04 15:21:57 +00001381/* Internal routine to get a line.
1382 Size argument interpretation:
1383 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001384 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001385*/
1386
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001387static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001388get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001389{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001390 FILE *fp = f->f_fp;
1391 int c;
1392 char *buf, *end;
1393 size_t total_v_size; /* total # of slots in buffer */
1394 size_t used_v_size; /* # used slots in buffer */
1395 size_t increment; /* amount to increment the buffer */
1396 PyObject *v;
1397 int newlinetypes = f->f_newlinetypes;
1398 int skipnextlf = f->f_skipnextlf;
1399 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001400
Jack Jansen7b8c7542002-04-14 20:12:41 +00001401#if defined(USE_FGETS_IN_GETLINE)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001402 if (n <= 0 && !univ_newline )
1403 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001404#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001405 total_v_size = n > 0 ? n : 100;
1406 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
1407 if (v == NULL)
1408 return NULL;
1409 buf = BUF(v);
1410 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 for (;;) {
1413 FILE_BEGIN_ALLOW_THREADS(f)
1414 FLOCKFILE(fp);
1415 if (univ_newline) {
1416 c = 'x'; /* Shut up gcc warning */
1417 while ( buf != end && (c = GETC(fp)) != EOF ) {
1418 if (skipnextlf ) {
1419 skipnextlf = 0;
1420 if (c == '\n') {
1421 /* Seeing a \n here with
1422 * skipnextlf true means we
1423 * saw a \r before.
1424 */
1425 newlinetypes |= NEWLINE_CRLF;
1426 c = GETC(fp);
1427 if (c == EOF) break;
1428 } else {
1429 newlinetypes |= NEWLINE_CR;
1430 }
1431 }
1432 if (c == '\r') {
1433 skipnextlf = 1;
1434 c = '\n';
1435 } else if ( c == '\n')
1436 newlinetypes |= NEWLINE_LF;
1437 *buf++ = c;
1438 if (c == '\n') break;
1439 }
1440 if ( c == EOF && skipnextlf )
1441 newlinetypes |= NEWLINE_CR;
1442 } else /* If not universal newlines use the normal loop */
1443 while ((c = GETC(fp)) != EOF &&
1444 (*buf++ = c) != '\n' &&
1445 buf != end)
1446 ;
1447 FUNLOCKFILE(fp);
1448 FILE_END_ALLOW_THREADS(f)
1449 f->f_newlinetypes = newlinetypes;
1450 f->f_skipnextlf = skipnextlf;
1451 if (c == '\n')
1452 break;
1453 if (c == EOF) {
1454 if (ferror(fp)) {
1455 PyErr_SetFromErrno(PyExc_IOError);
1456 clearerr(fp);
1457 Py_DECREF(v);
1458 return NULL;
1459 }
1460 clearerr(fp);
1461 if (PyErr_CheckSignals()) {
1462 Py_DECREF(v);
1463 return NULL;
1464 }
1465 break;
1466 }
1467 /* Must be because buf == end */
1468 if (n > 0)
1469 break;
1470 used_v_size = total_v_size;
1471 increment = total_v_size >> 2; /* mild exponential growth */
1472 total_v_size += increment;
1473 if (total_v_size > PY_SSIZE_T_MAX) {
1474 PyErr_SetString(PyExc_OverflowError,
1475 "line is longer than a Python string can hold");
1476 Py_DECREF(v);
1477 return NULL;
1478 }
1479 if (_PyString_Resize(&v, total_v_size) < 0)
1480 return NULL;
1481 buf = BUF(v) + used_v_size;
1482 end = BUF(v) + total_v_size;
1483 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001485 used_v_size = buf - BUF(v);
1486 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1487 return NULL;
1488 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001489}
1490
Guido van Rossum0bd24411991-04-04 15:21:57 +00001491/* External C interface */
1492
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001493PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001494PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001496 PyObject *result;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001498 if (f == NULL) {
1499 PyErr_BadInternalCall();
1500 return NULL;
1501 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001502
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 if (PyFile_Check(f)) {
1504 PyFileObject *fo = (PyFileObject *)f;
1505 if (fo->f_fp == NULL)
1506 return err_closed();
1507 if (!fo->readable)
1508 return err_mode("reading");
1509 /* refuse to mix with f.next() */
1510 if (fo->f_buf != NULL &&
1511 (fo->f_bufend - fo->f_bufptr) > 0 &&
1512 fo->f_buf[0] != '\0')
1513 return err_iterbuffered();
1514 result = get_line(fo, n);
1515 }
1516 else {
1517 PyObject *reader;
1518 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001519
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 reader = PyObject_GetAttrString(f, "readline");
1521 if (reader == NULL)
1522 return NULL;
1523 if (n <= 0)
1524 args = PyTuple_New(0);
1525 else
1526 args = Py_BuildValue("(i)", n);
1527 if (args == NULL) {
1528 Py_DECREF(reader);
1529 return NULL;
1530 }
1531 result = PyEval_CallObject(reader, args);
1532 Py_DECREF(reader);
1533 Py_DECREF(args);
1534 if (result != NULL && !PyString_Check(result) &&
1535 !PyUnicode_Check(result)) {
1536 Py_DECREF(result);
1537 result = NULL;
1538 PyErr_SetString(PyExc_TypeError,
1539 "object.readline() returned non-string");
1540 }
1541 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001542
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001543 if (n < 0 && result != NULL && PyString_Check(result)) {
1544 char *s = PyString_AS_STRING(result);
1545 Py_ssize_t len = PyString_GET_SIZE(result);
1546 if (len == 0) {
1547 Py_DECREF(result);
1548 result = NULL;
1549 PyErr_SetString(PyExc_EOFError,
1550 "EOF when reading a line");
1551 }
1552 else if (s[len-1] == '\n') {
1553 if (result->ob_refcnt == 1) {
1554 if (_PyString_Resize(&result, len-1))
1555 return NULL;
1556 }
1557 else {
1558 PyObject *v;
1559 v = PyString_FromStringAndSize(s, len-1);
1560 Py_DECREF(result);
1561 result = v;
1562 }
1563 }
1564 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001565#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001566 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1567 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1568 Py_ssize_t len = PyUnicode_GET_SIZE(result);
1569 if (len == 0) {
1570 Py_DECREF(result);
1571 result = NULL;
1572 PyErr_SetString(PyExc_EOFError,
1573 "EOF when reading a line");
1574 }
1575 else if (s[len-1] == '\n') {
1576 if (result->ob_refcnt == 1)
1577 PyUnicode_Resize(&result, len-1);
1578 else {
1579 PyObject *v;
1580 v = PyUnicode_FromUnicode(s, len-1);
1581 Py_DECREF(result);
1582 result = v;
1583 }
1584 }
1585 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001586#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001587 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001588}
1589
1590/* Python method */
1591
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001592static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001593file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001594{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001595 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001596
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001597 if (f->f_fp == NULL)
1598 return err_closed();
1599 if (!f->readable)
1600 return err_mode("reading");
1601 /* refuse to mix with f.next() */
1602 if (f->f_buf != NULL &&
1603 (f->f_bufend - f->f_bufptr) > 0 &&
1604 f->f_buf[0] != '\0')
1605 return err_iterbuffered();
1606 if (!PyArg_ParseTuple(args, "|i:readline", &n))
1607 return NULL;
1608 if (n == 0)
1609 return PyString_FromString("");
1610 if (n < 0)
1611 n = 0;
1612 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001613}
1614
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001615static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001616file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001617{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001618 long sizehint = 0;
1619 PyObject *list = NULL;
1620 PyObject *line;
1621 char small_buffer[SMALLCHUNK];
1622 char *buffer = small_buffer;
1623 size_t buffersize = SMALLCHUNK;
1624 PyObject *big_buffer = NULL;
1625 size_t nfilled = 0;
1626 size_t nread;
1627 size_t totalread = 0;
1628 char *p, *q, *end;
1629 int err;
1630 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001631
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001632 if (f->f_fp == NULL)
1633 return err_closed();
1634 if (!f->readable)
1635 return err_mode("reading");
1636 /* refuse to mix with f.next() */
1637 if (f->f_buf != NULL &&
1638 (f->f_bufend - f->f_bufptr) > 0 &&
1639 f->f_buf[0] != '\0')
1640 return err_iterbuffered();
1641 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
1642 return NULL;
1643 if ((list = PyList_New(0)) == NULL)
1644 return NULL;
1645 for (;;) {
1646 if (shortread)
1647 nread = 0;
1648 else {
1649 FILE_BEGIN_ALLOW_THREADS(f)
1650 errno = 0;
1651 nread = Py_UniversalNewlineFread(buffer+nfilled,
1652 buffersize-nfilled, f->f_fp, (PyObject *)f);
1653 FILE_END_ALLOW_THREADS(f)
1654 shortread = (nread < buffersize-nfilled);
1655 }
1656 if (nread == 0) {
1657 sizehint = 0;
1658 if (!ferror(f->f_fp))
1659 break;
1660 PyErr_SetFromErrno(PyExc_IOError);
1661 clearerr(f->f_fp);
1662 goto error;
1663 }
1664 totalread += nread;
1665 p = (char *)memchr(buffer+nfilled, '\n', nread);
1666 if (p == NULL) {
1667 /* Need a larger buffer to fit this line */
1668 nfilled += nread;
1669 buffersize *= 2;
1670 if (buffersize > PY_SSIZE_T_MAX) {
1671 PyErr_SetString(PyExc_OverflowError,
1672 "line is longer than a Python string can hold");
1673 goto error;
1674 }
1675 if (big_buffer == NULL) {
1676 /* Create the big buffer */
1677 big_buffer = PyString_FromStringAndSize(
1678 NULL, buffersize);
1679 if (big_buffer == NULL)
1680 goto error;
1681 buffer = PyString_AS_STRING(big_buffer);
1682 memcpy(buffer, small_buffer, nfilled);
1683 }
1684 else {
1685 /* Grow the big buffer */
1686 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1687 goto error;
1688 buffer = PyString_AS_STRING(big_buffer);
1689 }
1690 continue;
1691 }
1692 end = buffer+nfilled+nread;
1693 q = buffer;
1694 do {
1695 /* Process complete lines */
1696 p++;
1697 line = PyString_FromStringAndSize(q, p-q);
1698 if (line == NULL)
1699 goto error;
1700 err = PyList_Append(list, line);
1701 Py_DECREF(line);
1702 if (err != 0)
1703 goto error;
1704 q = p;
1705 p = (char *)memchr(q, '\n', end-q);
1706 } while (p != NULL);
1707 /* Move the remaining incomplete line to the start */
1708 nfilled = end-q;
1709 memmove(buffer, q, nfilled);
1710 if (sizehint > 0)
1711 if (totalread >= (size_t)sizehint)
1712 break;
1713 }
1714 if (nfilled != 0) {
1715 /* Partial last line */
1716 line = PyString_FromStringAndSize(buffer, nfilled);
1717 if (line == NULL)
1718 goto error;
1719 if (sizehint > 0) {
1720 /* Need to complete the last line */
1721 PyObject *rest = get_line(f, 0);
1722 if (rest == NULL) {
1723 Py_DECREF(line);
1724 goto error;
1725 }
1726 PyString_Concat(&line, rest);
1727 Py_DECREF(rest);
1728 if (line == NULL)
1729 goto error;
1730 }
1731 err = PyList_Append(list, line);
1732 Py_DECREF(line);
1733 if (err != 0)
1734 goto error;
1735 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001736
1737cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001738 Py_XDECREF(big_buffer);
1739 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001740
1741error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001742 Py_CLEAR(list);
1743 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001744}
1745
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001746static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001747file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001748{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001749 Py_buffer pbuf;
Victor Stinnercaafd772010-09-08 10:51:01 +00001750 const char *s;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001751 Py_ssize_t n, n2;
Victor Stinnercaafd772010-09-08 10:51:01 +00001752 PyObject *encoded = NULL;
1753
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001754 if (f->f_fp == NULL)
1755 return err_closed();
1756 if (!f->writable)
1757 return err_mode("writing");
1758 if (f->f_binary) {
1759 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1760 return NULL;
1761 s = pbuf.buf;
1762 n = pbuf.len;
Victor Stinnercaafd772010-09-08 10:51:01 +00001763 }
1764 else {
1765 const char *encoding, *errors;
1766 PyObject *text;
1767 if (!PyArg_ParseTuple(args, "O", &text))
1768 return NULL;
1769
1770 if (PyString_Check(text)) {
1771 s = PyString_AS_STRING(text);
1772 n = PyString_GET_SIZE(text);
1773 } else if (PyUnicode_Check(text)) {
1774 if (f->f_encoding != Py_None)
1775 encoding = PyString_AS_STRING(f->f_encoding);
1776 else
1777 encoding = PyUnicode_GetDefaultEncoding();
1778 if (f->f_errors != Py_None)
1779 errors = PyString_AS_STRING(f->f_errors);
1780 else
1781 errors = "strict";
1782 encoded = PyUnicode_AsEncodedString(text, encoding, errors);
1783 if (encoded == NULL)
1784 return NULL;
1785 s = PyString_AS_STRING(encoded);
1786 n = PyString_GET_SIZE(encoded);
1787 } else {
1788 if (PyObject_AsCharBuffer(text, &s, &n))
1789 return NULL;
1790 }
1791 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001792 f->f_softspace = 0;
1793 FILE_BEGIN_ALLOW_THREADS(f)
1794 errno = 0;
1795 n2 = fwrite(s, 1, n, f->f_fp);
1796 FILE_END_ALLOW_THREADS(f)
Victor Stinnercaafd772010-09-08 10:51:01 +00001797 Py_XDECREF(encoded);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001798 if (f->f_binary)
1799 PyBuffer_Release(&pbuf);
1800 if (n2 != n) {
1801 PyErr_SetFromErrno(PyExc_IOError);
1802 clearerr(f->f_fp);
1803 return NULL;
1804 }
1805 Py_INCREF(Py_None);
1806 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001807}
1808
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001809static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001810file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001811{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001812#define CHUNKSIZE 1000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 PyObject *list, *line;
1814 PyObject *it; /* iter(seq) */
1815 PyObject *result;
1816 int index, islist;
1817 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001819 assert(seq != NULL);
1820 if (f->f_fp == NULL)
1821 return err_closed();
1822 if (!f->writable)
1823 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001824
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001825 result = NULL;
1826 list = NULL;
1827 islist = PyList_Check(seq);
1828 if (islist)
1829 it = NULL;
1830 else {
1831 it = PyObject_GetIter(seq);
1832 if (it == NULL) {
1833 PyErr_SetString(PyExc_TypeError,
1834 "writelines() requires an iterable argument");
1835 return NULL;
1836 }
1837 /* From here on, fail by going to error, to reclaim "it". */
1838 list = PyList_New(CHUNKSIZE);
1839 if (list == NULL)
1840 goto error;
1841 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001842
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001843 /* Strategy: slurp CHUNKSIZE lines into a private list,
1844 checking that they are all strings, then write that list
1845 without holding the interpreter lock, then come back for more. */
1846 for (index = 0; ; index += CHUNKSIZE) {
1847 if (islist) {
1848 Py_XDECREF(list);
1849 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
1850 if (list == NULL)
1851 goto error;
1852 j = PyList_GET_SIZE(list);
1853 }
1854 else {
1855 for (j = 0; j < CHUNKSIZE; j++) {
1856 line = PyIter_Next(it);
1857 if (line == NULL) {
1858 if (PyErr_Occurred())
1859 goto error;
1860 break;
1861 }
1862 PyList_SetItem(list, j, line);
1863 }
Benjamin Petersonbf775542010-10-16 19:20:12 +00001864 /* The iterator might have closed the file on us. */
1865 if (f->f_fp == NULL) {
1866 err_closed();
1867 goto error;
1868 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001869 }
1870 if (j == 0)
1871 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001872
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001873 /* Check that all entries are indeed strings. If not,
1874 apply the same rules as for file.write() and
1875 convert the results to strings. This is slow, but
1876 seems to be the only way since all conversion APIs
1877 could potentially execute Python code. */
1878 for (i = 0; i < j; i++) {
1879 PyObject *v = PyList_GET_ITEM(list, i);
1880 if (!PyString_Check(v)) {
1881 const char *buffer;
1882 if (((f->f_binary &&
1883 PyObject_AsReadBuffer(v,
1884 (const void**)&buffer,
1885 &len)) ||
1886 PyObject_AsCharBuffer(v,
1887 &buffer,
1888 &len))) {
1889 PyErr_SetString(PyExc_TypeError,
1890 "writelines() argument must be a sequence of strings");
1891 goto error;
1892 }
1893 line = PyString_FromStringAndSize(buffer,
1894 len);
1895 if (line == NULL)
1896 goto error;
1897 Py_DECREF(v);
1898 PyList_SET_ITEM(list, i, line);
1899 }
1900 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 /* Since we are releasing the global lock, the
1903 following code may *not* execute Python code. */
1904 f->f_softspace = 0;
1905 FILE_BEGIN_ALLOW_THREADS(f)
1906 errno = 0;
1907 for (i = 0; i < j; i++) {
1908 line = PyList_GET_ITEM(list, i);
1909 len = PyString_GET_SIZE(line);
1910 nwritten = fwrite(PyString_AS_STRING(line),
1911 1, len, f->f_fp);
1912 if (nwritten != len) {
1913 FILE_ABORT_ALLOW_THREADS(f)
1914 PyErr_SetFromErrno(PyExc_IOError);
1915 clearerr(f->f_fp);
1916 goto error;
1917 }
1918 }
1919 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001920
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001921 if (j < CHUNKSIZE)
1922 break;
1923 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001924
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001925 Py_INCREF(Py_None);
1926 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001927 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001928 Py_XDECREF(list);
1929 Py_XDECREF(it);
1930 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001931#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001932}
1933
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001934static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001935file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001937 if (f->f_fp == NULL)
1938 return err_closed();
1939 Py_INCREF(f);
1940 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001941}
1942
Georg Brandl98b40ad2006-06-08 14:50:21 +00001943static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001944file_xreadlines(PyFileObject *f)
1945{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001946 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1947 "try 'for line in f' instead", 1) < 0)
1948 return NULL;
1949 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00001950}
1951
1952static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001953file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001954{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001955 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
1956 if (!ret)
1957 /* If error occurred, pass through */
1958 return NULL;
1959 Py_DECREF(ret);
1960 /* We cannot return the result of close since a true
1961 * value will be interpreted as "yes, swallow the
1962 * exception if one was raised inside the with block". */
1963 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00001964}
1965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001966PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001967"readline([size]) -> next line from the file, as a string.\n"
1968"\n"
1969"Retain newline. A non-negative size argument limits the maximum\n"
1970"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001972
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001973PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001974"read([size]) -> read at most size bytes, returned as a string.\n"
1975"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001976"If the size argument is negative or omitted, read until EOF is reached.\n"
1977"Notice that when in non-blocking mode, less data than what was requested\n"
1978"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001979
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001980PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001981"write(str) -> None. Write string str to file.\n"
1982"\n"
1983"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001984"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001987"fileno() -> integer \"file descriptor\".\n"
1988"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001989"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001990
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001991PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001992"seek(offset[, whence]) -> None. Move to new file position.\n"
1993"\n"
1994"Argument offset is a byte count. Optional argument whence defaults to\n"
1995"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1996"(move relative to current position, positive or negative), and 2 (move\n"
1997"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001998"seeking beyond the end of a file). If the file is opened in text mode,\n"
1999"only offsets returned by tell() are legal. Use of other offsets causes\n"
2000"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00002001"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002002"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002003
Guido van Rossumd7047b31995-01-02 19:07:15 +00002004#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002005PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002006"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
2007"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002008"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00002009#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00002010
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002011PyDoc_STRVAR(tell_doc,
2012"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002014PyDoc_STRVAR(readinto_doc,
2015"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002016
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002017PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002018"readlines([size]) -> list of strings, each a line from the file.\n"
2019"\n"
2020"Call readline() repeatedly and return a list of the lines so read.\n"
2021"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002022"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002025"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002026"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002027"For backward compatibility. File objects now include the performance\n"
2028"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002029
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002030PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002031"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002032"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002033"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002034"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002036PyDoc_STRVAR(flush_doc,
2037"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002039PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002040"close() -> None or (perhaps) an integer. Close the file.\n"
2041"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00002042"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002043"further I/O operations. close() may be called more than once without\n"
2044"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002045"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002047PyDoc_STRVAR(isatty_doc,
2048"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002049
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002050PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002051 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002052
Georg Brandl98b40ad2006-06-08 14:50:21 +00002053PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002054 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002055
Tim Petersefc3a3a2001-09-20 07:55:22 +00002056static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002057 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2058 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2059 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2060 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2061 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002062#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002063 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002064#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002065 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2066 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2067 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2068 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2069 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2070 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2071 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2072 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2073 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2074 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2075 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002076};
2077
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002078#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002079
Guido van Rossum6f799372001-09-20 20:46:19 +00002080static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002081 {"mode", T_OBJECT, OFF(f_mode), RO,
2082 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2083 {"name", T_OBJECT, OFF(f_name), RO,
2084 "file name"},
2085 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2086 "file encoding"},
2087 {"errors", T_OBJECT, OFF(f_errors), RO,
2088 "Unicode error handler"},
2089 /* getattr(f, "closed") is implemented without this table */
2090 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002091};
2092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002095{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002096 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002097}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002098static PyObject *
2099get_newlines(PyFileObject *f, void *closure)
2100{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002101 switch (f->f_newlinetypes) {
2102 case NEWLINE_UNKNOWN:
2103 Py_INCREF(Py_None);
2104 return Py_None;
2105 case NEWLINE_CR:
2106 return PyString_FromString("\r");
2107 case NEWLINE_LF:
2108 return PyString_FromString("\n");
2109 case NEWLINE_CR|NEWLINE_LF:
2110 return Py_BuildValue("(ss)", "\r", "\n");
2111 case NEWLINE_CRLF:
2112 return PyString_FromString("\r\n");
2113 case NEWLINE_CR|NEWLINE_CRLF:
2114 return Py_BuildValue("(ss)", "\r", "\r\n");
2115 case NEWLINE_LF|NEWLINE_CRLF:
2116 return Py_BuildValue("(ss)", "\n", "\r\n");
2117 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2118 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2119 default:
2120 PyErr_Format(PyExc_SystemError,
2121 "Unknown newlines value 0x%x\n",
2122 f->f_newlinetypes);
2123 return NULL;
2124 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002125}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002126
Georg Brandl65bb42d2008-03-21 20:38:24 +00002127static PyObject *
2128get_softspace(PyFileObject *f, void *closure)
2129{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002130 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2131 return NULL;
2132 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002133}
2134
2135static int
2136set_softspace(PyFileObject *f, PyObject *value)
2137{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002138 int new;
2139 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2140 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002141
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002142 if (value == NULL) {
2143 PyErr_SetString(PyExc_TypeError,
2144 "can't delete softspace attribute");
2145 return -1;
2146 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002148 new = PyInt_AsLong(value);
2149 if (new == -1 && PyErr_Occurred())
2150 return -1;
2151 f->f_softspace = new;
2152 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002153}
2154
Guido van Rossum32d34c82001-09-20 21:45:26 +00002155static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002156 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2157 {"newlines", (getter)get_newlines, NULL,
2158 "end-of-line convention used in this file"},
2159 {"softspace", (getter)get_softspace, (setter)set_softspace,
2160 "flag indicating that a space needs to be printed; used by print"},
2161 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002163
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002164static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002165drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002166{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002167 if (f->f_buf != NULL) {
2168 PyMem_Free(f->f_buf);
2169 f->f_buf = NULL;
2170 }
Guido van Rossum65967252001-04-21 13:20:18 +00002171}
2172
Tim Petersf1827cf2003-09-07 03:30:18 +00002173/* Make sure that file has a readahead buffer with at least one byte
2174 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002175 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002176static int
2177readahead(PyFileObject *f, int bufsize)
2178{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002179 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002180
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002181 if (f->f_buf != NULL) {
2182 if( (f->f_bufend - f->f_bufptr) >= 1)
2183 return 0;
2184 else
2185 drop_readahead(f);
2186 }
2187 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
2188 PyErr_NoMemory();
2189 return -1;
2190 }
2191 FILE_BEGIN_ALLOW_THREADS(f)
2192 errno = 0;
2193 chunksize = Py_UniversalNewlineFread(
2194 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
2195 FILE_END_ALLOW_THREADS(f)
2196 if (chunksize == 0) {
2197 if (ferror(f->f_fp)) {
2198 PyErr_SetFromErrno(PyExc_IOError);
2199 clearerr(f->f_fp);
2200 drop_readahead(f);
2201 return -1;
2202 }
2203 }
2204 f->f_bufptr = f->f_buf;
2205 f->f_bufend = f->f_buf + chunksize;
2206 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002207}
2208
2209/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002210 uninitialized bytes followed by the remainder of the line. Don't be
2211 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002212 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2213
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002214static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002215readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2216{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002217 PyStringObject* s;
2218 char *bufptr;
2219 char *buf;
2220 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002221
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002222 if (f->f_buf == NULL)
2223 if (readahead(f, bufsize) < 0)
2224 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002225
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002226 len = f->f_bufend - f->f_bufptr;
2227 if (len == 0)
2228 return (PyStringObject *)
2229 PyString_FromStringAndSize(NULL, skip);
2230 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
2231 if (bufptr != NULL) {
2232 bufptr++; /* Count the '\n' */
2233 len = bufptr - f->f_bufptr;
2234 s = (PyStringObject *)
2235 PyString_FromStringAndSize(NULL, skip+len);
2236 if (s == NULL)
2237 return NULL;
2238 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2239 f->f_bufptr = bufptr;
2240 if (bufptr == f->f_bufend)
2241 drop_readahead(f);
2242 } else {
2243 bufptr = f->f_bufptr;
2244 buf = f->f_buf;
2245 f->f_buf = NULL; /* Force new readahead buffer */
2246 assert(skip+len < INT_MAX);
2247 s = readahead_get_line_skip(
2248 f, (int)(skip+len), bufsize + (bufsize>>2) );
2249 if (s == NULL) {
2250 PyMem_Free(buf);
2251 return NULL;
2252 }
2253 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2254 PyMem_Free(buf);
2255 }
2256 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002257}
2258
2259/* A larger buffer size may actually decrease performance. */
2260#define READAHEAD_BUFSIZE 8192
2261
2262static PyObject *
2263file_iternext(PyFileObject *f)
2264{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002265 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002266
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002267 if (f->f_fp == NULL)
2268 return err_closed();
2269 if (!f->readable)
2270 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002271
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002272 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2273 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2274 Py_XDECREF(l);
2275 return NULL;
2276 }
2277 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002278}
2279
2280
Tim Peters59c9a642001-09-13 05:38:56 +00002281static PyObject *
2282file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2283{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002284 PyObject *self;
2285 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002286
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002287 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002288
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002289 if (not_yet_string == NULL) {
2290 not_yet_string = PyString_InternFromString("<uninitialized file>");
2291 if (not_yet_string == NULL)
2292 return NULL;
2293 }
Tim Peters44410012001-09-14 03:26:08 +00002294
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002295 self = type->tp_alloc(type, 0);
2296 if (self != NULL) {
2297 /* Always fill in the name and mode, so that nobody else
2298 needs to special-case NULLs there. */
2299 Py_INCREF(not_yet_string);
2300 ((PyFileObject *)self)->f_name = not_yet_string;
2301 Py_INCREF(not_yet_string);
2302 ((PyFileObject *)self)->f_mode = not_yet_string;
2303 Py_INCREF(Py_None);
2304 ((PyFileObject *)self)->f_encoding = Py_None;
2305 Py_INCREF(Py_None);
2306 ((PyFileObject *)self)->f_errors = Py_None;
2307 ((PyFileObject *)self)->weakreflist = NULL;
2308 ((PyFileObject *)self)->unlocked_count = 0;
2309 }
2310 return self;
Tim Peters44410012001-09-14 03:26:08 +00002311}
2312
2313static int
2314file_init(PyObject *self, PyObject *args, PyObject *kwds)
2315{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002316 PyFileObject *foself = (PyFileObject *)self;
2317 int ret = 0;
2318 static char *kwlist[] = {"name", "mode", "buffering", 0};
2319 char *name = NULL;
2320 char *mode = "r";
2321 int bufsize = -1;
2322 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002323#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002324 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002325#endif
Tim Peters44410012001-09-14 03:26:08 +00002326
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002327 assert(PyFile_Check(self));
2328 if (foself->f_fp != NULL) {
2329 /* Have to close the existing file first. */
2330 PyObject *closeresult = file_close(foself);
2331 if (closeresult == NULL)
2332 return -1;
2333 Py_DECREF(closeresult);
2334 }
Tim Peters59c9a642001-09-13 05:38:56 +00002335
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002336#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002337 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2338 kwlist, &po, &mode, &bufsize)) {
2339 wideargument = 1;
2340 if (fill_file_fields(foself, NULL, po, mode,
2341 fclose) == NULL)
2342 goto Error;
2343 } else {
2344 /* Drop the argument parsing error as narrow
2345 strings are also valid. */
2346 PyErr_Clear();
2347 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002348#endif
2349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002350 if (!wideargument) {
2351 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002353 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2354 Py_FileSystemDefaultEncoding,
2355 &name,
2356 &mode, &bufsize))
2357 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002359 /* We parse again to get the name as a PyObject */
2360 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2361 kwlist, &o_name, &mode,
2362 &bufsize))
2363 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002364
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002365 if (fill_file_fields(foself, NULL, o_name, mode,
2366 fclose) == NULL)
2367 goto Error;
2368 }
2369 if (open_the_file(foself, name, mode) == NULL)
2370 goto Error;
2371 foself->f_setbuf = NULL;
2372 PyFile_SetBufSize(self, bufsize);
2373 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002374
2375Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 ret = -1;
2377 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002378Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002379 PyMem_Free(name); /* free the encoded string */
2380 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002381}
2382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002383PyDoc_VAR(file_doc) =
2384PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002385"file(name[, mode[, buffering]]) -> file object\n"
2386"\n"
2387"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2388"writing or appending. The file will be created if it doesn't exist\n"
2389"when opened for writing or appending; it will be truncated when\n"
2390"opened for writing. Add a 'b' to the mode for binary files.\n"
2391"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2392"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002393"buffered, and larger numbers specify the buffer size. The preferred way\n"
2394"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002395)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002396PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002397"Add a 'U' to mode to open the file for input with universal newline\n"
2398"support. Any line ending in the input file will be seen as a '\\n'\n"
2399"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2400"the value for this attribute is one of None (no newline read yet),\n"
2401"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2402"\n"
2403"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002404);
Tim Peters59c9a642001-09-13 05:38:56 +00002405
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002406PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002407 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2408 "file",
2409 sizeof(PyFileObject),
2410 0,
2411 (destructor)file_dealloc, /* tp_dealloc */
2412 0, /* tp_print */
2413 0, /* tp_getattr */
2414 0, /* tp_setattr */
2415 0, /* tp_compare */
2416 (reprfunc)file_repr, /* tp_repr */
2417 0, /* tp_as_number */
2418 0, /* tp_as_sequence */
2419 0, /* tp_as_mapping */
2420 0, /* tp_hash */
2421 0, /* tp_call */
2422 0, /* tp_str */
2423 PyObject_GenericGetAttr, /* tp_getattro */
2424 /* softspace is writable: we must supply tp_setattro */
2425 PyObject_GenericSetAttr, /* tp_setattro */
2426 0, /* tp_as_buffer */
2427 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2428 file_doc, /* tp_doc */
2429 0, /* tp_traverse */
2430 0, /* tp_clear */
2431 0, /* tp_richcompare */
2432 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2433 (getiterfunc)file_self, /* tp_iter */
2434 (iternextfunc)file_iternext, /* tp_iternext */
2435 file_methods, /* tp_methods */
2436 file_memberlist, /* tp_members */
2437 file_getsetlist, /* tp_getset */
2438 0, /* tp_base */
2439 0, /* tp_dict */
2440 0, /* tp_descr_get */
2441 0, /* tp_descr_set */
2442 0, /* tp_dictoffset */
2443 file_init, /* tp_init */
2444 PyType_GenericAlloc, /* tp_alloc */
2445 file_new, /* tp_new */
2446 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002447};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002448
2449/* Interface for the 'soft space' between print items. */
2450
2451int
Fred Drakefd99de62000-07-09 05:02:18 +00002452PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002453{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002454 long oldflag = 0;
2455 if (f == NULL) {
2456 /* Do nothing */
2457 }
2458 else if (PyFile_Check(f)) {
2459 oldflag = ((PyFileObject *)f)->f_softspace;
2460 ((PyFileObject *)f)->f_softspace = newflag;
2461 }
2462 else {
2463 PyObject *v;
2464 v = PyObject_GetAttrString(f, "softspace");
2465 if (v == NULL)
2466 PyErr_Clear();
2467 else {
2468 if (PyInt_Check(v))
2469 oldflag = PyInt_AsLong(v);
2470 assert(oldflag < INT_MAX);
2471 Py_DECREF(v);
2472 }
2473 v = PyInt_FromLong((long)newflag);
2474 if (v == NULL)
2475 PyErr_Clear();
2476 else {
2477 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2478 PyErr_Clear();
2479 Py_DECREF(v);
2480 }
2481 }
2482 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002483}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002484
2485/* Interfaces to write objects/strings to file-like objects */
2486
2487int
Fred Drakefd99de62000-07-09 05:02:18 +00002488PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002489{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002490 PyObject *writer, *value, *args, *result;
2491 if (f == NULL) {
2492 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2493 return -1;
2494 }
2495 else if (PyFile_Check(f)) {
2496 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002497#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002498 PyObject *enc = fobj->f_encoding;
2499 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002500#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002501 if (fobj->f_fp == NULL) {
2502 err_closed();
2503 return -1;
2504 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002505#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002506 if ((flags & Py_PRINT_RAW) &&
2507 PyUnicode_Check(v) && enc != Py_None) {
2508 char *cenc = PyString_AS_STRING(enc);
2509 char *errors = fobj->f_errors == Py_None ?
2510 "strict" : PyString_AS_STRING(fobj->f_errors);
2511 value = PyUnicode_AsEncodedString(v, cenc, errors);
2512 if (value == NULL)
2513 return -1;
2514 } else {
2515 value = v;
2516 Py_INCREF(value);
2517 }
2518 result = file_PyObject_Print(value, fobj, flags);
2519 Py_DECREF(value);
2520 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002521#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002523#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002524 }
2525 writer = PyObject_GetAttrString(f, "write");
2526 if (writer == NULL)
2527 return -1;
2528 if (flags & Py_PRINT_RAW) {
2529 if (PyUnicode_Check(v)) {
2530 value = v;
2531 Py_INCREF(value);
2532 } else
2533 value = PyObject_Str(v);
2534 }
2535 else
2536 value = PyObject_Repr(v);
2537 if (value == NULL) {
2538 Py_DECREF(writer);
2539 return -1;
2540 }
2541 args = PyTuple_Pack(1, value);
2542 if (args == NULL) {
2543 Py_DECREF(value);
2544 Py_DECREF(writer);
2545 return -1;
2546 }
2547 result = PyEval_CallObject(writer, args);
2548 Py_DECREF(args);
2549 Py_DECREF(value);
2550 Py_DECREF(writer);
2551 if (result == NULL)
2552 return -1;
2553 Py_DECREF(result);
2554 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002555}
2556
Guido van Rossum27a60b11997-05-22 22:25:11 +00002557int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002558PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002559{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002560
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002561 if (f == NULL) {
2562 /* Should be caused by a pre-existing error */
2563 if (!PyErr_Occurred())
2564 PyErr_SetString(PyExc_SystemError,
2565 "null file for PyFile_WriteString");
2566 return -1;
2567 }
2568 else if (PyFile_Check(f)) {
2569 PyFileObject *fobj = (PyFileObject *) f;
2570 FILE *fp = PyFile_AsFile(f);
2571 if (fp == NULL) {
2572 err_closed();
2573 return -1;
2574 }
2575 FILE_BEGIN_ALLOW_THREADS(fobj)
2576 fputs(s, fp);
2577 FILE_END_ALLOW_THREADS(fobj)
2578 return 0;
2579 }
2580 else if (!PyErr_Occurred()) {
2581 PyObject *v = PyString_FromString(s);
2582 int err;
2583 if (v == NULL)
2584 return -1;
2585 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2586 Py_DECREF(v);
2587 return err;
2588 }
2589 else
2590 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002591}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002592
2593/* Try to get a file-descriptor from a Python object. If the object
2594 is an integer or long integer, its value is returned. If not, the
2595 object's fileno() method is called if it exists; the method must return
2596 an integer or long integer, which is returned as the file descriptor value.
2597 -1 is returned on failure.
2598*/
2599
2600int PyObject_AsFileDescriptor(PyObject *o)
2601{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002602 int fd;
2603 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002604
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002605 if (PyInt_Check(o)) {
2606 fd = PyInt_AsLong(o);
2607 }
2608 else if (PyLong_Check(o)) {
2609 fd = PyLong_AsLong(o);
2610 }
2611 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2612 {
2613 PyObject *fno = PyEval_CallObject(meth, NULL);
2614 Py_DECREF(meth);
2615 if (fno == NULL)
2616 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002617
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002618 if (PyInt_Check(fno)) {
2619 fd = PyInt_AsLong(fno);
2620 Py_DECREF(fno);
2621 }
2622 else if (PyLong_Check(fno)) {
2623 fd = PyLong_AsLong(fno);
2624 Py_DECREF(fno);
2625 }
2626 else {
2627 PyErr_SetString(PyExc_TypeError,
2628 "fileno() returned a non-integer");
2629 Py_DECREF(fno);
2630 return -1;
2631 }
2632 }
2633 else {
2634 PyErr_SetString(PyExc_TypeError,
2635 "argument must be an int, or have a fileno() method.");
2636 return -1;
2637 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002638
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002639 if (fd < 0) {
2640 PyErr_Format(PyExc_ValueError,
2641 "file descriptor cannot be a negative integer (%i)",
2642 fd);
2643 return -1;
2644 }
2645 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002646}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002647
Jack Jansen7b8c7542002-04-14 20:12:41 +00002648/* From here on we need access to the real fgets and fread */
2649#undef fgets
2650#undef fread
2651
2652/*
2653** Py_UniversalNewlineFgets is an fgets variation that understands
2654** all of \r, \n and \r\n conventions.
2655** The stream should be opened in binary mode.
2656** If fobj is NULL the routine always does newline conversion, and
2657** it may peek one char ahead to gobble the second char in \r\n.
2658** If fobj is non-NULL it must be a PyFileObject. In this case there
2659** is no readahead but in stead a flag is used to skip a following
2660** \n on the next read. Also, if the file is open in binary mode
2661** the whole conversion is skipped. Finally, the routine keeps track of
2662** the different types of newlines seen.
2663** Note that we need no error handling: fgets() treats error and eof
2664** identically.
2665*/
2666char *
2667Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2668{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002669 char *p = buf;
2670 int c;
2671 int newlinetypes = 0;
2672 int skipnextlf = 0;
2673 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002675 if (fobj) {
2676 if (!PyFile_Check(fobj)) {
2677 errno = ENXIO; /* What can you do... */
2678 return NULL;
2679 }
2680 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2681 if ( !univ_newline )
2682 return fgets(buf, n, stream);
2683 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2684 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2685 }
2686 FLOCKFILE(stream);
2687 c = 'x'; /* Shut up gcc warning */
2688 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2689 if (skipnextlf ) {
2690 skipnextlf = 0;
2691 if (c == '\n') {
2692 /* Seeing a \n here with skipnextlf true
2693 ** means we saw a \r before.
2694 */
2695 newlinetypes |= NEWLINE_CRLF;
2696 c = GETC(stream);
2697 if (c == EOF) break;
2698 } else {
2699 /*
2700 ** Note that c == EOF also brings us here,
2701 ** so we're okay if the last char in the file
2702 ** is a CR.
2703 */
2704 newlinetypes |= NEWLINE_CR;
2705 }
2706 }
2707 if (c == '\r') {
2708 /* A \r is translated into a \n, and we skip
2709 ** an adjacent \n, if any. We don't set the
2710 ** newlinetypes flag until we've seen the next char.
2711 */
2712 skipnextlf = 1;
2713 c = '\n';
2714 } else if ( c == '\n') {
2715 newlinetypes |= NEWLINE_LF;
2716 }
2717 *p++ = c;
2718 if (c == '\n') break;
2719 }
2720 if ( c == EOF && skipnextlf )
2721 newlinetypes |= NEWLINE_CR;
2722 FUNLOCKFILE(stream);
2723 *p = '\0';
2724 if (fobj) {
2725 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2726 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2727 } else if ( skipnextlf ) {
2728 /* If we have no file object we cannot save the
2729 ** skipnextlf flag. We have to readahead, which
2730 ** will cause a pause if we're reading from an
2731 ** interactive stream, but that is very unlikely
2732 ** unless we're doing something silly like
2733 ** execfile("/dev/tty").
2734 */
2735 c = GETC(stream);
2736 if ( c != '\n' )
2737 ungetc(c, stream);
2738 }
2739 if (p == buf)
2740 return NULL;
2741 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002742}
2743
2744/*
2745** Py_UniversalNewlineFread is an fread variation that understands
2746** all of \r, \n and \r\n conventions.
2747** The stream should be opened in binary mode.
2748** fobj must be a PyFileObject. In this case there
2749** is no readahead but in stead a flag is used to skip a following
2750** \n on the next read. Also, if the file is open in binary mode
2751** the whole conversion is skipped. Finally, the routine keeps track of
2752** the different types of newlines seen.
2753*/
2754size_t
Tim Peters058b1412002-04-21 07:29:14 +00002755Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002756 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002757{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002758 char *dst = buf;
2759 PyFileObject *f = (PyFileObject *)fobj;
2760 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002762 assert(buf != NULL);
2763 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002764
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002765 if (!fobj || !PyFile_Check(fobj)) {
2766 errno = ENXIO; /* What can you do... */
2767 return 0;
2768 }
2769 if (!f->f_univ_newline)
2770 return fread(buf, 1, n, stream);
2771 newlinetypes = f->f_newlinetypes;
2772 skipnextlf = f->f_skipnextlf;
2773 /* Invariant: n is the number of bytes remaining to be filled
2774 * in the buffer.
2775 */
2776 while (n) {
2777 size_t nread;
2778 int shortread;
2779 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002780
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002781 nread = fread(dst, 1, n, stream);
2782 assert(nread <= n);
2783 if (nread == 0)
2784 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002785
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002786 n -= nread; /* assuming 1 byte out for each in; will adjust */
2787 shortread = n != 0; /* true iff EOF or error */
2788 while (nread--) {
2789 char c = *src++;
2790 if (c == '\r') {
2791 /* Save as LF and set flag to skip next LF. */
2792 *dst++ = '\n';
2793 skipnextlf = 1;
2794 }
2795 else if (skipnextlf && c == '\n') {
2796 /* Skip LF, and remember we saw CR LF. */
2797 skipnextlf = 0;
2798 newlinetypes |= NEWLINE_CRLF;
2799 ++n;
2800 }
2801 else {
2802 /* Normal char to be stored in buffer. Also
2803 * update the newlinetypes flag if either this
2804 * is an LF or the previous char was a CR.
2805 */
2806 if (c == '\n')
2807 newlinetypes |= NEWLINE_LF;
2808 else if (skipnextlf)
2809 newlinetypes |= NEWLINE_CR;
2810 *dst++ = c;
2811 skipnextlf = 0;
2812 }
2813 }
2814 if (shortread) {
2815 /* If this is EOF, update type flags. */
2816 if (skipnextlf && feof(stream))
2817 newlinetypes |= NEWLINE_CR;
2818 break;
2819 }
2820 }
2821 f->f_newlinetypes = newlinetypes;
2822 f->f_skipnextlf = skipnextlf;
2823 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002824}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002825
2826#ifdef __cplusplus
2827}
2828#endif