blob: 79b9aad4e8943c8fae326456f75a64c563875d3b [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{
Ezio Melotti11f8b682012-03-12 01:17:02 +0200638 PyObject *ret = NULL;
639 PyObject *name = NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000640 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000641#ifdef Py_USING_UNICODE
Ezio Melotti11f8b682012-03-12 01:17:02 +0200642 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000643 const char *name_str = name ? PyString_AsString(name) : "?";
644 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
645 f->f_fp == NULL ? "closed" : "open",
646 name_str,
647 PyString_AsString(f->f_mode),
648 f);
649 Py_XDECREF(name);
650 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000651#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000652 } else {
Ezio Melotti11f8b682012-03-12 01:17:02 +0200653 name = PyObject_Repr(f->f_name);
654 if (name == NULL)
655 return NULL;
656 ret = PyString_FromFormat("<%s file %s, mode '%s' at %p>",
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000657 f->f_fp == NULL ? "closed" : "open",
Ezio Melotti11f8b682012-03-12 01:17:02 +0200658 PyString_AsString(name),
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 PyString_AsString(f->f_mode),
660 f);
Ezio Melotti11f8b682012-03-12 01:17:02 +0200661 Py_XDECREF(name);
662 return ret;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000667file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000668{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 PyObject *sts = close_the_file(f);
Antoine Pitrou83137c22010-05-17 19:56:59 +0000670 if (sts) {
671 PyMem_Free(f->f_setbuf);
672 f->f_setbuf = NULL;
673 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675}
676
Trent Mickf29f47b2000-08-11 19:02:59 +0000677
Guido van Rossumb8552162001-09-05 14:58:11 +0000678/* Our very own off_t-like type, 64-bit if possible */
679#if !defined(HAVE_LARGEFILE_SUPPORT)
680typedef off_t Py_off_t;
681#elif SIZEOF_OFF_T >= 8
682typedef off_t Py_off_t;
683#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000684typedef fpos_t Py_off_t;
685#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000686#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000687#endif
688
689
Trent Mickf29f47b2000-08-11 19:02:59 +0000690/* a portable fseek() function
691 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000692static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000693_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000694{
Guido van Rossumb8552162001-09-05 14:58:11 +0000695#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000696 return fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000697#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000698 return fseeko(fp, offset, whence);
Trent Mickf29f47b2000-08-11 19:02:59 +0000699#elif defined(HAVE_FSEEK64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000700 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000701#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000703#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000704 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
705 and fgetpos() to implement fseek()*/
706 fpos_t pos;
707 switch (whence) {
708 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000709#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 fflush(fp);
711 if (_lseeki64(fileno(fp), 0, 2) == -1)
712 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000713#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 if (fseek(fp, 0, SEEK_END) != 0)
715 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000716#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000717 /* fall through */
718 case SEEK_CUR:
719 if (fgetpos(fp, &pos) != 0)
720 return -1;
721 offset += pos;
722 break;
723 /* case SEEK_SET: break; */
724 }
725 return fsetpos(fp, &offset);
Trent Mickf29f47b2000-08-11 19:02:59 +0000726#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000727#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000728#endif
729}
730
731
732/* a portable ftell() function
733 Return -1 on failure with errno set appropriately, current file
734 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000735static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000736_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000737{
Guido van Rossumb8552162001-09-05 14:58:11 +0000738#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000739 return ftell(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000740#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 return ftello(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000742#elif defined(HAVE_FTELL64)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 return ftell64(fp);
Guido van Rossumb8552162001-09-05 14:58:11 +0000744#elif SIZEOF_FPOS_T >= 8
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 fpos_t pos;
746 if (fgetpos(fp, &pos) != 0)
747 return -1;
748 return pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000749#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000750#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000751#endif
752}
753
754
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000755static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000756file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000757{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000758 int whence;
759 int ret;
760 Py_off_t offset;
761 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000762
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000763 if (f->f_fp == NULL)
764 return err_closed();
765 drop_readahead(f);
766 whence = 0;
767 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
768 return NULL;
769 off_index = PyNumber_Index(offobj);
770 if (!off_index) {
771 if (!PyFloat_Check(offobj))
772 return NULL;
773 /* Deprecated in 2.6 */
774 PyErr_Clear();
775 if (PyErr_WarnEx(PyExc_DeprecationWarning,
776 "integer argument expected, got float",
777 1) < 0)
778 return NULL;
779 off_index = offobj;
780 Py_INCREF(offobj);
781 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000782#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000783 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000784#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 offset = PyLong_Check(off_index) ?
786 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000787#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000788 Py_DECREF(off_index);
789 if (PyErr_Occurred())
790 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000791
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 FILE_BEGIN_ALLOW_THREADS(f)
793 errno = 0;
794 ret = _portable_fseek(f->f_fp, offset, whence);
795 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000796
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 if (ret != 0) {
798 PyErr_SetFromErrno(PyExc_IOError);
799 clearerr(f->f_fp);
800 return NULL;
801 }
802 f->f_skipnextlf = 0;
803 Py_INCREF(Py_None);
804 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000805}
806
Trent Mickf29f47b2000-08-11 19:02:59 +0000807
Guido van Rossumd7047b31995-01-02 19:07:15 +0000808#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000810file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 Py_off_t newsize;
813 PyObject *newsizeobj = NULL;
814 Py_off_t initialpos;
815 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000816
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000817 if (f->f_fp == NULL)
818 return err_closed();
819 if (!f->writable)
820 return err_mode("writing");
821 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
822 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000823
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 /* Get current file position. If the file happens to be open for
825 * update and the last operation was an input operation, C doesn't
826 * define what the later fflush() will do, but we promise truncate()
827 * won't change the current position (and fflush() *does* change it
828 * then at least on Windows). The easiest thing is to capture
829 * current pos now and seek back to it at the end.
830 */
831 FILE_BEGIN_ALLOW_THREADS(f)
832 errno = 0;
833 initialpos = _portable_ftell(f->f_fp);
834 FILE_END_ALLOW_THREADS(f)
835 if (initialpos == -1)
836 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000837
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000838 /* Set newsize to current postion if newsizeobj NULL, else to the
839 * specified value.
840 */
841 if (newsizeobj != NULL) {
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000842#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000843 newsize = PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000844#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000845 newsize = PyLong_Check(newsizeobj) ?
846 PyLong_AsLongLong(newsizeobj) :
847 PyInt_AsLong(newsizeobj);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000848#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 if (PyErr_Occurred())
850 return NULL;
851 }
852 else /* default to current position */
853 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000854
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000855 /* Flush the stream. We're mixing stream-level I/O with lower-level
856 * I/O, and a flush may be necessary to synch both platform views
857 * of the current file state.
858 */
859 FILE_BEGIN_ALLOW_THREADS(f)
860 errno = 0;
861 ret = fflush(f->f_fp);
862 FILE_END_ALLOW_THREADS(f)
863 if (ret != 0)
864 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000865
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000866#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
868 so don't even try using it. */
869 {
870 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000871
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000872 /* Have to move current pos to desired endpoint on Windows. */
873 FILE_BEGIN_ALLOW_THREADS(f)
874 errno = 0;
875 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
876 FILE_END_ALLOW_THREADS(f)
877 if (ret)
878 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000879
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000880 /* Truncate. Note that this may grow the file! */
881 FILE_BEGIN_ALLOW_THREADS(f)
882 errno = 0;
883 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
884 ret = hFile == (HANDLE)-1;
885 if (ret == 0) {
886 ret = SetEndOfFile(hFile) == 0;
887 if (ret)
888 errno = EACCES;
889 }
890 FILE_END_ALLOW_THREADS(f)
891 if (ret)
892 goto onioerror;
893 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000894#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000895 FILE_BEGIN_ALLOW_THREADS(f)
896 errno = 0;
897 ret = ftruncate(fileno(f->f_fp), newsize);
898 FILE_END_ALLOW_THREADS(f)
899 if (ret != 0)
900 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000901#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000902
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000903 /* Restore original file position. */
904 FILE_BEGIN_ALLOW_THREADS(f)
905 errno = 0;
906 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
907 FILE_END_ALLOW_THREADS(f)
908 if (ret)
909 goto onioerror;
Tim Petersf1827cf2003-09-07 03:30:18 +0000910
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000911 Py_INCREF(Py_None);
912 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000913
914onioerror:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000915 PyErr_SetFromErrno(PyExc_IOError);
916 clearerr(f->f_fp);
917 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000918}
919#endif /* HAVE_FTRUNCATE */
920
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000921static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000922file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000923{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000924 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000925
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 if (f->f_fp == NULL)
927 return err_closed();
928 FILE_BEGIN_ALLOW_THREADS(f)
929 errno = 0;
930 pos = _portable_ftell(f->f_fp);
931 FILE_END_ALLOW_THREADS(f)
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000932
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000933 if (pos == -1) {
934 PyErr_SetFromErrno(PyExc_IOError);
935 clearerr(f->f_fp);
936 return NULL;
937 }
938 if (f->f_skipnextlf) {
939 int c;
940 c = GETC(f->f_fp);
941 if (c == '\n') {
942 f->f_newlinetypes |= NEWLINE_CRLF;
943 pos++;
944 f->f_skipnextlf = 0;
945 } else if (c != EOF) ungetc(c, f->f_fp);
946 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000947#if !defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000948 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000949#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000951#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000952}
953
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000955file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000956{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000957 if (f->f_fp == NULL)
958 return err_closed();
959 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000960}
961
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000962static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000963file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000964{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000965 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000966
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 if (f->f_fp == NULL)
968 return err_closed();
969 FILE_BEGIN_ALLOW_THREADS(f)
970 errno = 0;
971 res = fflush(f->f_fp);
972 FILE_END_ALLOW_THREADS(f)
973 if (res != 0) {
974 PyErr_SetFromErrno(PyExc_IOError);
975 clearerr(f->f_fp);
976 return NULL;
977 }
978 Py_INCREF(Py_None);
979 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000980}
981
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000982static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000983file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000984{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 long res;
986 if (f->f_fp == NULL)
987 return err_closed();
988 FILE_BEGIN_ALLOW_THREADS(f)
989 res = isatty((int)fileno(f->f_fp));
990 FILE_END_ALLOW_THREADS(f)
991 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000992}
993
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000994
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000995#if BUFSIZ < 8192
996#define SMALLCHUNK 8192
997#else
998#define SMALLCHUNK BUFSIZ
999#endif
1000
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001001static 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
Nadeem Vawda36248152011-10-13 13:52:46 +02001029 /* Expand the buffer by an amount proportional to the current size,
1030 giving us amortized linear-time behavior. Use a less-than-double
1031 growth factor to avoid excessive allocation. */
1032 return currentsize + (currentsize >> 3) + 6;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001033}
1034
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001035#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1036#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1037#else
1038#ifdef EWOULDBLOCK
1039#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1040#else
1041#ifdef EAGAIN
1042#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1043#else
1044#define BLOCKED_ERRNO(x) 0
1045#endif
1046#endif
1047#endif
1048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001049static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001050file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001051{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001052 long bytesrequested = -1;
1053 size_t bytesread, buffersize, chunksize;
1054 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001055
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001056 if (f->f_fp == NULL)
1057 return err_closed();
1058 if (!f->readable)
1059 return err_mode("reading");
1060 /* refuse to mix with f.next() */
1061 if (f->f_buf != NULL &&
1062 (f->f_bufend - f->f_bufptr) > 0 &&
1063 f->f_buf[0] != '\0')
1064 return err_iterbuffered();
1065 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
1066 return NULL;
1067 if (bytesrequested < 0)
1068 buffersize = new_buffersize(f, (size_t)0);
1069 else
1070 buffersize = bytesrequested;
1071 if (buffersize > PY_SSIZE_T_MAX) {
1072 PyErr_SetString(PyExc_OverflowError,
1073 "requested number of bytes is more than a Python string can hold");
1074 return NULL;
1075 }
1076 v = PyString_FromStringAndSize((char *)NULL, buffersize);
1077 if (v == NULL)
1078 return NULL;
1079 bytesread = 0;
1080 for (;;) {
1081 FILE_BEGIN_ALLOW_THREADS(f)
1082 errno = 0;
1083 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
1084 buffersize - bytesread, f->f_fp, (PyObject *)f);
1085 FILE_END_ALLOW_THREADS(f)
1086 if (chunksize == 0) {
1087 if (!ferror(f->f_fp))
1088 break;
1089 clearerr(f->f_fp);
1090 /* When in non-blocking mode, data shouldn't
1091 * be discarded if a blocking signal was
1092 * received. That will also happen if
1093 * chunksize != 0, but bytesread < buffersize. */
1094 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1095 break;
1096 PyErr_SetFromErrno(PyExc_IOError);
1097 Py_DECREF(v);
1098 return NULL;
1099 }
1100 bytesread += chunksize;
1101 if (bytesread < buffersize) {
1102 clearerr(f->f_fp);
1103 break;
1104 }
1105 if (bytesrequested < 0) {
1106 buffersize = new_buffersize(f, buffersize);
1107 if (_PyString_Resize(&v, buffersize) < 0)
1108 return NULL;
1109 } else {
1110 /* Got what was requested. */
1111 break;
1112 }
1113 }
1114 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1115 return NULL;
1116 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001117}
1118
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001119static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001120file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001121{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001122 char *ptr;
1123 Py_ssize_t ntodo;
1124 Py_ssize_t ndone, nnow;
1125 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001126
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 if (f->f_fp == NULL)
1128 return err_closed();
1129 if (!f->readable)
1130 return err_mode("reading");
1131 /* refuse to mix with f.next() */
1132 if (f->f_buf != NULL &&
1133 (f->f_bufend - f->f_bufptr) > 0 &&
1134 f->f_buf[0] != '\0')
1135 return err_iterbuffered();
1136 if (!PyArg_ParseTuple(args, "w*", &pbuf))
1137 return NULL;
1138 ptr = pbuf.buf;
1139 ntodo = pbuf.len;
1140 ndone = 0;
1141 while (ntodo > 0) {
1142 FILE_BEGIN_ALLOW_THREADS(f)
1143 errno = 0;
1144 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
1145 (PyObject *)f);
1146 FILE_END_ALLOW_THREADS(f)
1147 if (nnow == 0) {
1148 if (!ferror(f->f_fp))
1149 break;
1150 PyErr_SetFromErrno(PyExc_IOError);
1151 clearerr(f->f_fp);
1152 PyBuffer_Release(&pbuf);
1153 return NULL;
1154 }
1155 ndone += nnow;
1156 ntodo -= nnow;
1157 }
1158 PyBuffer_Release(&pbuf);
1159 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001160}
1161
Tim Peters86821b22001-01-07 21:19:34 +00001162/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001163Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001164
1165Under MSVC 6:
1166
Tim Peters1c733232001-01-08 04:02:07 +00001167+ MS threadsafe getc is very slow (multiple layers of function calls before+
1168 after each character, to lock+unlock the stream).
1169+ The stream-locking functions are MS-internal -- can't access them from user
1170 code.
1171+ There's nothing Tim could find in the MS C or platform SDK libraries that
1172 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001173+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1174
1175So we use fgets for speed(!), despite that it's painful.
1176
1177MS realloc is also slow.
1178
Tim Petersf29b64d2001-01-15 06:33:19 +00001179Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1180have):
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001181 Linux a wash
1182 Solaris a wash
1183 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001184
Tim Petersf29b64d2001-01-15 06:33:19 +00001185CAUTION: The C std isn't clear about this: in those cases where fgets
1186writes something into the buffer, can it write into any position beyond the
1187required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1188known on which it does; and it would be a strange way to code fgets. Still,
1189getline_via_fgets may not work correctly if it does. The std test
1190test_bufio.py should fail if platform fgets() routinely writes beyond the
1191trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001192**************************************************************************/
1193
Tim Petersf29b64d2001-01-15 06:33:19 +00001194/* Use this routine if told to, or by default on non-get_unlocked()
1195 * platforms unless told not to. Yikes! Let's spell that out:
1196 * On a platform with getc_unlocked():
1197 * By default, use getc_unlocked().
1198 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1199 * On a platform without getc_unlocked():
1200 * By default, use fgets().
1201 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1202 */
1203#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1204#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001205#endif
1206
Tim Petersf29b64d2001-01-15 06:33:19 +00001207#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1208#undef USE_FGETS_IN_GETLINE
1209#endif
1210
1211#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001212static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001213getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001214{
Tim Peters15b83852001-01-08 00:53:12 +00001215/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001216 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1217 * to fill this much of the buffer with a known value in order to figure out
1218 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1219 * than "most" lines, we waste time filling unused buffer slots. 100 is
1220 * surely adequate for most peoples' email archives, chewing over source code,
1221 * etc -- "regular old text files".
1222 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1223 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1224 * cautions about boosting that. 300 was chosen because the worst real-life
1225 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1226 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001227 */
Tim Peters142297a2001-01-15 10:36:56 +00001228#define INITBUFSIZE 100
1229#define MAXBUFSIZE 300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001230 char* p; /* temp */
1231 char buf[MAXBUFSIZE];
1232 PyObject* v; /* the string object result */
1233 char* pvfree; /* address of next free slot */
1234 char* pvend; /* address one beyond last free slot */
1235 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1236 size_t total_v_size; /* total # of slots in buffer */
1237 size_t increment; /* amount to increment the buffer */
1238 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001239
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001240 /* Optimize for normal case: avoid _PyString_Resize if at all
1241 * possible via first reading into stack buffer "buf".
1242 */
1243 total_v_size = INITBUFSIZE; /* start small and pray */
1244 pvfree = buf;
1245 for (;;) {
1246 FILE_BEGIN_ALLOW_THREADS(f)
1247 pvend = buf + total_v_size;
1248 nfree = pvend - pvfree;
1249 memset(pvfree, '\n', nfree);
1250 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1251 p = fgets(pvfree, (int)nfree, fp);
1252 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001253
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001254 if (p == NULL) {
1255 clearerr(fp);
1256 if (PyErr_CheckSignals())
1257 return NULL;
1258 v = PyString_FromStringAndSize(buf, pvfree - buf);
1259 return v;
1260 }
1261 /* fgets read *something* */
1262 p = memchr(pvfree, '\n', nfree);
1263 if (p != NULL) {
1264 /* Did the \n come from fgets or from us?
1265 * Since fgets stops at the first \n, and then writes
1266 * \0, if it's from fgets a \0 must be next. But if
1267 * that's so, it could not have come from us, since
1268 * the \n's we filled the buffer with have only more
1269 * \n's to the right.
1270 */
1271 if (p+1 < pvend && *(p+1) == '\0') {
1272 /* It's from fgets: we win! In particular,
1273 * we haven't done any mallocs yet, and can
1274 * build the final result on the first try.
1275 */
1276 ++p; /* include \n from fgets */
1277 }
1278 else {
1279 /* Must be from us: fgets didn't fill the
1280 * buffer and didn't find a newline, so it
1281 * must be the last and newline-free line of
1282 * the file.
1283 */
1284 assert(p > pvfree && *(p-1) == '\0');
1285 --p; /* don't include \0 from fgets */
1286 }
1287 v = PyString_FromStringAndSize(buf, p - buf);
1288 return v;
1289 }
1290 /* yuck: fgets overwrote all the newlines, i.e. the entire
1291 * buffer. So this line isn't over yet, or maybe it is but
1292 * we're exactly at EOF. If we haven't already, try using the
1293 * rest of the stack buffer.
1294 */
1295 assert(*(pvend-1) == '\0');
1296 if (pvfree == buf) {
1297 pvfree = pvend - 1; /* overwrite trailing null */
1298 total_v_size = MAXBUFSIZE;
1299 }
1300 else
1301 break;
1302 }
Tim Peters142297a2001-01-15 10:36:56 +00001303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001304 /* The stack buffer isn't big enough; malloc a string object and read
1305 * into its buffer.
1306 */
1307 total_v_size = MAXBUFSIZE << 1;
1308 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
1309 if (v == NULL)
1310 return v;
1311 /* copy over everything except the last null byte */
1312 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1313 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001314
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001315 /* Keep reading stuff into v; if it ever ends successfully, break
1316 * after setting p one beyond the end of the line. The code here is
1317 * very much like the code above, except reads into v's buffer; see
1318 * the code above for detailed comments about the logic.
1319 */
1320 for (;;) {
1321 FILE_BEGIN_ALLOW_THREADS(f)
1322 pvend = BUF(v) + total_v_size;
1323 nfree = pvend - pvfree;
1324 memset(pvfree, '\n', nfree);
1325 assert(nfree < INT_MAX);
1326 p = fgets(pvfree, (int)nfree, fp);
1327 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001328
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001329 if (p == NULL) {
1330 clearerr(fp);
1331 if (PyErr_CheckSignals()) {
1332 Py_DECREF(v);
1333 return NULL;
1334 }
1335 p = pvfree;
1336 break;
1337 }
1338 p = memchr(pvfree, '\n', nfree);
1339 if (p != NULL) {
1340 if (p+1 < pvend && *(p+1) == '\0') {
1341 /* \n came from fgets */
1342 ++p;
1343 break;
1344 }
1345 /* \n came from us; last line of file, no newline */
1346 assert(p > pvfree && *(p-1) == '\0');
1347 --p;
1348 break;
1349 }
1350 /* expand buffer and try again */
1351 assert(*(pvend-1) == '\0');
1352 increment = total_v_size >> 2; /* mild exponential growth */
1353 prev_v_size = total_v_size;
1354 total_v_size += increment;
1355 /* check for overflow */
1356 if (total_v_size <= prev_v_size ||
1357 total_v_size > PY_SSIZE_T_MAX) {
1358 PyErr_SetString(PyExc_OverflowError,
1359 "line is longer than a Python string can hold");
1360 Py_DECREF(v);
1361 return NULL;
1362 }
1363 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1364 return NULL;
1365 /* overwrite the trailing null byte */
1366 pvfree = BUF(v) + (prev_v_size - 1);
1367 }
1368 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1369 return NULL;
1370 return v;
Tim Peters86821b22001-01-07 21:19:34 +00001371#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001372#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001373}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001374#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001375
Guido van Rossum0bd24411991-04-04 15:21:57 +00001376/* Internal routine to get a line.
1377 Size argument interpretation:
1378 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001379 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001380*/
1381
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001382static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001383get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001384{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 FILE *fp = f->f_fp;
1386 int c;
1387 char *buf, *end;
1388 size_t total_v_size; /* total # of slots in buffer */
1389 size_t used_v_size; /* # used slots in buffer */
1390 size_t increment; /* amount to increment the buffer */
1391 PyObject *v;
1392 int newlinetypes = f->f_newlinetypes;
1393 int skipnextlf = f->f_skipnextlf;
1394 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001395
Jack Jansen7b8c7542002-04-14 20:12:41 +00001396#if defined(USE_FGETS_IN_GETLINE)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001397 if (n <= 0 && !univ_newline )
1398 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001399#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001400 total_v_size = n > 0 ? n : 100;
1401 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
1402 if (v == NULL)
1403 return NULL;
1404 buf = BUF(v);
1405 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001406
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001407 for (;;) {
1408 FILE_BEGIN_ALLOW_THREADS(f)
1409 FLOCKFILE(fp);
1410 if (univ_newline) {
1411 c = 'x'; /* Shut up gcc warning */
1412 while ( buf != end && (c = GETC(fp)) != EOF ) {
1413 if (skipnextlf ) {
1414 skipnextlf = 0;
1415 if (c == '\n') {
1416 /* Seeing a \n here with
1417 * skipnextlf true means we
1418 * saw a \r before.
1419 */
1420 newlinetypes |= NEWLINE_CRLF;
1421 c = GETC(fp);
1422 if (c == EOF) break;
1423 } else {
1424 newlinetypes |= NEWLINE_CR;
1425 }
1426 }
1427 if (c == '\r') {
1428 skipnextlf = 1;
1429 c = '\n';
1430 } else if ( c == '\n')
1431 newlinetypes |= NEWLINE_LF;
1432 *buf++ = c;
1433 if (c == '\n') break;
1434 }
1435 if ( c == EOF && skipnextlf )
1436 newlinetypes |= NEWLINE_CR;
1437 } else /* If not universal newlines use the normal loop */
1438 while ((c = GETC(fp)) != EOF &&
1439 (*buf++ = c) != '\n' &&
1440 buf != end)
1441 ;
1442 FUNLOCKFILE(fp);
1443 FILE_END_ALLOW_THREADS(f)
1444 f->f_newlinetypes = newlinetypes;
1445 f->f_skipnextlf = skipnextlf;
1446 if (c == '\n')
1447 break;
1448 if (c == EOF) {
1449 if (ferror(fp)) {
1450 PyErr_SetFromErrno(PyExc_IOError);
1451 clearerr(fp);
1452 Py_DECREF(v);
1453 return NULL;
1454 }
1455 clearerr(fp);
1456 if (PyErr_CheckSignals()) {
1457 Py_DECREF(v);
1458 return NULL;
1459 }
1460 break;
1461 }
1462 /* Must be because buf == end */
1463 if (n > 0)
1464 break;
1465 used_v_size = total_v_size;
1466 increment = total_v_size >> 2; /* mild exponential growth */
1467 total_v_size += increment;
1468 if (total_v_size > PY_SSIZE_T_MAX) {
1469 PyErr_SetString(PyExc_OverflowError,
1470 "line is longer than a Python string can hold");
1471 Py_DECREF(v);
1472 return NULL;
1473 }
1474 if (_PyString_Resize(&v, total_v_size) < 0)
1475 return NULL;
1476 buf = BUF(v) + used_v_size;
1477 end = BUF(v) + total_v_size;
1478 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001479
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001480 used_v_size = buf - BUF(v);
1481 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1482 return NULL;
1483 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001484}
1485
Guido van Rossum0bd24411991-04-04 15:21:57 +00001486/* External C interface */
1487
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001488PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001489PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001490{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 PyObject *result;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001492
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001493 if (f == NULL) {
1494 PyErr_BadInternalCall();
1495 return NULL;
1496 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001498 if (PyFile_Check(f)) {
1499 PyFileObject *fo = (PyFileObject *)f;
1500 if (fo->f_fp == NULL)
1501 return err_closed();
1502 if (!fo->readable)
1503 return err_mode("reading");
1504 /* refuse to mix with f.next() */
1505 if (fo->f_buf != NULL &&
1506 (fo->f_bufend - fo->f_bufptr) > 0 &&
1507 fo->f_buf[0] != '\0')
1508 return err_iterbuffered();
1509 result = get_line(fo, n);
1510 }
1511 else {
1512 PyObject *reader;
1513 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001514
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001515 reader = PyObject_GetAttrString(f, "readline");
1516 if (reader == NULL)
1517 return NULL;
1518 if (n <= 0)
1519 args = PyTuple_New(0);
1520 else
1521 args = Py_BuildValue("(i)", n);
1522 if (args == NULL) {
1523 Py_DECREF(reader);
1524 return NULL;
1525 }
1526 result = PyEval_CallObject(reader, args);
1527 Py_DECREF(reader);
1528 Py_DECREF(args);
1529 if (result != NULL && !PyString_Check(result) &&
1530 !PyUnicode_Check(result)) {
1531 Py_DECREF(result);
1532 result = NULL;
1533 PyErr_SetString(PyExc_TypeError,
1534 "object.readline() returned non-string");
1535 }
1536 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001537
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001538 if (n < 0 && result != NULL && PyString_Check(result)) {
1539 char *s = PyString_AS_STRING(result);
1540 Py_ssize_t len = PyString_GET_SIZE(result);
1541 if (len == 0) {
1542 Py_DECREF(result);
1543 result = NULL;
1544 PyErr_SetString(PyExc_EOFError,
1545 "EOF when reading a line");
1546 }
1547 else if (s[len-1] == '\n') {
1548 if (result->ob_refcnt == 1) {
1549 if (_PyString_Resize(&result, len-1))
1550 return NULL;
1551 }
1552 else {
1553 PyObject *v;
1554 v = PyString_FromStringAndSize(s, len-1);
1555 Py_DECREF(result);
1556 result = v;
1557 }
1558 }
1559 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001560#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001561 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1562 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1563 Py_ssize_t len = PyUnicode_GET_SIZE(result);
1564 if (len == 0) {
1565 Py_DECREF(result);
1566 result = NULL;
1567 PyErr_SetString(PyExc_EOFError,
1568 "EOF when reading a line");
1569 }
1570 else if (s[len-1] == '\n') {
1571 if (result->ob_refcnt == 1)
1572 PyUnicode_Resize(&result, len-1);
1573 else {
1574 PyObject *v;
1575 v = PyUnicode_FromUnicode(s, len-1);
1576 Py_DECREF(result);
1577 result = v;
1578 }
1579 }
1580 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001581#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001582 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001583}
1584
1585/* Python method */
1586
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001587static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001588file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001589{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001590 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001591
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001592 if (f->f_fp == NULL)
1593 return err_closed();
1594 if (!f->readable)
1595 return err_mode("reading");
1596 /* refuse to mix with f.next() */
1597 if (f->f_buf != NULL &&
1598 (f->f_bufend - f->f_bufptr) > 0 &&
1599 f->f_buf[0] != '\0')
1600 return err_iterbuffered();
1601 if (!PyArg_ParseTuple(args, "|i:readline", &n))
1602 return NULL;
1603 if (n == 0)
1604 return PyString_FromString("");
1605 if (n < 0)
1606 n = 0;
1607 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001608}
1609
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001610static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001611file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001612{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001613 long sizehint = 0;
1614 PyObject *list = NULL;
1615 PyObject *line;
1616 char small_buffer[SMALLCHUNK];
1617 char *buffer = small_buffer;
1618 size_t buffersize = SMALLCHUNK;
1619 PyObject *big_buffer = NULL;
1620 size_t nfilled = 0;
1621 size_t nread;
1622 size_t totalread = 0;
1623 char *p, *q, *end;
1624 int err;
1625 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001627 if (f->f_fp == NULL)
1628 return err_closed();
1629 if (!f->readable)
1630 return err_mode("reading");
1631 /* refuse to mix with f.next() */
1632 if (f->f_buf != NULL &&
1633 (f->f_bufend - f->f_bufptr) > 0 &&
1634 f->f_buf[0] != '\0')
1635 return err_iterbuffered();
1636 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
1637 return NULL;
1638 if ((list = PyList_New(0)) == NULL)
1639 return NULL;
1640 for (;;) {
1641 if (shortread)
1642 nread = 0;
1643 else {
1644 FILE_BEGIN_ALLOW_THREADS(f)
1645 errno = 0;
1646 nread = Py_UniversalNewlineFread(buffer+nfilled,
1647 buffersize-nfilled, f->f_fp, (PyObject *)f);
1648 FILE_END_ALLOW_THREADS(f)
1649 shortread = (nread < buffersize-nfilled);
1650 }
1651 if (nread == 0) {
1652 sizehint = 0;
1653 if (!ferror(f->f_fp))
1654 break;
1655 PyErr_SetFromErrno(PyExc_IOError);
1656 clearerr(f->f_fp);
1657 goto error;
1658 }
1659 totalread += nread;
1660 p = (char *)memchr(buffer+nfilled, '\n', nread);
1661 if (p == NULL) {
1662 /* Need a larger buffer to fit this line */
1663 nfilled += nread;
1664 buffersize *= 2;
1665 if (buffersize > PY_SSIZE_T_MAX) {
1666 PyErr_SetString(PyExc_OverflowError,
1667 "line is longer than a Python string can hold");
1668 goto error;
1669 }
1670 if (big_buffer == NULL) {
1671 /* Create the big buffer */
1672 big_buffer = PyString_FromStringAndSize(
1673 NULL, buffersize);
1674 if (big_buffer == NULL)
1675 goto error;
1676 buffer = PyString_AS_STRING(big_buffer);
1677 memcpy(buffer, small_buffer, nfilled);
1678 }
1679 else {
1680 /* Grow the big buffer */
1681 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1682 goto error;
1683 buffer = PyString_AS_STRING(big_buffer);
1684 }
1685 continue;
1686 }
1687 end = buffer+nfilled+nread;
1688 q = buffer;
1689 do {
1690 /* Process complete lines */
1691 p++;
1692 line = PyString_FromStringAndSize(q, p-q);
1693 if (line == NULL)
1694 goto error;
1695 err = PyList_Append(list, line);
1696 Py_DECREF(line);
1697 if (err != 0)
1698 goto error;
1699 q = p;
1700 p = (char *)memchr(q, '\n', end-q);
1701 } while (p != NULL);
1702 /* Move the remaining incomplete line to the start */
1703 nfilled = end-q;
1704 memmove(buffer, q, nfilled);
1705 if (sizehint > 0)
1706 if (totalread >= (size_t)sizehint)
1707 break;
1708 }
1709 if (nfilled != 0) {
1710 /* Partial last line */
1711 line = PyString_FromStringAndSize(buffer, nfilled);
1712 if (line == NULL)
1713 goto error;
1714 if (sizehint > 0) {
1715 /* Need to complete the last line */
1716 PyObject *rest = get_line(f, 0);
1717 if (rest == NULL) {
1718 Py_DECREF(line);
1719 goto error;
1720 }
1721 PyString_Concat(&line, rest);
1722 Py_DECREF(rest);
1723 if (line == NULL)
1724 goto error;
1725 }
1726 err = PyList_Append(list, line);
1727 Py_DECREF(line);
1728 if (err != 0)
1729 goto error;
1730 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001731
1732cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001733 Py_XDECREF(big_buffer);
1734 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001735
1736error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 Py_CLEAR(list);
1738 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001739}
1740
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001741static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001742file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001743{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001744 Py_buffer pbuf;
Victor Stinnercaafd772010-09-08 10:51:01 +00001745 const char *s;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001746 Py_ssize_t n, n2;
Victor Stinnercaafd772010-09-08 10:51:01 +00001747 PyObject *encoded = NULL;
1748
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001749 if (f->f_fp == NULL)
1750 return err_closed();
1751 if (!f->writable)
1752 return err_mode("writing");
1753 if (f->f_binary) {
1754 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1755 return NULL;
1756 s = pbuf.buf;
1757 n = pbuf.len;
Victor Stinnercaafd772010-09-08 10:51:01 +00001758 }
1759 else {
1760 const char *encoding, *errors;
1761 PyObject *text;
1762 if (!PyArg_ParseTuple(args, "O", &text))
1763 return NULL;
1764
1765 if (PyString_Check(text)) {
1766 s = PyString_AS_STRING(text);
1767 n = PyString_GET_SIZE(text);
1768 } else if (PyUnicode_Check(text)) {
1769 if (f->f_encoding != Py_None)
1770 encoding = PyString_AS_STRING(f->f_encoding);
1771 else
1772 encoding = PyUnicode_GetDefaultEncoding();
1773 if (f->f_errors != Py_None)
1774 errors = PyString_AS_STRING(f->f_errors);
1775 else
1776 errors = "strict";
1777 encoded = PyUnicode_AsEncodedString(text, encoding, errors);
1778 if (encoded == NULL)
1779 return NULL;
1780 s = PyString_AS_STRING(encoded);
1781 n = PyString_GET_SIZE(encoded);
1782 } else {
1783 if (PyObject_AsCharBuffer(text, &s, &n))
1784 return NULL;
1785 }
1786 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001787 f->f_softspace = 0;
1788 FILE_BEGIN_ALLOW_THREADS(f)
1789 errno = 0;
1790 n2 = fwrite(s, 1, n, f->f_fp);
1791 FILE_END_ALLOW_THREADS(f)
Victor Stinnercaafd772010-09-08 10:51:01 +00001792 Py_XDECREF(encoded);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001793 if (f->f_binary)
1794 PyBuffer_Release(&pbuf);
1795 if (n2 != n) {
1796 PyErr_SetFromErrno(PyExc_IOError);
1797 clearerr(f->f_fp);
1798 return NULL;
1799 }
1800 Py_INCREF(Py_None);
1801 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001802}
1803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001804static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001805file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001806{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001807#define CHUNKSIZE 1000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001808 PyObject *list, *line;
1809 PyObject *it; /* iter(seq) */
1810 PyObject *result;
1811 int index, islist;
1812 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 assert(seq != NULL);
1815 if (f->f_fp == NULL)
1816 return err_closed();
1817 if (!f->writable)
1818 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001819
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001820 result = NULL;
1821 list = NULL;
1822 islist = PyList_Check(seq);
1823 if (islist)
1824 it = NULL;
1825 else {
1826 it = PyObject_GetIter(seq);
1827 if (it == NULL) {
1828 PyErr_SetString(PyExc_TypeError,
1829 "writelines() requires an iterable argument");
1830 return NULL;
1831 }
1832 /* From here on, fail by going to error, to reclaim "it". */
1833 list = PyList_New(CHUNKSIZE);
1834 if (list == NULL)
1835 goto error;
1836 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001837
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001838 /* Strategy: slurp CHUNKSIZE lines into a private list,
1839 checking that they are all strings, then write that list
1840 without holding the interpreter lock, then come back for more. */
1841 for (index = 0; ; index += CHUNKSIZE) {
1842 if (islist) {
1843 Py_XDECREF(list);
1844 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
1845 if (list == NULL)
1846 goto error;
1847 j = PyList_GET_SIZE(list);
1848 }
1849 else {
1850 for (j = 0; j < CHUNKSIZE; j++) {
1851 line = PyIter_Next(it);
1852 if (line == NULL) {
1853 if (PyErr_Occurred())
1854 goto error;
1855 break;
1856 }
1857 PyList_SetItem(list, j, line);
1858 }
Benjamin Petersonbf775542010-10-16 19:20:12 +00001859 /* The iterator might have closed the file on us. */
1860 if (f->f_fp == NULL) {
1861 err_closed();
1862 goto error;
1863 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001864 }
1865 if (j == 0)
1866 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001867
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001868 /* Check that all entries are indeed strings. If not,
1869 apply the same rules as for file.write() and
1870 convert the results to strings. This is slow, but
1871 seems to be the only way since all conversion APIs
1872 could potentially execute Python code. */
1873 for (i = 0; i < j; i++) {
1874 PyObject *v = PyList_GET_ITEM(list, i);
1875 if (!PyString_Check(v)) {
1876 const char *buffer;
1877 if (((f->f_binary &&
1878 PyObject_AsReadBuffer(v,
1879 (const void**)&buffer,
1880 &len)) ||
1881 PyObject_AsCharBuffer(v,
1882 &buffer,
1883 &len))) {
1884 PyErr_SetString(PyExc_TypeError,
1885 "writelines() argument must be a sequence of strings");
1886 goto error;
1887 }
1888 line = PyString_FromStringAndSize(buffer,
1889 len);
1890 if (line == NULL)
1891 goto error;
1892 Py_DECREF(v);
1893 PyList_SET_ITEM(list, i, line);
1894 }
1895 }
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001896
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001897 /* Since we are releasing the global lock, the
1898 following code may *not* execute Python code. */
1899 f->f_softspace = 0;
1900 FILE_BEGIN_ALLOW_THREADS(f)
1901 errno = 0;
1902 for (i = 0; i < j; i++) {
1903 line = PyList_GET_ITEM(list, i);
1904 len = PyString_GET_SIZE(line);
1905 nwritten = fwrite(PyString_AS_STRING(line),
1906 1, len, f->f_fp);
1907 if (nwritten != len) {
1908 FILE_ABORT_ALLOW_THREADS(f)
1909 PyErr_SetFromErrno(PyExc_IOError);
1910 clearerr(f->f_fp);
1911 goto error;
1912 }
1913 }
1914 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001915
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001916 if (j < CHUNKSIZE)
1917 break;
1918 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001919
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 Py_INCREF(Py_None);
1921 result = Py_None;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001922 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001923 Py_XDECREF(list);
1924 Py_XDECREF(it);
1925 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001926#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001927}
1928
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001929static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001930file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001931{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001932 if (f->f_fp == NULL)
1933 return err_closed();
1934 Py_INCREF(f);
1935 return (PyObject *)f;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001936}
1937
Georg Brandl98b40ad2006-06-08 14:50:21 +00001938static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001939file_xreadlines(PyFileObject *f)
1940{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001941 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1942 "try 'for line in f' instead", 1) < 0)
1943 return NULL;
1944 return file_self(f);
Georg Brandla9916b52008-05-17 22:11:54 +00001945}
1946
1947static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001948file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001949{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001950 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
1951 if (!ret)
1952 /* If error occurred, pass through */
1953 return NULL;
1954 Py_DECREF(ret);
1955 /* We cannot return the result of close since a true
1956 * value will be interpreted as "yes, swallow the
1957 * exception if one was raised inside the with block". */
1958 Py_RETURN_NONE;
Georg Brandl98b40ad2006-06-08 14:50:21 +00001959}
1960
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001961PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001962"readline([size]) -> next line from the file, as a string.\n"
1963"\n"
1964"Retain newline. A non-negative size argument limits the maximum\n"
1965"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001966"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001968PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001969"read([size]) -> read at most size bytes, returned as a string.\n"
1970"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001971"If the size argument is negative or omitted, read until EOF is reached.\n"
1972"Notice that when in non-blocking mode, less data than what was requested\n"
1973"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001974
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001975PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001976"write(str) -> None. Write string str to file.\n"
1977"\n"
1978"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001979"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001981PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001982"fileno() -> integer \"file descriptor\".\n"
1983"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001984"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001987"seek(offset[, whence]) -> None. Move to new file position.\n"
1988"\n"
1989"Argument offset is a byte count. Optional argument whence defaults to\n"
1990"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1991"(move relative to current position, positive or negative), and 2 (move\n"
1992"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001993"seeking beyond the end of a file). If the file is opened in text mode,\n"
1994"only offsets returned by tell() are legal. Use of other offsets causes\n"
1995"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001996"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001998
Guido van Rossumd7047b31995-01-02 19:07:15 +00001999#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002000PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002001"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
2002"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002003"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00002004#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00002005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002006PyDoc_STRVAR(tell_doc,
2007"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002008
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002009PyDoc_STRVAR(readinto_doc,
2010"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002011
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002012PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002013"readlines([size]) -> list of strings, each a line from the file.\n"
2014"\n"
2015"Call readline() repeatedly and return a list of the lines so read.\n"
2016"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002017"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002018
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002019PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002020"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002021"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002022"For backward compatibility. File objects now include the performance\n"
2023"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002025PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002026"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002027"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00002028"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002029"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031PyDoc_STRVAR(flush_doc,
2032"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002033
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002034PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00002035"close() -> None or (perhaps) an integer. Close the file.\n"
2036"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00002037"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00002038"further I/O operations. close() may be called more than once without\n"
2039"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002040"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002042PyDoc_STRVAR(isatty_doc,
2043"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002044
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002045PyDoc_STRVAR(enter_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002046 "__enter__() -> self.");
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002047
Georg Brandl98b40ad2006-06-08 14:50:21 +00002048PyDoc_STRVAR(exit_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002049 "__exit__(*excinfo) -> None. Closes the file.");
Georg Brandl98b40ad2006-06-08 14:50:21 +00002050
Tim Petersefc3a3a2001-09-20 07:55:22 +00002051static PyMethodDef file_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002052 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2053 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2054 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2055 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2056 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002057#ifdef HAVE_FTRUNCATE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002058 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002059#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002060 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2061 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
2062 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2063 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2064 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
2065 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2066 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2067 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
2068 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
2069 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
2070 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002071};
2072
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002074
Guido van Rossum6f799372001-09-20 20:46:19 +00002075static PyMemberDef file_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002076 {"mode", T_OBJECT, OFF(f_mode), RO,
2077 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2078 {"name", T_OBJECT, OFF(f_name), RO,
2079 "file name"},
2080 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2081 "file encoding"},
2082 {"errors", T_OBJECT, OFF(f_errors), RO,
2083 "Unicode error handler"},
2084 /* getattr(f, "closed") is implemented without this table */
2085 {NULL} /* Sentinel */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002086};
2087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002088static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002090{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002091 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002092}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002093static PyObject *
2094get_newlines(PyFileObject *f, void *closure)
2095{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002096 switch (f->f_newlinetypes) {
2097 case NEWLINE_UNKNOWN:
2098 Py_INCREF(Py_None);
2099 return Py_None;
2100 case NEWLINE_CR:
2101 return PyString_FromString("\r");
2102 case NEWLINE_LF:
2103 return PyString_FromString("\n");
2104 case NEWLINE_CR|NEWLINE_LF:
2105 return Py_BuildValue("(ss)", "\r", "\n");
2106 case NEWLINE_CRLF:
2107 return PyString_FromString("\r\n");
2108 case NEWLINE_CR|NEWLINE_CRLF:
2109 return Py_BuildValue("(ss)", "\r", "\r\n");
2110 case NEWLINE_LF|NEWLINE_CRLF:
2111 return Py_BuildValue("(ss)", "\n", "\r\n");
2112 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2113 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2114 default:
2115 PyErr_Format(PyExc_SystemError,
2116 "Unknown newlines value 0x%x\n",
2117 f->f_newlinetypes);
2118 return NULL;
2119 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002120}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002121
Georg Brandl65bb42d2008-03-21 20:38:24 +00002122static PyObject *
2123get_softspace(PyFileObject *f, void *closure)
2124{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002125 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2126 return NULL;
2127 return PyInt_FromLong(f->f_softspace);
Georg Brandl65bb42d2008-03-21 20:38:24 +00002128}
2129
2130static int
2131set_softspace(PyFileObject *f, PyObject *value)
2132{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002133 int new;
2134 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2135 return -1;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002136
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002137 if (value == NULL) {
2138 PyErr_SetString(PyExc_TypeError,
2139 "can't delete softspace attribute");
2140 return -1;
2141 }
Georg Brandl65bb42d2008-03-21 20:38:24 +00002142
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002143 new = PyInt_AsLong(value);
2144 if (new == -1 && PyErr_Occurred())
2145 return -1;
2146 f->f_softspace = new;
2147 return 0;
Georg Brandl65bb42d2008-03-21 20:38:24 +00002148}
2149
Guido van Rossum32d34c82001-09-20 21:45:26 +00002150static PyGetSetDef file_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002151 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
2152 {"newlines", (getter)get_newlines, NULL,
2153 "end-of-line convention used in this file"},
2154 {"softspace", (getter)get_softspace, (setter)set_softspace,
2155 "flag indicating that a space needs to be printed; used by print"},
2156 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002158
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002159static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002160drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002161{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002162 if (f->f_buf != NULL) {
2163 PyMem_Free(f->f_buf);
2164 f->f_buf = NULL;
2165 }
Guido van Rossum65967252001-04-21 13:20:18 +00002166}
2167
Tim Petersf1827cf2003-09-07 03:30:18 +00002168/* Make sure that file has a readahead buffer with at least one byte
2169 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002170 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002171static int
2172readahead(PyFileObject *f, int bufsize)
2173{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002174 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002175
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002176 if (f->f_buf != NULL) {
2177 if( (f->f_bufend - f->f_bufptr) >= 1)
2178 return 0;
2179 else
2180 drop_readahead(f);
2181 }
2182 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
2183 PyErr_NoMemory();
2184 return -1;
2185 }
2186 FILE_BEGIN_ALLOW_THREADS(f)
2187 errno = 0;
2188 chunksize = Py_UniversalNewlineFread(
2189 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
2190 FILE_END_ALLOW_THREADS(f)
2191 if (chunksize == 0) {
2192 if (ferror(f->f_fp)) {
2193 PyErr_SetFromErrno(PyExc_IOError);
2194 clearerr(f->f_fp);
2195 drop_readahead(f);
2196 return -1;
2197 }
2198 }
2199 f->f_bufptr = f->f_buf;
2200 f->f_bufend = f->f_buf + chunksize;
2201 return 0;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002202}
2203
2204/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002205 uninitialized bytes followed by the remainder of the line. Don't be
2206 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002207 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2208
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002209static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002210readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2211{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002212 PyStringObject* s;
2213 char *bufptr;
2214 char *buf;
2215 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002216
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002217 if (f->f_buf == NULL)
2218 if (readahead(f, bufsize) < 0)
2219 return NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002220
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002221 len = f->f_bufend - f->f_bufptr;
2222 if (len == 0)
2223 return (PyStringObject *)
2224 PyString_FromStringAndSize(NULL, skip);
2225 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
2226 if (bufptr != NULL) {
2227 bufptr++; /* Count the '\n' */
2228 len = bufptr - f->f_bufptr;
2229 s = (PyStringObject *)
2230 PyString_FromStringAndSize(NULL, skip+len);
2231 if (s == NULL)
2232 return NULL;
2233 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
2234 f->f_bufptr = bufptr;
2235 if (bufptr == f->f_bufend)
2236 drop_readahead(f);
2237 } else {
2238 bufptr = f->f_bufptr;
2239 buf = f->f_buf;
2240 f->f_buf = NULL; /* Force new readahead buffer */
2241 assert(skip+len < INT_MAX);
2242 s = readahead_get_line_skip(
2243 f, (int)(skip+len), bufsize + (bufsize>>2) );
2244 if (s == NULL) {
2245 PyMem_Free(buf);
2246 return NULL;
2247 }
2248 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
2249 PyMem_Free(buf);
2250 }
2251 return s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002252}
2253
2254/* A larger buffer size may actually decrease performance. */
2255#define READAHEAD_BUFSIZE 8192
2256
2257static PyObject *
2258file_iternext(PyFileObject *f)
2259{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002260 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002261
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002262 if (f->f_fp == NULL)
2263 return err_closed();
2264 if (!f->readable)
2265 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002266
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002267 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
2268 if (l == NULL || PyString_GET_SIZE(l) == 0) {
2269 Py_XDECREF(l);
2270 return NULL;
2271 }
2272 return (PyObject *)l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002273}
2274
2275
Tim Peters59c9a642001-09-13 05:38:56 +00002276static PyObject *
2277file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2278{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002279 PyObject *self;
2280 static PyObject *not_yet_string;
Tim Peters44410012001-09-14 03:26:08 +00002281
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002282 assert(type != NULL && type->tp_alloc != NULL);
Tim Peters44410012001-09-14 03:26:08 +00002283
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002284 if (not_yet_string == NULL) {
2285 not_yet_string = PyString_InternFromString("<uninitialized file>");
2286 if (not_yet_string == NULL)
2287 return NULL;
2288 }
Tim Peters44410012001-09-14 03:26:08 +00002289
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002290 self = type->tp_alloc(type, 0);
2291 if (self != NULL) {
2292 /* Always fill in the name and mode, so that nobody else
2293 needs to special-case NULLs there. */
2294 Py_INCREF(not_yet_string);
2295 ((PyFileObject *)self)->f_name = not_yet_string;
2296 Py_INCREF(not_yet_string);
2297 ((PyFileObject *)self)->f_mode = not_yet_string;
2298 Py_INCREF(Py_None);
2299 ((PyFileObject *)self)->f_encoding = Py_None;
2300 Py_INCREF(Py_None);
2301 ((PyFileObject *)self)->f_errors = Py_None;
2302 ((PyFileObject *)self)->weakreflist = NULL;
2303 ((PyFileObject *)self)->unlocked_count = 0;
2304 }
2305 return self;
Tim Peters44410012001-09-14 03:26:08 +00002306}
2307
2308static int
2309file_init(PyObject *self, PyObject *args, PyObject *kwds)
2310{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002311 PyFileObject *foself = (PyFileObject *)self;
2312 int ret = 0;
2313 static char *kwlist[] = {"name", "mode", "buffering", 0};
2314 char *name = NULL;
2315 char *mode = "r";
2316 int bufsize = -1;
2317 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002318#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002319 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002320#endif
Tim Peters44410012001-09-14 03:26:08 +00002321
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002322 assert(PyFile_Check(self));
2323 if (foself->f_fp != NULL) {
2324 /* Have to close the existing file first. */
2325 PyObject *closeresult = file_close(foself);
2326 if (closeresult == NULL)
2327 return -1;
2328 Py_DECREF(closeresult);
2329 }
Tim Peters59c9a642001-09-13 05:38:56 +00002330
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002331#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002332 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2333 kwlist, &po, &mode, &bufsize)) {
2334 wideargument = 1;
2335 if (fill_file_fields(foself, NULL, po, mode,
2336 fclose) == NULL)
2337 goto Error;
2338 } else {
2339 /* Drop the argument parsing error as narrow
2340 strings are also valid. */
2341 PyErr_Clear();
2342 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002343#endif
2344
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002345 if (!wideargument) {
2346 PyObject *o_name;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002347
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002348 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2349 Py_FileSystemDefaultEncoding,
2350 &name,
2351 &mode, &bufsize))
2352 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002353
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002354 /* We parse again to get the name as a PyObject */
2355 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2356 kwlist, &o_name, &mode,
2357 &bufsize))
2358 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002359
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002360 if (fill_file_fields(foself, NULL, o_name, mode,
2361 fclose) == NULL)
2362 goto Error;
2363 }
2364 if (open_the_file(foself, name, mode) == NULL)
2365 goto Error;
2366 foself->f_setbuf = NULL;
2367 PyFile_SetBufSize(self, bufsize);
2368 goto Done;
Tim Peters44410012001-09-14 03:26:08 +00002369
2370Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 ret = -1;
2372 /* fall through */
Tim Peters44410012001-09-14 03:26:08 +00002373Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002374 PyMem_Free(name); /* free the encoded string */
2375 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002376}
2377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002378PyDoc_VAR(file_doc) =
2379PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002380"file(name[, mode[, buffering]]) -> file object\n"
2381"\n"
2382"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2383"writing or appending. The file will be created if it doesn't exist\n"
2384"when opened for writing or appending; it will be truncated when\n"
2385"opened for writing. Add a 'b' to the mode for binary files.\n"
2386"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2387"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002388"buffered, and larger numbers specify the buffer size. The preferred way\n"
2389"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002390)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002391PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002392"Add a 'U' to mode to open the file for input with universal newline\n"
2393"support. Any line ending in the input file will be seen as a '\\n'\n"
2394"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2395"the value for this attribute is one of None (no newline read yet),\n"
2396"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2397"\n"
2398"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002399);
Tim Peters59c9a642001-09-13 05:38:56 +00002400
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002401PyTypeObject PyFile_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002402 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2403 "file",
2404 sizeof(PyFileObject),
2405 0,
2406 (destructor)file_dealloc, /* tp_dealloc */
2407 0, /* tp_print */
2408 0, /* tp_getattr */
2409 0, /* tp_setattr */
2410 0, /* tp_compare */
2411 (reprfunc)file_repr, /* tp_repr */
2412 0, /* tp_as_number */
2413 0, /* tp_as_sequence */
2414 0, /* tp_as_mapping */
2415 0, /* tp_hash */
2416 0, /* tp_call */
2417 0, /* tp_str */
2418 PyObject_GenericGetAttr, /* tp_getattro */
2419 /* softspace is writable: we must supply tp_setattro */
2420 PyObject_GenericSetAttr, /* tp_setattro */
2421 0, /* tp_as_buffer */
2422 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2423 file_doc, /* tp_doc */
2424 0, /* tp_traverse */
2425 0, /* tp_clear */
2426 0, /* tp_richcompare */
2427 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
2428 (getiterfunc)file_self, /* tp_iter */
2429 (iternextfunc)file_iternext, /* tp_iternext */
2430 file_methods, /* tp_methods */
2431 file_memberlist, /* tp_members */
2432 file_getsetlist, /* tp_getset */
2433 0, /* tp_base */
2434 0, /* tp_dict */
2435 0, /* tp_descr_get */
2436 0, /* tp_descr_set */
2437 0, /* tp_dictoffset */
2438 file_init, /* tp_init */
2439 PyType_GenericAlloc, /* tp_alloc */
2440 file_new, /* tp_new */
2441 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002442};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002443
2444/* Interface for the 'soft space' between print items. */
2445
2446int
Fred Drakefd99de62000-07-09 05:02:18 +00002447PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002448{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002449 long oldflag = 0;
2450 if (f == NULL) {
2451 /* Do nothing */
2452 }
2453 else if (PyFile_Check(f)) {
2454 oldflag = ((PyFileObject *)f)->f_softspace;
2455 ((PyFileObject *)f)->f_softspace = newflag;
2456 }
2457 else {
2458 PyObject *v;
2459 v = PyObject_GetAttrString(f, "softspace");
2460 if (v == NULL)
2461 PyErr_Clear();
2462 else {
2463 if (PyInt_Check(v))
2464 oldflag = PyInt_AsLong(v);
2465 assert(oldflag < INT_MAX);
2466 Py_DECREF(v);
2467 }
2468 v = PyInt_FromLong((long)newflag);
2469 if (v == NULL)
2470 PyErr_Clear();
2471 else {
2472 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2473 PyErr_Clear();
2474 Py_DECREF(v);
2475 }
2476 }
2477 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002478}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002479
2480/* Interfaces to write objects/strings to file-like objects */
2481
2482int
Fred Drakefd99de62000-07-09 05:02:18 +00002483PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002484{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002485 PyObject *writer, *value, *args, *result;
2486 if (f == NULL) {
2487 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
2488 return -1;
2489 }
2490 else if (PyFile_Check(f)) {
2491 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002492#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002493 PyObject *enc = fobj->f_encoding;
2494 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002495#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002496 if (fobj->f_fp == NULL) {
2497 err_closed();
2498 return -1;
2499 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002500#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002501 if ((flags & Py_PRINT_RAW) &&
2502 PyUnicode_Check(v) && enc != Py_None) {
2503 char *cenc = PyString_AS_STRING(enc);
2504 char *errors = fobj->f_errors == Py_None ?
2505 "strict" : PyString_AS_STRING(fobj->f_errors);
2506 value = PyUnicode_AsEncodedString(v, cenc, errors);
2507 if (value == NULL)
2508 return -1;
2509 } else {
2510 value = v;
2511 Py_INCREF(value);
2512 }
2513 result = file_PyObject_Print(value, fobj, flags);
2514 Py_DECREF(value);
2515 return result;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002516#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002517 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002518#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002519 }
2520 writer = PyObject_GetAttrString(f, "write");
2521 if (writer == NULL)
2522 return -1;
2523 if (flags & Py_PRINT_RAW) {
2524 if (PyUnicode_Check(v)) {
2525 value = v;
2526 Py_INCREF(value);
2527 } else
2528 value = PyObject_Str(v);
2529 }
2530 else
2531 value = PyObject_Repr(v);
2532 if (value == NULL) {
2533 Py_DECREF(writer);
2534 return -1;
2535 }
2536 args = PyTuple_Pack(1, value);
2537 if (args == NULL) {
2538 Py_DECREF(value);
2539 Py_DECREF(writer);
2540 return -1;
2541 }
2542 result = PyEval_CallObject(writer, args);
2543 Py_DECREF(args);
2544 Py_DECREF(value);
2545 Py_DECREF(writer);
2546 if (result == NULL)
2547 return -1;
2548 Py_DECREF(result);
2549 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002550}
2551
Guido van Rossum27a60b11997-05-22 22:25:11 +00002552int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002553PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002554{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002555
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002556 if (f == NULL) {
2557 /* Should be caused by a pre-existing error */
2558 if (!PyErr_Occurred())
2559 PyErr_SetString(PyExc_SystemError,
2560 "null file for PyFile_WriteString");
2561 return -1;
2562 }
2563 else if (PyFile_Check(f)) {
2564 PyFileObject *fobj = (PyFileObject *) f;
2565 FILE *fp = PyFile_AsFile(f);
2566 if (fp == NULL) {
2567 err_closed();
2568 return -1;
2569 }
2570 FILE_BEGIN_ALLOW_THREADS(fobj)
2571 fputs(s, fp);
2572 FILE_END_ALLOW_THREADS(fobj)
2573 return 0;
2574 }
2575 else if (!PyErr_Occurred()) {
2576 PyObject *v = PyString_FromString(s);
2577 int err;
2578 if (v == NULL)
2579 return -1;
2580 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2581 Py_DECREF(v);
2582 return err;
2583 }
2584 else
2585 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002586}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002587
2588/* Try to get a file-descriptor from a Python object. If the object
2589 is an integer or long integer, its value is returned. If not, the
2590 object's fileno() method is called if it exists; the method must return
2591 an integer or long integer, which is returned as the file descriptor value.
2592 -1 is returned on failure.
2593*/
2594
2595int PyObject_AsFileDescriptor(PyObject *o)
2596{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002597 int fd;
2598 PyObject *meth;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002599
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002600 if (PyInt_Check(o)) {
2601 fd = PyInt_AsLong(o);
2602 }
2603 else if (PyLong_Check(o)) {
2604 fd = PyLong_AsLong(o);
2605 }
2606 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2607 {
2608 PyObject *fno = PyEval_CallObject(meth, NULL);
2609 Py_DECREF(meth);
2610 if (fno == NULL)
2611 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002612
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002613 if (PyInt_Check(fno)) {
2614 fd = PyInt_AsLong(fno);
2615 Py_DECREF(fno);
2616 }
2617 else if (PyLong_Check(fno)) {
2618 fd = PyLong_AsLong(fno);
2619 Py_DECREF(fno);
2620 }
2621 else {
2622 PyErr_SetString(PyExc_TypeError,
2623 "fileno() returned a non-integer");
2624 Py_DECREF(fno);
2625 return -1;
2626 }
2627 }
2628 else {
2629 PyErr_SetString(PyExc_TypeError,
2630 "argument must be an int, or have a fileno() method.");
2631 return -1;
2632 }
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002633
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002634 if (fd < 0) {
2635 PyErr_Format(PyExc_ValueError,
2636 "file descriptor cannot be a negative integer (%i)",
2637 fd);
2638 return -1;
2639 }
2640 return fd;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002641}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002642
Jack Jansen7b8c7542002-04-14 20:12:41 +00002643/* From here on we need access to the real fgets and fread */
2644#undef fgets
2645#undef fread
2646
2647/*
2648** Py_UniversalNewlineFgets is an fgets variation that understands
2649** all of \r, \n and \r\n conventions.
2650** The stream should be opened in binary mode.
2651** If fobj is NULL the routine always does newline conversion, and
2652** it may peek one char ahead to gobble the second char in \r\n.
2653** If fobj is non-NULL it must be a PyFileObject. In this case there
2654** is no readahead but in stead a flag is used to skip a following
2655** \n on the next read. Also, if the file is open in binary mode
2656** the whole conversion is skipped. Finally, the routine keeps track of
2657** the different types of newlines seen.
2658** Note that we need no error handling: fgets() treats error and eof
2659** identically.
2660*/
2661char *
2662Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2663{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002664 char *p = buf;
2665 int c;
2666 int newlinetypes = 0;
2667 int skipnextlf = 0;
2668 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002669
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002670 if (fobj) {
2671 if (!PyFile_Check(fobj)) {
2672 errno = ENXIO; /* What can you do... */
2673 return NULL;
2674 }
2675 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2676 if ( !univ_newline )
2677 return fgets(buf, n, stream);
2678 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2679 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2680 }
2681 FLOCKFILE(stream);
2682 c = 'x'; /* Shut up gcc warning */
2683 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2684 if (skipnextlf ) {
2685 skipnextlf = 0;
2686 if (c == '\n') {
2687 /* Seeing a \n here with skipnextlf true
2688 ** means we saw a \r before.
2689 */
2690 newlinetypes |= NEWLINE_CRLF;
2691 c = GETC(stream);
2692 if (c == EOF) break;
2693 } else {
2694 /*
2695 ** Note that c == EOF also brings us here,
2696 ** so we're okay if the last char in the file
2697 ** is a CR.
2698 */
2699 newlinetypes |= NEWLINE_CR;
2700 }
2701 }
2702 if (c == '\r') {
2703 /* A \r is translated into a \n, and we skip
2704 ** an adjacent \n, if any. We don't set the
2705 ** newlinetypes flag until we've seen the next char.
2706 */
2707 skipnextlf = 1;
2708 c = '\n';
2709 } else if ( c == '\n') {
2710 newlinetypes |= NEWLINE_LF;
2711 }
2712 *p++ = c;
2713 if (c == '\n') break;
2714 }
2715 if ( c == EOF && skipnextlf )
2716 newlinetypes |= NEWLINE_CR;
2717 FUNLOCKFILE(stream);
2718 *p = '\0';
2719 if (fobj) {
2720 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2721 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2722 } else if ( skipnextlf ) {
2723 /* If we have no file object we cannot save the
2724 ** skipnextlf flag. We have to readahead, which
2725 ** will cause a pause if we're reading from an
2726 ** interactive stream, but that is very unlikely
2727 ** unless we're doing something silly like
2728 ** execfile("/dev/tty").
2729 */
2730 c = GETC(stream);
2731 if ( c != '\n' )
2732 ungetc(c, stream);
2733 }
2734 if (p == buf)
2735 return NULL;
2736 return buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002737}
2738
2739/*
2740** Py_UniversalNewlineFread is an fread variation that understands
2741** all of \r, \n and \r\n conventions.
2742** The stream should be opened in binary mode.
2743** fobj must be a PyFileObject. In this case there
2744** is no readahead but in stead a flag is used to skip a following
2745** \n on the next read. Also, if the file is open in binary mode
2746** the whole conversion is skipped. Finally, the routine keeps track of
2747** the different types of newlines seen.
2748*/
2749size_t
Tim Peters058b1412002-04-21 07:29:14 +00002750Py_UniversalNewlineFread(char *buf, size_t n,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002751 FILE *stream, PyObject *fobj)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002752{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002753 char *dst = buf;
2754 PyFileObject *f = (PyFileObject *)fobj;
2755 int newlinetypes, skipnextlf;
Tim Peters058b1412002-04-21 07:29:14 +00002756
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002757 assert(buf != NULL);
2758 assert(stream != NULL);
Tim Peters058b1412002-04-21 07:29:14 +00002759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002760 if (!fobj || !PyFile_Check(fobj)) {
2761 errno = ENXIO; /* What can you do... */
2762 return 0;
2763 }
2764 if (!f->f_univ_newline)
2765 return fread(buf, 1, n, stream);
2766 newlinetypes = f->f_newlinetypes;
2767 skipnextlf = f->f_skipnextlf;
2768 /* Invariant: n is the number of bytes remaining to be filled
2769 * in the buffer.
2770 */
2771 while (n) {
2772 size_t nread;
2773 int shortread;
2774 char *src = dst;
Tim Peters058b1412002-04-21 07:29:14 +00002775
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002776 nread = fread(dst, 1, n, stream);
2777 assert(nread <= n);
2778 if (nread == 0)
2779 break;
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002780
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002781 n -= nread; /* assuming 1 byte out for each in; will adjust */
2782 shortread = n != 0; /* true iff EOF or error */
2783 while (nread--) {
2784 char c = *src++;
2785 if (c == '\r') {
2786 /* Save as LF and set flag to skip next LF. */
2787 *dst++ = '\n';
2788 skipnextlf = 1;
2789 }
2790 else if (skipnextlf && c == '\n') {
2791 /* Skip LF, and remember we saw CR LF. */
2792 skipnextlf = 0;
2793 newlinetypes |= NEWLINE_CRLF;
2794 ++n;
2795 }
2796 else {
2797 /* Normal char to be stored in buffer. Also
2798 * update the newlinetypes flag if either this
2799 * is an LF or the previous char was a CR.
2800 */
2801 if (c == '\n')
2802 newlinetypes |= NEWLINE_LF;
2803 else if (skipnextlf)
2804 newlinetypes |= NEWLINE_CR;
2805 *dst++ = c;
2806 skipnextlf = 0;
2807 }
2808 }
2809 if (shortread) {
2810 /* If this is EOF, update type flags. */
2811 if (skipnextlf && feof(stream))
2812 newlinetypes |= NEWLINE_CR;
2813 break;
2814 }
2815 }
2816 f->f_newlinetypes = newlinetypes;
2817 f->f_skipnextlf = skipnextlf;
2818 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002819}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002820
2821#ifdef __cplusplus
2822}
2823#endif