blob: 32207027e0ce25d33691726c5bc4c78b8794000c [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
Guido van Rossumff7e83d1999-08-27 20:39:37 +000025#ifndef DONT_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 */
40#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{ \
55 fobj->unlocked_count++; \
56 Py_BEGIN_ALLOW_THREADS
57
58#define FILE_END_ALLOW_THREADS(fobj) \
59 Py_END_ALLOW_THREADS \
60 fobj->unlocked_count--; \
61 assert(fobj->unlocked_count >= 0); \
62}
63
64#define FILE_ABORT_ALLOW_THREADS(fobj) \
65 Py_BLOCK_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0);
68
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{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000078 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 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{
84 fobj->unlocked_count++;
85}
86
87void PyFile_DecUseCount(PyFileObject *fobj)
88{
89 fobj->unlocked_count--;
90 assert(fobj->unlocked_count >= 0);
91}
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{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000097 return NULL;
98 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 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{
108 int result;
109 PyFile_IncUseCount(f);
110 result = PyObject_Print(op, f->f_fp, flags);
111 PyFile_DecUseCount(f);
112 return result;
113}
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)
123 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)) {
Neil Schemenauered19b882002-03-23 02:06:50 +0000128 char *msg = strerror(EISDIR);
Benjamin Petersonfe231b02008-12-29 17:47:42 +0000129 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
130 EISDIR, msg, f->f_name);
Neil Schemenauered19b882002-03-23 02:06:50 +0000131 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000132 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000133 return NULL;
134 }
135#endif
136 return f;
137}
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,
142 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000144 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000145 assert(f != NULL);
146 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000147 assert(f->f_fp == NULL);
148
149 Py_DECREF(f->f_name);
150 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000151 Py_DECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000152 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000153
Neal Norwitzb337bb52006-07-17 00:55:45 +0000154 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000155 f->f_name = name;
156
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000157 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000158
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000159 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000160 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000161 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000162 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000163 f->f_univ_newline = (strchr(mode, 'U') != NULL);
164 f->f_newlinetypes = NEWLINE_UNKNOWN;
165 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000166 Py_INCREF(Py_None);
167 f->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +0000168 Py_INCREF(Py_None);
169 f->f_errors = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000170
Neal Norwitzb337bb52006-07-17 00:55:45 +0000171 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000173 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000174 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176}
177
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000178#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
179#define Py_VERIFY_WINNT
180/* The CRT on windows compiled with Visual Studio 2005 and higher may
181 * assert if given invalid mode strings. This is all fine and well
182 * in static languages like C where the mode string is typcially hard
183 * coded. But in Python, were we pass in the mode string from the user,
184 * we need to verify it first manually
185 */
186static int _PyVerify_Mode_WINNT(const char *mode)
187{
188 /* See if mode string is valid on Windows to avoid hard assertions */
189 /* remove leading spacese */
190 int singles = 0;
191 int pairs = 0;
192 int encoding = 0;
193 const char *s, *c;
194
195 while(*mode == ' ') /* strip initial spaces */
196 ++mode;
197 if (!strchr("rwa", *mode)) /* must start with one of these */
198 return 0;
199 while (*++mode) {
200 if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
201 continue;
202 s = "+TD"; /* each of this can appear only once */
203 c = strchr(s, *mode);
204 if (c) {
205 ptrdiff_t idx = s-c;
206 if (singles & (1<<idx))
207 return 0;
208 singles |= (1<<idx);
209 continue;
210 }
211 s = "btcnSR"; /* only one of each letter in the pairs allowed */
212 c = strchr(s, *mode);
213 if (c) {
214 ptrdiff_t idx = (s-c)/2;
215 if (pairs & (1<<idx))
216 return 0;
217 pairs |= (1<<idx);
218 continue;
219 }
220 if (*mode == ',') {
221 encoding = 1;
222 break;
223 }
224 return 0; /* found an invalid char */
225 }
226
227 if (encoding) {
228 char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
229 while (*mode == ' ')
230 ++mode;
231 /* find 'ccs =' */
232 if (strncmp(mode, "ccs", 3))
233 return 0;
234 mode += 3;
235 while (*mode == ' ')
236 ++mode;
237 if (*mode != '=')
238 return 0;
239 while (*mode == ' ')
240 ++mode;
241 for(encoding = 0; encoding<_countof(e); ++encoding) {
242 size_t l = strlen(e[encoding]);
243 if (!strncmp(mode, e[encoding], l)) {
244 mode += l; /* found a valid encoding */
245 break;
246 }
247 }
248 if (encoding == _countof(e))
249 return 0;
250 }
251 /* skip trailing spaces */
252 while (*mode == ' ')
253 ++mode;
254
255 return *mode == '\0'; /* must be at the end of the string */
256}
257#endif
258
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000259/* check for known incorrect mode strings - problem is, platforms are
260 free to accept any mode characters they like and are supposed to
261 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000262 universal newline support is expressly forbidden by PEP 278.
263 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000264 won't know what it is. Non-zero return signals an exception */
265int
266_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000267{
Georg Brandl7b90e162006-05-18 07:01:27 +0000268 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000269 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000270
Georg Brandl7b90e162006-05-18 07:01:27 +0000271 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000272 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000273 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000274 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000275
Georg Brandl7b90e162006-05-18 07:01:27 +0000276 upos = strchr(mode, 'U');
277 if (upos) {
278 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000279
Georg Brandl7b90e162006-05-18 07:01:27 +0000280 if (mode[0] == 'w' || mode[0] == 'a') {
281 PyErr_Format(PyExc_ValueError, "universal newline "
282 "mode can only be used with modes "
283 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000284 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000285 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000286
287 if (mode[0] != 'r') {
288 memmove(mode+1, mode, strlen(mode)+1);
289 mode[0] = 'r';
290 }
291
292 if (!strchr(mode, 'b')) {
293 memmove(mode+2, mode+1, strlen(mode));
294 mode[1] = 'b';
295 }
296 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
297 PyErr_Format(PyExc_ValueError, "mode string must begin with "
298 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000299 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000300 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000301#ifdef Py_VERIFY_WINNT
302 /* additional checks on NT with visual studio 2005 and higher */
303 if (!_PyVerify_Mode_WINNT(mode)) {
304 PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
305 return -1;
306 }
307#endif
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000308 return 0;
309}
310
Tim Peters59c9a642001-09-13 05:38:56 +0000311static PyObject *
312open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Georg Brandl7b90e162006-05-18 07:01:27 +0000314 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000315 assert(f != NULL);
316 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000317#ifdef MS_WINDOWS
318 /* windows ignores the passed name in order to support Unicode */
319 assert(f->f_name != NULL);
320#else
Tim Peters59c9a642001-09-13 05:38:56 +0000321 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000322#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000323 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000324 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000325
Georg Brandl7b90e162006-05-18 07:01:27 +0000326 /* probably need to replace 'U' by 'rb' */
327 newmode = PyMem_MALLOC(strlen(mode) + 3);
328 if (!newmode) {
329 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000330 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000331 }
332 strcpy(newmode, mode);
333
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000334 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000335 f = NULL;
336 goto cleanup;
337 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000338
Tim Peters8fa45672001-09-13 21:01:29 +0000339 /* rexec.py can't stop a user from getting the file() constructor --
340 all they have to do is get *any* file object f, and then do
341 type(f). Here we prevent them from doing damage with it. */
342 if (PyEval_GetRestricted()) {
343 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000344 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000345 f = NULL;
346 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000347 }
Tim Petersa27a1502001-11-09 20:59:14 +0000348 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000349
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000350#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000351 if (PyUnicode_Check(f->f_name)) {
352 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000353 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000354 if (f->f_name && wmode) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000355 FILE_BEGIN_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000356 /* PyUnicode_AS_UNICODE OK without thread
357 lock as it is a simple dereference. */
358 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
359 PyUnicode_AS_UNICODE(wmode));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000360 FILE_END_ALLOW_THREADS(f)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000361 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000362 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000363 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000364#endif
365 if (NULL == f->f_fp && NULL != name) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000366 FILE_BEGIN_ALLOW_THREADS(f)
Georg Brandl7b90e162006-05-18 07:01:27 +0000367 f->f_fp = fopen(name, newmode);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000368 FILE_END_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000369 }
370
Guido van Rossuma08095a1991-02-13 23:25:27 +0000371 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000372#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000373 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
374 * across all Windows flavors. When it sets EINVAL varies
375 * across Windows flavors, the exact conditions aren't
376 * documented, and the answer lies in the OS's implementation
377 * of Win32's CreateFile function (whose source is secret).
378 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000379 * Starting with Visual Studio .NET 2005, EINVAL is correctly
380 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000381 */
382 if (errno == 0) /* bad mode string */
383 errno = EINVAL;
384 else if (errno == EINVAL) /* unknown, but not a mode string */
385 errno = ENOENT;
386#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000387 /* EINVAL is returned when an invalid filename or
388 * an invalid mode is supplied. */
Amaury Forgeot d'Arc17617a02008-09-25 20:52:56 +0000389 if (errno == EINVAL) {
390 PyObject *v;
391 char message[100];
392 PyOS_snprintf(message, 100,
393 "invalid mode ('%.50s') or filename", mode);
394 v = Py_BuildValue("(isO)", errno, message, f->f_name);
395 if (v != NULL) {
396 PyErr_SetObject(PyExc_IOError, v);
397 Py_DECREF(v);
398 }
399 }
Jeremy Hylton41c83212001-11-09 16:17:24 +0000400 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000401 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000402 f = NULL;
403 }
Tim Peters2ea91112002-04-08 04:13:12 +0000404 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000405 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000406
407cleanup:
408 PyMem_FREE(newmode);
409
Tim Peters59c9a642001-09-13 05:38:56 +0000410 return (PyObject *)f;
411}
412
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000413static PyObject *
414close_the_file(PyFileObject *f)
415{
416 int sts = 0;
417 int (*local_close)(FILE *);
418 FILE *local_fp = f->f_fp;
419 if (local_fp != NULL) {
420 local_close = f->f_close;
421 if (local_close != NULL && f->unlocked_count > 0) {
422 if (f->ob_refcnt > 0) {
423 PyErr_SetString(PyExc_IOError,
424 "close() called during concurrent "
425 "operation on the same file object.");
426 } else {
427 /* This should not happen unless someone is
428 * carelessly playing with the PyFileObject
429 * struct fields and/or its associated FILE
430 * pointer. */
431 PyErr_SetString(PyExc_SystemError,
432 "PyFileObject locking error in "
433 "destructor (refcnt <= 0 at close).");
434 }
435 return NULL;
436 }
437 /* NULL out the FILE pointer before releasing the GIL, because
438 * it will not be valid anymore after the close() function is
439 * called. */
440 f->f_fp = NULL;
441 if (local_close != NULL) {
442 Py_BEGIN_ALLOW_THREADS
443 errno = 0;
444 sts = (*local_close)(local_fp);
445 Py_END_ALLOW_THREADS
446 if (sts == EOF)
447 return PyErr_SetFromErrno(PyExc_IOError);
448 if (sts != 0)
449 return PyInt_FromLong((long)sts);
450 }
451 }
452 Py_RETURN_NONE;
453}
454
Tim Peters59c9a642001-09-13 05:38:56 +0000455PyObject *
456PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
457{
Tim Peters44410012001-09-14 03:26:08 +0000458 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
459 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000460 if (f != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000461 PyObject *o_name = PyString_FromString(name);
Neal Norwitzb337bb52006-07-17 00:55:45 +0000462 if (o_name == NULL)
463 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000464 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000465 Py_DECREF(f);
466 f = NULL;
467 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000468 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000469 }
470 return (PyObject *) f;
471}
472
473PyObject *
474PyFile_FromString(char *name, char *mode)
475{
476 extern int fclose(FILE *);
477 PyFileObject *f;
478
479 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
480 if (f != NULL) {
481 if (open_the_file(f, name, mode) == NULL) {
482 Py_DECREF(f);
483 f = NULL;
484 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487}
488
Guido van Rossumb6775db1994-08-01 11:34:53 +0000489void
Fred Drakefd99de62000-07-09 05:02:18 +0000490PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000491{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000492 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000493 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000494 int type;
495 switch (bufsize) {
496 case 0:
497 type = _IONBF;
498 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000499#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000500 case 1:
501 type = _IOLBF;
502 bufsize = BUFSIZ;
503 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000504#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000505 default:
506 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000507#ifndef HAVE_SETVBUF
508 bufsize = BUFSIZ;
509#endif
510 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000511 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000512 fflush(file->f_fp);
513 if (type == _IONBF) {
514 PyMem_Free(file->f_setbuf);
515 file->f_setbuf = NULL;
516 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000517 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
518 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000519 }
520#ifdef HAVE_SETVBUF
521 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000522#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000523 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000524#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000525 }
526}
527
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000528/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000529 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000530
531int
532PyFile_SetEncoding(PyObject *f, const char *enc)
533{
Martin v. Löwis99815892008-06-01 07:20:46 +0000534 return PyFile_SetEncodingAndErrors(f, enc, NULL);
535}
536
537int
538PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
539{
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000540 PyFileObject *file = (PyFileObject*)f;
Martin v. Löwis99815892008-06-01 07:20:46 +0000541 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000542
543 assert(PyFile_Check(f));
Gregory P. Smith99a3dce2008-06-10 17:42:36 +0000544 str = PyString_FromString(enc);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000545 if (!str)
546 return 0;
Martin v. Löwis99815892008-06-01 07:20:46 +0000547 if (errors) {
548 oerrors = PyString_FromString(errors);
549 if (!oerrors) {
550 Py_DECREF(str);
551 return 0;
552 }
553 } else {
554 oerrors = Py_None;
555 Py_INCREF(Py_None);
556 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000557 Py_DECREF(file->f_encoding);
558 file->f_encoding = str;
Martin v. Löwis99815892008-06-01 07:20:46 +0000559 Py_DECREF(file->f_errors);
560 file->f_errors = oerrors;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000561 return 1;
562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000565err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000566{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000568 return NULL;
569}
570
Thomas Woutersc45251a2006-02-12 11:53:32 +0000571/* Refuse regular file I/O if there's data in the iteration-buffer.
572 * Mixing them would cause data to arrive out of order, as the read*
573 * methods don't use the iteration buffer. */
574static PyObject *
575err_iterbuffered(void)
576{
577 PyErr_SetString(PyExc_ValueError,
578 "Mixing iteration and read methods would lose data");
579 return NULL;
580}
581
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000582static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000583
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584/* Methods */
585
586static void
Fred Drakefd99de62000-07-09 05:02:18 +0000587file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000589 PyObject *ret;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000590 if (f->weakreflist != NULL)
591 PyObject_ClearWeakRefs((PyObject *) f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000592 ret = close_the_file(f);
593 if (!ret) {
594 PySys_WriteStderr("close failed in file object destructor:\n");
595 PyErr_Print();
596 }
597 else {
598 Py_DECREF(ret);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000599 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000600 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000601 Py_XDECREF(f->f_name);
602 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000603 Py_XDECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000604 Py_XDECREF(f->f_errors);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000605 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000606 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000607}
608
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000609static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000610file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000612 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000613#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000614 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000615 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000616 const char *name_str = name ? PyString_AsString(name) : "?";
617 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000618 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000619 name_str,
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000620 PyString_AsString(f->f_mode),
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000621 f);
622 Py_XDECREF(name);
623 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000624#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000625 } else {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000626 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000627 f->f_fp == NULL ? "closed" : "open",
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000628 PyString_AsString(f->f_name),
629 PyString_AsString(f->f_mode),
Barry Warsaw7ce36942001-08-24 18:34:26 +0000630 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000631 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632}
633
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000635file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000637 PyObject *sts = close_the_file(f);
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000638 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000639 f->f_setbuf = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000640 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641}
642
Trent Mickf29f47b2000-08-11 19:02:59 +0000643
Guido van Rossumb8552162001-09-05 14:58:11 +0000644/* Our very own off_t-like type, 64-bit if possible */
645#if !defined(HAVE_LARGEFILE_SUPPORT)
646typedef off_t Py_off_t;
647#elif SIZEOF_OFF_T >= 8
648typedef off_t Py_off_t;
649#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000650typedef fpos_t Py_off_t;
651#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000652#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000653#endif
654
655
Trent Mickf29f47b2000-08-11 19:02:59 +0000656/* a portable fseek() function
657 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000658static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000659_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000660{
Guido van Rossumb8552162001-09-05 14:58:11 +0000661#if !defined(HAVE_LARGEFILE_SUPPORT)
662 return fseek(fp, offset, whence);
663#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000664 return fseeko(fp, offset, whence);
665#elif defined(HAVE_FSEEK64)
666 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000667#elif defined(__BEOS__)
668 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000669#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000670 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
671 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000672 fpos_t pos;
673 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000674 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000675#ifdef MS_WINDOWS
676 fflush(fp);
677 if (_lseeki64(fileno(fp), 0, 2) == -1)
678 return -1;
679#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000680 if (fseek(fp, 0, SEEK_END) != 0)
681 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000682#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000683 /* fall through */
684 case SEEK_CUR:
685 if (fgetpos(fp, &pos) != 0)
686 return -1;
687 offset += pos;
688 break;
689 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000690 }
691 return fsetpos(fp, &offset);
692#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000693#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000694#endif
695}
696
697
698/* a portable ftell() function
699 Return -1 on failure with errno set appropriately, current file
700 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000701static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000702_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000703{
Guido van Rossumb8552162001-09-05 14:58:11 +0000704#if !defined(HAVE_LARGEFILE_SUPPORT)
705 return ftell(fp);
706#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
707 return ftello(fp);
708#elif defined(HAVE_FTELL64)
709 return ftell64(fp);
710#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000711 fpos_t pos;
712 if (fgetpos(fp, &pos) != 0)
713 return -1;
714 return pos;
715#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000716#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000717#endif
718}
719
720
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000721static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000722file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000724 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000725 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000726 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000727 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000728
Guido van Rossumd7297e61992-07-06 14:19:26 +0000729 if (f->f_fp == NULL)
730 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000731 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000732 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000733 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000734 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000735 off_index = PyNumber_Index(offobj);
736 if (!off_index) {
737 if (!PyFloat_Check(offobj))
738 return NULL;
739 /* Deprecated in 2.6 */
740 PyErr_Clear();
Benjamin Petersonf19a7b92008-04-27 18:40:21 +0000741 if (PyErr_WarnEx(PyExc_DeprecationWarning,
742 "integer argument expected, got float",
743 1) < 0)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000744 return NULL;
745 off_index = offobj;
746 Py_INCREF(offobj);
747 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000748#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000749 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000750#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000751 offset = PyLong_Check(off_index) ?
752 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000753#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000754 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000755 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000756 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000757
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000758 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000759 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000760 ret = _portable_fseek(f->f_fp, offset, whence);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000761 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000762
Guido van Rossumff4949e1992-08-05 19:58:53 +0000763 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000765 clearerr(f->f_fp);
766 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000767 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000768 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000769 Py_INCREF(Py_None);
770 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000771}
772
Trent Mickf29f47b2000-08-11 19:02:59 +0000773
Guido van Rossumd7047b31995-01-02 19:07:15 +0000774#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000775static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000776file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000777{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000778 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000779 PyObject *newsizeobj = NULL;
780 Py_off_t initialpos;
781 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000782
Guido van Rossumd7047b31995-01-02 19:07:15 +0000783 if (f->f_fp == NULL)
784 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000785 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000786 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000787
Tim Petersf1827cf2003-09-07 03:30:18 +0000788 /* Get current file position. If the file happens to be open for
789 * update and the last operation was an input operation, C doesn't
790 * define what the later fflush() will do, but we promise truncate()
791 * won't change the current position (and fflush() *does* change it
792 * then at least on Windows). The easiest thing is to capture
793 * current pos now and seek back to it at the end.
794 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000795 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000796 errno = 0;
797 initialpos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000798 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000799 if (initialpos == -1)
800 goto onioerror;
801
Tim Petersfb05db22002-03-11 00:24:00 +0000802 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000803 * specified value.
804 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000805 if (newsizeobj != NULL) {
806#if !defined(HAVE_LARGEFILE_SUPPORT)
807 newsize = PyInt_AsLong(newsizeobj);
808#else
809 newsize = PyLong_Check(newsizeobj) ?
810 PyLong_AsLongLong(newsizeobj) :
811 PyInt_AsLong(newsizeobj);
812#endif
813 if (PyErr_Occurred())
814 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000815 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000816 else /* default to current position */
817 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000818
Tim Petersf1827cf2003-09-07 03:30:18 +0000819 /* Flush the stream. We're mixing stream-level I/O with lower-level
820 * I/O, and a flush may be necessary to synch both platform views
821 * of the current file state.
822 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000823 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000824 errno = 0;
825 ret = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000826 FILE_END_ALLOW_THREADS(f)
Tim Petersfb05db22002-03-11 00:24:00 +0000827 if (ret != 0)
828 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000829
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000830#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000831 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000832 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000833 {
Tim Petersfb05db22002-03-11 00:24:00 +0000834 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000835
Tim Petersf1827cf2003-09-07 03:30:18 +0000836 /* Have to move current pos to desired endpoint on Windows. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000837 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000838 errno = 0;
839 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000840 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000841 if (ret)
842 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000843
Tim Peters8f01b682002-03-12 03:04:44 +0000844 /* Truncate. Note that this may grow the file! */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000845 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters8f01b682002-03-12 03:04:44 +0000846 errno = 0;
847 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000848 ret = hFile == (HANDLE)-1;
849 if (ret == 0) {
850 ret = SetEndOfFile(hFile) == 0;
851 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000852 errno = EACCES;
853 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000854 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000855 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000856 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000857 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000858#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000859 FILE_BEGIN_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000860 errno = 0;
861 ret = ftruncate(fileno(f->f_fp), newsize);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000862 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000863 if (ret != 0)
864 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000865#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000866
Tim Petersf1827cf2003-09-07 03:30:18 +0000867 /* Restore original file position. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000868 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000869 errno = 0;
870 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000871 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000872 if (ret)
873 goto onioerror;
874
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000875 Py_INCREF(Py_None);
876 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000877
878onioerror:
879 PyErr_SetFromErrno(PyExc_IOError);
880 clearerr(f->f_fp);
881 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000882}
883#endif /* HAVE_FTRUNCATE */
884
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000885static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000886file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000887{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000888 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000889
Guido van Rossumd7297e61992-07-06 14:19:26 +0000890 if (f->f_fp == NULL)
891 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000892 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000893 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000894 pos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000895 FILE_END_ALLOW_THREADS(f)
896
Trent Mickf29f47b2000-08-11 19:02:59 +0000897 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000898 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000899 clearerr(f->f_fp);
900 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000901 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000902 if (f->f_skipnextlf) {
903 int c;
904 c = GETC(f->f_fp);
905 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000906 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000907 pos++;
908 f->f_skipnextlf = 0;
909 } else if (c != EOF) ungetc(c, f->f_fp);
910 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000911#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000912 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000913#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000914 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000915#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000916}
917
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000918static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000919file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000920{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000921 if (f->f_fp == NULL)
922 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000923 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000924}
925
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000926static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000927file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000928{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000929 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000930
Guido van Rossumd7297e61992-07-06 14:19:26 +0000931 if (f->f_fp == NULL)
932 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000933 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000934 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000935 res = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000936 FILE_END_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000937 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000938 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000939 clearerr(f->f_fp);
940 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000941 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000942 Py_INCREF(Py_None);
943 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000944}
945
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000946static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000947file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000948{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000949 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000950 if (f->f_fp == NULL)
951 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000952 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000953 res = isatty((int)fileno(f->f_fp));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000954 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000955 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000956}
957
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000958
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000959#if BUFSIZ < 8192
960#define SMALLCHUNK 8192
961#else
962#define SMALLCHUNK BUFSIZ
963#endif
964
Guido van Rossum3c259041999-01-14 19:00:14 +0000965#if SIZEOF_INT < 4
966#define BIGCHUNK (512 * 32)
967#else
968#define BIGCHUNK (512 * 1024)
969#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000970
971static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000972new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000973{
974#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000975 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000976 struct stat st;
977 if (fstat(fileno(f->f_fp), &st) == 0) {
978 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000979 /* The following is not a bug: we really need to call lseek()
980 *and* ftell(). The reason is that some stdio libraries
981 mistakenly flush their buffer when ftell() is called and
982 the lseek() call it makes fails, thereby throwing away
983 data that cannot be recovered in any way. To avoid this,
984 we first test lseek(), and only call ftell() if lseek()
985 works. We can't use the lseek() value either, because we
986 need to take the amount of buffered data into account.
987 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000988 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000989 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000990 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000991 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000992 if (pos < 0)
993 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000994 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000995 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000996 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000997 }
998#endif
999 if (currentsize > SMALLCHUNK) {
1000 /* Keep doubling until we reach BIGCHUNK;
1001 then keep adding BIGCHUNK. */
1002 if (currentsize <= BIGCHUNK)
1003 return currentsize + currentsize;
1004 else
1005 return currentsize + BIGCHUNK;
1006 }
1007 return currentsize + SMALLCHUNK;
1008}
1009
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001010#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1011#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1012#else
1013#ifdef EWOULDBLOCK
1014#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1015#else
1016#ifdef EAGAIN
1017#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1018#else
1019#define BLOCKED_ERRNO(x) 0
1020#endif
1021#endif
1022#endif
1023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001025file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001026{
Guido van Rossum789a1611997-05-10 22:33:55 +00001027 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001028 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001029 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001030
Guido van Rossumd7297e61992-07-06 14:19:26 +00001031 if (f->f_fp == NULL)
1032 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001033 /* refuse to mix with f.next() */
1034 if (f->f_buf != NULL &&
1035 (f->f_bufend - f->f_bufptr) > 0 &&
1036 f->f_buf[0] != '\0')
1037 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001038 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +00001039 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001040 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +00001041 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001042 else
1043 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001044 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001045 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001046 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001047 return NULL;
1048 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001049 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001050 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001051 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001052 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001053 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001054 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001055 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001056 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001057 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001058 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001059 if (chunksize == 0) {
1060 if (!ferror(f->f_fp))
1061 break;
Guido van Rossum6263d541997-05-10 22:07:25 +00001062 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001063 /* When in non-blocking mode, data shouldn't
1064 * be discarded if a blocking signal was
1065 * received. That will also happen if
1066 * chunksize != 0, but bytesread < buffersize. */
1067 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1068 break;
1069 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +00001070 Py_DECREF(v);
1071 return NULL;
1072 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001073 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001074 if (bytesread < buffersize) {
1075 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001076 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001077 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001078 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +00001079 buffersize = new_buffersize(f, buffersize);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001080 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001081 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001082 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +00001083 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001084 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001085 }
1086 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001087 if (bytesread != buffersize)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001088 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001089 return v;
1090}
1091
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001092static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001093file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001094{
1095 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096 Py_ssize_t ntodo;
1097 Py_ssize_t ndone, nnow;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001098 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001099
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001100 if (f->f_fp == NULL)
1101 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001102 /* refuse to mix with f.next() */
1103 if (f->f_buf != NULL &&
1104 (f->f_bufend - f->f_bufptr) > 0 &&
1105 f->f_buf[0] != '\0')
1106 return err_iterbuffered();
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001107 if (!PyArg_ParseTuple(args, "w*", &pbuf))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001108 return NULL;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001109 ptr = pbuf.buf;
1110 ntodo = pbuf.len;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001111 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001112 while (ntodo > 0) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001113 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001114 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +00001115 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001116 (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001117 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001118 if (nnow == 0) {
1119 if (!ferror(f->f_fp))
1120 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001121 PyErr_SetFromErrno(PyExc_IOError);
1122 clearerr(f->f_fp);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001123 PyBuffer_Release(&pbuf);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001124 return NULL;
1125 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001126 ndone += nnow;
1127 ntodo -= nnow;
1128 }
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001129 PyBuffer_Release(&pbuf);
Neal Norwitz076d1e02006-08-21 18:20:10 +00001130 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001131}
1132
Tim Peters86821b22001-01-07 21:19:34 +00001133/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001134Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001135
1136Under MSVC 6:
1137
Tim Peters1c733232001-01-08 04:02:07 +00001138+ MS threadsafe getc is very slow (multiple layers of function calls before+
1139 after each character, to lock+unlock the stream).
1140+ The stream-locking functions are MS-internal -- can't access them from user
1141 code.
1142+ There's nothing Tim could find in the MS C or platform SDK libraries that
1143 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001144+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1145
1146So we use fgets for speed(!), despite that it's painful.
1147
1148MS realloc is also slow.
1149
Tim Petersf29b64d2001-01-15 06:33:19 +00001150Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1151have):
1152 Linux a wash
1153 Solaris a wash
1154 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001155
Tim Petersf29b64d2001-01-15 06:33:19 +00001156CAUTION: The C std isn't clear about this: in those cases where fgets
1157writes something into the buffer, can it write into any position beyond the
1158required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1159known on which it does; and it would be a strange way to code fgets. Still,
1160getline_via_fgets may not work correctly if it does. The std test
1161test_bufio.py should fail if platform fgets() routinely writes beyond the
1162trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001163**************************************************************************/
1164
Tim Petersf29b64d2001-01-15 06:33:19 +00001165/* Use this routine if told to, or by default on non-get_unlocked()
1166 * platforms unless told not to. Yikes! Let's spell that out:
1167 * On a platform with getc_unlocked():
1168 * By default, use getc_unlocked().
1169 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1170 * On a platform without getc_unlocked():
1171 * By default, use fgets().
1172 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1173 */
1174#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1175#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001176#endif
1177
Tim Petersf29b64d2001-01-15 06:33:19 +00001178#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1179#undef USE_FGETS_IN_GETLINE
1180#endif
1181
1182#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001183static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001184getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001185{
Tim Peters15b83852001-01-08 00:53:12 +00001186/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001187 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1188 * to fill this much of the buffer with a known value in order to figure out
1189 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1190 * than "most" lines, we waste time filling unused buffer slots. 100 is
1191 * surely adequate for most peoples' email archives, chewing over source code,
1192 * etc -- "regular old text files".
1193 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1194 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1195 * cautions about boosting that. 300 was chosen because the worst real-life
1196 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1197 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001198 */
Tim Peters142297a2001-01-15 10:36:56 +00001199#define INITBUFSIZE 100
1200#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001201 char* p; /* temp */
1202 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001203 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001204 char* pvfree; /* address of next free slot */
1205 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001206 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1207 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001208 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001209 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001210
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001211 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001212 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001213 */
Tim Peters142297a2001-01-15 10:36:56 +00001214 total_v_size = INITBUFSIZE; /* start small and pray */
1215 pvfree = buf;
1216 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001217 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters142297a2001-01-15 10:36:56 +00001218 pvend = buf + total_v_size;
1219 nfree = pvend - pvfree;
1220 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001221 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1222 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001223 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001224
Tim Peters142297a2001-01-15 10:36:56 +00001225 if (p == NULL) {
1226 clearerr(fp);
1227 if (PyErr_CheckSignals())
1228 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001229 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001230 return v;
1231 }
Tim Peters142297a2001-01-15 10:36:56 +00001232 /* fgets read *something* */
1233 p = memchr(pvfree, '\n', nfree);
1234 if (p != NULL) {
1235 /* Did the \n come from fgets or from us?
1236 * Since fgets stops at the first \n, and then writes
1237 * \0, if it's from fgets a \0 must be next. But if
1238 * that's so, it could not have come from us, since
1239 * the \n's we filled the buffer with have only more
1240 * \n's to the right.
1241 */
1242 if (p+1 < pvend && *(p+1) == '\0') {
1243 /* It's from fgets: we win! In particular,
1244 * we haven't done any mallocs yet, and can
1245 * build the final result on the first try.
1246 */
1247 ++p; /* include \n from fgets */
1248 }
1249 else {
1250 /* Must be from us: fgets didn't fill the
1251 * buffer and didn't find a newline, so it
1252 * must be the last and newline-free line of
1253 * the file.
1254 */
1255 assert(p > pvfree && *(p-1) == '\0');
1256 --p; /* don't include \0 from fgets */
1257 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001258 v = PyString_FromStringAndSize(buf, p - buf);
Tim Peters142297a2001-01-15 10:36:56 +00001259 return v;
1260 }
1261 /* yuck: fgets overwrote all the newlines, i.e. the entire
1262 * buffer. So this line isn't over yet, or maybe it is but
1263 * we're exactly at EOF. If we haven't already, try using the
1264 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001265 */
Tim Peters142297a2001-01-15 10:36:56 +00001266 assert(*(pvend-1) == '\0');
1267 if (pvfree == buf) {
1268 pvfree = pvend - 1; /* overwrite trailing null */
1269 total_v_size = MAXBUFSIZE;
1270 }
1271 else
1272 break;
Tim Peters86821b22001-01-07 21:19:34 +00001273 }
Tim Peters142297a2001-01-15 10:36:56 +00001274
1275 /* The stack buffer isn't big enough; malloc a string object and read
1276 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001277 */
Tim Petersddea2082002-03-23 10:03:50 +00001278 total_v_size = MAXBUFSIZE << 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001279 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001280 if (v == NULL)
1281 return v;
1282 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001283 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1284 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001285
1286 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001287 * after setting p one beyond the end of the line. The code here is
1288 * very much like the code above, except reads into v's buffer; see
1289 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001290 */
1291 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001292 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001293 pvend = BUF(v) + total_v_size;
1294 nfree = pvend - pvfree;
1295 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001296 assert(nfree < INT_MAX);
1297 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001298 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001299
1300 if (p == NULL) {
1301 clearerr(fp);
1302 if (PyErr_CheckSignals()) {
1303 Py_DECREF(v);
1304 return NULL;
1305 }
1306 p = pvfree;
1307 break;
1308 }
Tim Peters86821b22001-01-07 21:19:34 +00001309 p = memchr(pvfree, '\n', nfree);
1310 if (p != NULL) {
1311 if (p+1 < pvend && *(p+1) == '\0') {
1312 /* \n came from fgets */
1313 ++p;
1314 break;
1315 }
1316 /* \n came from us; last line of file, no newline */
1317 assert(p > pvfree && *(p-1) == '\0');
1318 --p;
1319 break;
1320 }
1321 /* expand buffer and try again */
1322 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001323 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001324 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001325 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001326 /* check for overflow */
1327 if (total_v_size <= prev_v_size ||
1328 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001329 PyErr_SetString(PyExc_OverflowError,
1330 "line is longer than a Python string can hold");
1331 Py_DECREF(v);
1332 return NULL;
1333 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001334 if (_PyString_Resize(&v, (int)total_v_size) < 0)
Tim Peters86821b22001-01-07 21:19:34 +00001335 return NULL;
1336 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001337 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001338 }
1339 if (BUF(v) + total_v_size != p)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001340 _PyString_Resize(&v, p - BUF(v));
Tim Peters86821b22001-01-07 21:19:34 +00001341 return v;
1342#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001343#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001344}
Tim Petersf29b64d2001-01-15 06:33:19 +00001345#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001346
Guido van Rossum0bd24411991-04-04 15:21:57 +00001347/* Internal routine to get a line.
1348 Size argument interpretation:
1349 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001350 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001351*/
1352
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001353static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001354get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001355{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001356 FILE *fp = f->f_fp;
1357 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001358 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001359 size_t total_v_size; /* total # of slots in buffer */
1360 size_t used_v_size; /* # used slots in buffer */
1361 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001363 int newlinetypes = f->f_newlinetypes;
1364 int skipnextlf = f->f_skipnextlf;
1365 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001366
Jack Jansen7b8c7542002-04-14 20:12:41 +00001367#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001368 if (n <= 0 && !univ_newline )
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001369 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001370#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001371 total_v_size = n > 0 ? n : 100;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001372 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001373 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001374 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001375 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001376 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001377
Guido van Rossumce5ba841991-03-06 13:06:18 +00001378 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001379 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001380 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001381 if (univ_newline) {
1382 c = 'x'; /* Shut up gcc warning */
1383 while ( buf != end && (c = GETC(fp)) != EOF ) {
1384 if (skipnextlf ) {
1385 skipnextlf = 0;
1386 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001387 /* Seeing a \n here with
1388 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001389 * saw a \r before.
1390 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001391 newlinetypes |= NEWLINE_CRLF;
1392 c = GETC(fp);
1393 if (c == EOF) break;
1394 } else {
1395 newlinetypes |= NEWLINE_CR;
1396 }
1397 }
1398 if (c == '\r') {
1399 skipnextlf = 1;
1400 c = '\n';
1401 } else if ( c == '\n')
1402 newlinetypes |= NEWLINE_LF;
1403 *buf++ = c;
1404 if (c == '\n') break;
1405 }
1406 if ( c == EOF && skipnextlf )
1407 newlinetypes |= NEWLINE_CR;
1408 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001409 while ((c = GETC(fp)) != EOF &&
1410 (*buf++ = c) != '\n' &&
1411 buf != end)
1412 ;
1413 FUNLOCKFILE(fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001414 FILE_END_ALLOW_THREADS(f)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001415 f->f_newlinetypes = newlinetypes;
1416 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001417 if (c == '\n')
1418 break;
1419 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001420 if (ferror(fp)) {
1421 PyErr_SetFromErrno(PyExc_IOError);
1422 clearerr(fp);
1423 Py_DECREF(v);
1424 return NULL;
1425 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001426 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001427 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001428 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001429 return NULL;
1430 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001431 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001432 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001433 /* Must be because buf == end */
1434 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001435 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001436 used_v_size = total_v_size;
1437 increment = total_v_size >> 2; /* mild exponential growth */
1438 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001439 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001440 PyErr_SetString(PyExc_OverflowError,
1441 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001442 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001443 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001444 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001445 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001446 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001447 buf = BUF(v) + used_v_size;
1448 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001449 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001450
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001451 used_v_size = buf - BUF(v);
1452 if (used_v_size != total_v_size)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001453 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001454 return v;
1455}
1456
Guido van Rossum0bd24411991-04-04 15:21:57 +00001457/* External C interface */
1458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001459PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001460PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001461{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001462 PyObject *result;
1463
Guido van Rossum3165fe61992-09-25 21:59:05 +00001464 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001465 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001466 return NULL;
1467 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001468
1469 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001470 PyFileObject *fo = (PyFileObject *)f;
1471 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001472 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001473 /* refuse to mix with f.next() */
1474 if (fo->f_buf != NULL &&
1475 (fo->f_bufend - fo->f_bufptr) > 0 &&
1476 fo->f_buf[0] != '\0')
1477 return err_iterbuffered();
1478 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001479 }
1480 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001481 PyObject *reader;
1482 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001483
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001485 if (reader == NULL)
1486 return NULL;
1487 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001488 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001489 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001491 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001492 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001493 return NULL;
1494 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001495 result = PyEval_CallObject(reader, args);
1496 Py_DECREF(reader);
1497 Py_DECREF(args);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001498 if (result != NULL && !PyString_Check(result) &&
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001499 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001500 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001501 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001502 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001503 "object.readline() returned non-string");
1504 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001505 }
1506
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001507 if (n < 0 && result != NULL && PyString_Check(result)) {
1508 char *s = PyString_AS_STRING(result);
1509 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001510 if (len == 0) {
1511 Py_DECREF(result);
1512 result = NULL;
1513 PyErr_SetString(PyExc_EOFError,
1514 "EOF when reading a line");
1515 }
1516 else if (s[len-1] == '\n') {
1517 if (result->ob_refcnt == 1)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001518 _PyString_Resize(&result, len-1);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001519 else {
1520 PyObject *v;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001521 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001522 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001523 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001524 }
1525 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001526 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001527#ifdef Py_USING_UNICODE
1528 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1529 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001530 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001531 if (len == 0) {
1532 Py_DECREF(result);
1533 result = NULL;
1534 PyErr_SetString(PyExc_EOFError,
1535 "EOF when reading a line");
1536 }
1537 else if (s[len-1] == '\n') {
1538 if (result->ob_refcnt == 1)
1539 PyUnicode_Resize(&result, len-1);
1540 else {
1541 PyObject *v;
1542 v = PyUnicode_FromUnicode(s, len-1);
1543 Py_DECREF(result);
1544 result = v;
1545 }
1546 }
1547 }
1548#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001549 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001550}
1551
1552/* Python method */
1553
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001554static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001555file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001556{
Guido van Rossum789a1611997-05-10 22:33:55 +00001557 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001558
Guido van Rossumd7297e61992-07-06 14:19:26 +00001559 if (f->f_fp == NULL)
1560 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001561 /* refuse to mix with f.next() */
1562 if (f->f_buf != NULL &&
1563 (f->f_bufend - f->f_bufptr) > 0 &&
1564 f->f_buf[0] != '\0')
1565 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001566 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001567 return NULL;
1568 if (n == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001569 return PyString_FromString("");
Guido van Rossum789a1611997-05-10 22:33:55 +00001570 if (n < 0)
1571 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001572 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001573}
1574
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001575static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001576file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001577{
Guido van Rossum789a1611997-05-10 22:33:55 +00001578 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001579 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001580 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001581 char small_buffer[SMALLCHUNK];
1582 char *buffer = small_buffer;
1583 size_t buffersize = SMALLCHUNK;
1584 PyObject *big_buffer = NULL;
1585 size_t nfilled = 0;
1586 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001587 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001588 char *p, *q, *end;
1589 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001590 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001591
Guido van Rossumd7297e61992-07-06 14:19:26 +00001592 if (f->f_fp == NULL)
1593 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001594 /* refuse to mix with f.next() */
1595 if (f->f_buf != NULL &&
1596 (f->f_bufend - f->f_bufptr) > 0 &&
1597 f->f_buf[0] != '\0')
1598 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001599 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001600 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001601 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001602 return NULL;
1603 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001604 if (shortread)
1605 nread = 0;
1606 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001607 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001608 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001609 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001610 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001611 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001612 shortread = (nread < buffersize-nfilled);
1613 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001614 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001615 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001616 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001617 break;
1618 PyErr_SetFromErrno(PyExc_IOError);
1619 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001620 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001621 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001622 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001623 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001624 if (p == NULL) {
1625 /* Need a larger buffer to fit this line */
1626 nfilled += nread;
1627 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001628 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001629 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001630 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001631 goto error;
1632 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001633 if (big_buffer == NULL) {
1634 /* Create the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001635 big_buffer = PyString_FromStringAndSize(
Guido van Rossum6263d541997-05-10 22:07:25 +00001636 NULL, buffersize);
1637 if (big_buffer == NULL)
1638 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001639 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001640 memcpy(buffer, small_buffer, nfilled);
1641 }
1642 else {
1643 /* Grow the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001644 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
Jack Jansen7b8c7542002-04-14 20:12:41 +00001645 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001646 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001647 }
1648 continue;
1649 }
1650 end = buffer+nfilled+nread;
1651 q = buffer;
1652 do {
1653 /* Process complete lines */
1654 p++;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001655 line = PyString_FromStringAndSize(q, p-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001656 if (line == NULL)
1657 goto error;
1658 err = PyList_Append(list, line);
1659 Py_DECREF(line);
1660 if (err != 0)
1661 goto error;
1662 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001663 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001664 } while (p != NULL);
1665 /* Move the remaining incomplete line to the start */
1666 nfilled = end-q;
1667 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001668 if (sizehint > 0)
1669 if (totalread >= (size_t)sizehint)
1670 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001671 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001672 if (nfilled != 0) {
1673 /* Partial last line */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001674 line = PyString_FromStringAndSize(buffer, nfilled);
Guido van Rossum6263d541997-05-10 22:07:25 +00001675 if (line == NULL)
1676 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001677 if (sizehint > 0) {
1678 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001679 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001680 if (rest == NULL) {
1681 Py_DECREF(line);
1682 goto error;
1683 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001684 PyString_Concat(&line, rest);
Guido van Rossum789a1611997-05-10 22:33:55 +00001685 Py_DECREF(rest);
1686 if (line == NULL)
1687 goto error;
1688 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001689 err = PyList_Append(list, line);
1690 Py_DECREF(line);
1691 if (err != 0)
1692 goto error;
1693 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001694
1695cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001696 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001697 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001698
1699error:
1700 Py_CLEAR(list);
1701 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001702}
1703
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001704static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001705file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001706{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001707 Py_buffer pbuf;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001708 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001709 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001710 if (f->f_fp == NULL)
1711 return err_closed();
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001712 if (f->f_binary) {
1713 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1714 return NULL;
1715 s = pbuf.buf;
1716 n = pbuf.len;
1717 } else
1718 if (!PyArg_ParseTuple(args, "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001719 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001720 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001721 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001722 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001723 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001724 FILE_END_ALLOW_THREADS(f)
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001725 if (f->f_binary)
1726 PyBuffer_Release(&pbuf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001727 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001728 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001729 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001730 return NULL;
1731 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001732 Py_INCREF(Py_None);
1733 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001734}
1735
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001736static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001737file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001738{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001739#define CHUNKSIZE 1000
1740 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001741 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001742 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001743 int index, islist;
1744 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001745
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001746 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001747 if (f->f_fp == NULL)
1748 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001749
1750 result = NULL;
1751 list = NULL;
1752 islist = PyList_Check(seq);
1753 if (islist)
1754 it = NULL;
1755 else {
1756 it = PyObject_GetIter(seq);
1757 if (it == NULL) {
1758 PyErr_SetString(PyExc_TypeError,
1759 "writelines() requires an iterable argument");
1760 return NULL;
1761 }
1762 /* From here on, fail by going to error, to reclaim "it". */
1763 list = PyList_New(CHUNKSIZE);
1764 if (list == NULL)
1765 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001766 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001767
1768 /* Strategy: slurp CHUNKSIZE lines into a private list,
1769 checking that they are all strings, then write that list
1770 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001771 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001772 if (islist) {
1773 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001774 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001775 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001776 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001777 j = PyList_GET_SIZE(list);
1778 }
1779 else {
1780 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001781 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001782 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001783 if (PyErr_Occurred())
1784 goto error;
1785 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001786 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001787 PyList_SetItem(list, j, line);
1788 }
1789 }
1790 if (j == 0)
1791 break;
1792
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001793 /* Check that all entries are indeed strings. If not,
1794 apply the same rules as for file.write() and
1795 convert the results to strings. This is slow, but
1796 seems to be the only way since all conversion APIs
1797 could potentially execute Python code. */
1798 for (i = 0; i < j; i++) {
1799 PyObject *v = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001800 if (!PyString_Check(v)) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001801 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001802 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001803 PyObject_AsReadBuffer(v,
1804 (const void**)&buffer,
1805 &len)) ||
1806 PyObject_AsCharBuffer(v,
1807 &buffer,
1808 &len))) {
1809 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001810 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001811 goto error;
1812 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001813 line = PyString_FromStringAndSize(buffer,
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001814 len);
1815 if (line == NULL)
1816 goto error;
1817 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001818 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001819 }
1820 }
1821
1822 /* Since we are releasing the global lock, the
1823 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001824 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001825 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001826 errno = 0;
1827 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001828 line = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001829 len = PyString_GET_SIZE(line);
1830 nwritten = fwrite(PyString_AS_STRING(line),
Guido van Rossumee70ad12000-03-13 16:27:06 +00001831 1, len, f->f_fp);
1832 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001833 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001834 PyErr_SetFromErrno(PyExc_IOError);
1835 clearerr(f->f_fp);
1836 goto error;
1837 }
1838 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001839 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001840
1841 if (j < CHUNKSIZE)
1842 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001843 }
1844
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001845 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001846 result = Py_None;
1847 error:
1848 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001849 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001850 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001851#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001852}
1853
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001854static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001855file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001856{
1857 if (f->f_fp == NULL)
1858 return err_closed();
1859 Py_INCREF(f);
1860 return (PyObject *)f;
1861}
1862
Georg Brandl98b40ad2006-06-08 14:50:21 +00001863static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001864file_xreadlines(PyFileObject *f)
1865{
1866 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1867 "try 'for line in f' instead", 1) < 0)
1868 return NULL;
1869 return file_self(f);
1870}
1871
1872static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001873file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001874{
Georg Brandlad61bc82008-02-23 15:11:18 +00001875 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001876 if (!ret)
1877 /* If error occurred, pass through */
1878 return NULL;
1879 Py_DECREF(ret);
1880 /* We cannot return the result of close since a true
1881 * value will be interpreted as "yes, swallow the
1882 * exception if one was raised inside the with block". */
1883 Py_RETURN_NONE;
1884}
1885
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001886PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001887"readline([size]) -> next line from the file, as a string.\n"
1888"\n"
1889"Retain newline. A non-negative size argument limits the maximum\n"
1890"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001892
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001893PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001894"read([size]) -> read at most size bytes, returned as a string.\n"
1895"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001896"If the size argument is negative or omitted, read until EOF is reached.\n"
1897"Notice that when in non-blocking mode, less data than what was requested\n"
1898"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001900PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001901"write(str) -> None. Write string str to file.\n"
1902"\n"
1903"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001904"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001906PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001907"fileno() -> integer \"file descriptor\".\n"
1908"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001909"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001911PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001912"seek(offset[, whence]) -> None. Move to new file position.\n"
1913"\n"
1914"Argument offset is a byte count. Optional argument whence defaults to\n"
1915"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1916"(move relative to current position, positive or negative), and 2 (move\n"
1917"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001918"seeking beyond the end of a file). If the file is opened in text mode,\n"
1919"only offsets returned by tell() are legal. Use of other offsets causes\n"
1920"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001921"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001922"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001923
Guido van Rossumd7047b31995-01-02 19:07:15 +00001924#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001925PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001926"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1927"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001928"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001929#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001931PyDoc_STRVAR(tell_doc,
1932"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001934PyDoc_STRVAR(readinto_doc,
1935"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001937PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001938"readlines([size]) -> list of strings, each a line from the file.\n"
1939"\n"
1940"Call readline() repeatedly and return a list of the lines so read.\n"
1941"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001942"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001943
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001944PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001945"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001946"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001947"For backward compatibility. File objects now include the performance\n"
1948"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001950PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001951"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001952"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001953"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001954"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001956PyDoc_STRVAR(flush_doc,
1957"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001958
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001959PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001960"close() -> None or (perhaps) an integer. Close the file.\n"
1961"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001962"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001963"further I/O operations. close() may be called more than once without\n"
1964"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001965"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967PyDoc_STRVAR(isatty_doc,
1968"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001969
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001970PyDoc_STRVAR(enter_doc,
1971 "__enter__() -> self.");
1972
Georg Brandl98b40ad2006-06-08 14:50:21 +00001973PyDoc_STRVAR(exit_doc,
1974 "__exit__(*excinfo) -> None. Closes the file.");
1975
Tim Petersefc3a3a2001-09-20 07:55:22 +00001976static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001977 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1978 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1979 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1980 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1981 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001982#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001983 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001984#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001985 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1986 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
Georg Brandla9916b52008-05-17 22:11:54 +00001987 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
1988 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
1989 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001990 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1991 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1992 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001993 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00001994 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001995 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001996};
1997
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001998#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001999
Guido van Rossum6f799372001-09-20 20:46:19 +00002000static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00002001 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00002002 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00002003 {"name", T_OBJECT, OFF(f_name), RO,
2004 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002005 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2006 "file encoding"},
Martin v. Löwis99815892008-06-01 07:20:46 +00002007 {"errors", T_OBJECT, OFF(f_errors), RO,
2008 "Unicode error handler"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00002009 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002010 {NULL} /* Sentinel */
2011};
2012
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002013static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002015{
Guido van Rossum77f6a652002-04-03 22:41:51 +00002016 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002017}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002018static PyObject *
2019get_newlines(PyFileObject *f, void *closure)
2020{
2021 switch (f->f_newlinetypes) {
2022 case NEWLINE_UNKNOWN:
2023 Py_INCREF(Py_None);
2024 return Py_None;
2025 case NEWLINE_CR:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002026 return PyString_FromString("\r");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002027 case NEWLINE_LF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002028 return PyString_FromString("\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002029 case NEWLINE_CR|NEWLINE_LF:
2030 return Py_BuildValue("(ss)", "\r", "\n");
2031 case NEWLINE_CRLF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002032 return PyString_FromString("\r\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002033 case NEWLINE_CR|NEWLINE_CRLF:
2034 return Py_BuildValue("(ss)", "\r", "\r\n");
2035 case NEWLINE_LF|NEWLINE_CRLF:
2036 return Py_BuildValue("(ss)", "\n", "\r\n");
2037 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2038 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2039 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00002040 PyErr_Format(PyExc_SystemError,
2041 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00002042 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00002043 return NULL;
2044 }
2045}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002046
Georg Brandl65bb42d2008-03-21 20:38:24 +00002047static PyObject *
2048get_softspace(PyFileObject *f, void *closure)
2049{
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002050 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002051 return NULL;
2052 return PyInt_FromLong(f->f_softspace);
2053}
2054
2055static int
2056set_softspace(PyFileObject *f, PyObject *value)
2057{
2058 int new;
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002059 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002060 return -1;
2061
2062 if (value == NULL) {
2063 PyErr_SetString(PyExc_TypeError,
2064 "can't delete softspace attribute");
2065 return -1;
2066 }
2067
2068 new = PyInt_AsLong(value);
2069 if (new == -1 && PyErr_Occurred())
2070 return -1;
2071 f->f_softspace = new;
2072 return 0;
2073}
2074
Guido van Rossum32d34c82001-09-20 21:45:26 +00002075static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00002076 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00002077 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00002078 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00002079 {"softspace", (getter)get_softspace, (setter)set_softspace,
2080 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002081 {0},
2082};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002083
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002084static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002085drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002086{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002087 if (f->f_buf != NULL) {
2088 PyMem_Free(f->f_buf);
2089 f->f_buf = NULL;
2090 }
Guido van Rossum65967252001-04-21 13:20:18 +00002091}
2092
Tim Petersf1827cf2003-09-07 03:30:18 +00002093/* Make sure that file has a readahead buffer with at least one byte
2094 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002095 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002096static int
2097readahead(PyFileObject *f, int bufsize)
2098{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002099 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002100
2101 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00002102 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002103 return 0;
2104 else
2105 drop_readahead(f);
2106 }
Anthony Baxter377be112006-04-11 06:54:30 +00002107 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00002108 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002109 return -1;
2110 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002111 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002112 errno = 0;
2113 chunksize = Py_UniversalNewlineFread(
2114 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002115 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002116 if (chunksize == 0) {
2117 if (ferror(f->f_fp)) {
2118 PyErr_SetFromErrno(PyExc_IOError);
2119 clearerr(f->f_fp);
2120 drop_readahead(f);
2121 return -1;
2122 }
2123 }
2124 f->f_bufptr = f->f_buf;
2125 f->f_bufend = f->f_buf + chunksize;
2126 return 0;
2127}
2128
2129/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002130 uninitialized bytes followed by the remainder of the line. Don't be
2131 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002132 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2133
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002134static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002135readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2136{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002137 PyStringObject* s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002138 char *bufptr;
2139 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002140 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002141
2142 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002143 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002144 return NULL;
2145
2146 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002147 if (len == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002148 return (PyStringObject *)
2149 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002150 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002151 if (bufptr != NULL) {
2152 bufptr++; /* Count the '\n' */
2153 len = bufptr - f->f_bufptr;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002154 s = (PyStringObject *)
2155 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002156 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002157 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002158 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002159 f->f_bufptr = bufptr;
2160 if (bufptr == f->f_bufend)
2161 drop_readahead(f);
2162 } else {
2163 bufptr = f->f_bufptr;
2164 buf = f->f_buf;
2165 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002166 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002167 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002168 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002169 if (s == NULL) {
2170 PyMem_Free(buf);
2171 return NULL;
2172 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002173 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002174 PyMem_Free(buf);
2175 }
2176 return s;
2177}
2178
2179/* A larger buffer size may actually decrease performance. */
2180#define READAHEAD_BUFSIZE 8192
2181
2182static PyObject *
2183file_iternext(PyFileObject *f)
2184{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002185 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002186
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002187 if (f->f_fp == NULL)
2188 return err_closed();
2189
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002190 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002191 if (l == NULL || PyString_GET_SIZE(l) == 0) {
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002192 Py_XDECREF(l);
2193 return NULL;
2194 }
2195 return (PyObject *)l;
2196}
2197
2198
Tim Peters59c9a642001-09-13 05:38:56 +00002199static PyObject *
2200file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2201{
Tim Peters44410012001-09-14 03:26:08 +00002202 PyObject *self;
2203 static PyObject *not_yet_string;
2204
2205 assert(type != NULL && type->tp_alloc != NULL);
2206
2207 if (not_yet_string == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002208 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002209 if (not_yet_string == NULL)
2210 return NULL;
2211 }
2212
2213 self = type->tp_alloc(type, 0);
2214 if (self != NULL) {
2215 /* Always fill in the name and mode, so that nobody else
2216 needs to special-case NULLs there. */
2217 Py_INCREF(not_yet_string);
2218 ((PyFileObject *)self)->f_name = not_yet_string;
2219 Py_INCREF(not_yet_string);
2220 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002221 Py_INCREF(Py_None);
2222 ((PyFileObject *)self)->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +00002223 Py_INCREF(Py_None);
2224 ((PyFileObject *)self)->f_errors = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002225 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002226 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002227 }
2228 return self;
2229}
2230
2231static int
2232file_init(PyObject *self, PyObject *args, PyObject *kwds)
2233{
2234 PyFileObject *foself = (PyFileObject *)self;
2235 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002236 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002237 char *name = NULL;
2238 char *mode = "r";
2239 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002240 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002241#ifdef MS_WINDOWS
Hirokazu Yamamotoa3c56092009-06-28 10:23:00 +00002242 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002243#endif
Tim Peters44410012001-09-14 03:26:08 +00002244
2245 assert(PyFile_Check(self));
2246 if (foself->f_fp != NULL) {
2247 /* Have to close the existing file first. */
2248 PyObject *closeresult = file_close(foself);
2249 if (closeresult == NULL)
2250 return -1;
2251 Py_DECREF(closeresult);
2252 }
Tim Peters59c9a642001-09-13 05:38:56 +00002253
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002254#ifdef MS_WINDOWS
Hirokazu Yamamotoa3c56092009-06-28 10:23:00 +00002255 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2256 kwlist, &po, &mode, &bufsize)) {
2257 wideargument = 1;
2258 if (fill_file_fields(foself, NULL, po, mode,
2259 fclose) == NULL)
2260 goto Error;
2261 } else {
2262 /* Drop the argument parsing error as narrow
2263 strings are also valid. */
2264 PyErr_Clear();
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002265 }
2266#endif
2267
2268 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002269 PyObject *o_name;
2270
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002271 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2272 Py_FileSystemDefaultEncoding,
2273 &name,
2274 &mode, &bufsize))
2275 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002276
2277 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002278 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2279 kwlist, &o_name, &mode,
2280 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002281 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002282
2283 if (fill_file_fields(foself, NULL, o_name, mode,
2284 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002285 goto Error;
2286 }
Tim Peters44410012001-09-14 03:26:08 +00002287 if (open_the_file(foself, name, mode) == NULL)
2288 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002289 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002290 PyFile_SetBufSize(self, bufsize);
2291 goto Done;
2292
2293Error:
2294 ret = -1;
2295 /* fall through */
2296Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002297 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002298 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002299}
2300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002301PyDoc_VAR(file_doc) =
2302PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002303"file(name[, mode[, buffering]]) -> file object\n"
2304"\n"
2305"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2306"writing or appending. The file will be created if it doesn't exist\n"
2307"when opened for writing or appending; it will be truncated when\n"
2308"opened for writing. Add a 'b' to the mode for binary files.\n"
2309"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2310"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002311"buffered, and larger numbers specify the buffer size. The preferred way\n"
2312"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002313)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002314PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002315"Add a 'U' to mode to open the file for input with universal newline\n"
2316"support. Any line ending in the input file will be seen as a '\\n'\n"
2317"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2318"the value for this attribute is one of None (no newline read yet),\n"
2319"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2320"\n"
2321"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002322);
Tim Peters59c9a642001-09-13 05:38:56 +00002323
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002325 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002326 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002328 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002329 (destructor)file_dealloc, /* tp_dealloc */
2330 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331 0, /* tp_getattr */
2332 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002333 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002335 0, /* tp_as_number */
2336 0, /* tp_as_sequence */
2337 0, /* tp_as_mapping */
2338 0, /* tp_hash */
2339 0, /* tp_call */
2340 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002342 /* softspace is writable: we must supply tp_setattro */
2343 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002344 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002345 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002346 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347 0, /* tp_traverse */
2348 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002349 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002350 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002351 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002352 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353 file_methods, /* tp_methods */
2354 file_memberlist, /* tp_members */
2355 file_getsetlist, /* tp_getset */
2356 0, /* tp_base */
2357 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002358 0, /* tp_descr_get */
2359 0, /* tp_descr_set */
2360 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002361 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002362 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002363 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002364 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002365};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002366
2367/* Interface for the 'soft space' between print items. */
2368
2369int
Fred Drakefd99de62000-07-09 05:02:18 +00002370PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002371{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002372 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002373 if (f == NULL) {
2374 /* Do nothing */
2375 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002376 else if (PyFile_Check(f)) {
2377 oldflag = ((PyFileObject *)f)->f_softspace;
2378 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002379 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002380 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002381 PyObject *v;
2382 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002383 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002384 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002385 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002386 if (PyInt_Check(v))
2387 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002388 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002389 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002390 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002391 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002392 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002393 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002394 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002395 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2396 PyErr_Clear();
2397 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002398 }
2399 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002400 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002401}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002402
2403/* Interfaces to write objects/strings to file-like objects */
2404
2405int
Fred Drakefd99de62000-07-09 05:02:18 +00002406PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002407{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002408 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002409 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002410 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002411 return -1;
2412 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002413 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002414 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002415#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002416 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002417 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002418#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002419 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002420 err_closed();
2421 return -1;
2422 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002423#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002424 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002425 PyUnicode_Check(v) && enc != Py_None) {
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002426 char *cenc = PyString_AS_STRING(enc);
Martin v. Löwis99815892008-06-01 07:20:46 +00002427 char *errors = fobj->f_errors == Py_None ?
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002428 "strict" : PyString_AS_STRING(fobj->f_errors);
Martin v. Löwis99815892008-06-01 07:20:46 +00002429 value = PyUnicode_AsEncodedString(v, cenc, errors);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002430 if (value == NULL)
2431 return -1;
2432 } else {
2433 value = v;
2434 Py_INCREF(value);
2435 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002436 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002437 Py_DECREF(value);
2438 return result;
2439#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002440 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002441#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002442 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002443 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002444 if (writer == NULL)
2445 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002446 if (flags & Py_PRINT_RAW) {
2447 if (PyUnicode_Check(v)) {
2448 value = v;
2449 Py_INCREF(value);
2450 } else
2451 value = PyObject_Str(v);
2452 }
2453 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002454 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002455 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002456 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002457 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002458 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002459 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002460 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002461 Py_DECREF(value);
2462 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002463 return -1;
2464 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002465 result = PyEval_CallObject(writer, args);
2466 Py_DECREF(args);
2467 Py_DECREF(value);
2468 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002469 if (result == NULL)
2470 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002471 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002472 return 0;
2473}
2474
Guido van Rossum27a60b11997-05-22 22:25:11 +00002475int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002476PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002477{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002478
Guido van Rossum3165fe61992-09-25 21:59:05 +00002479 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002480 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002481 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002482 PyErr_SetString(PyExc_SystemError,
2483 "null file for PyFile_WriteString");
2484 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002485 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002486 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002487 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002488 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002489 if (fp == NULL) {
2490 err_closed();
2491 return -1;
2492 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002493 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002494 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002495 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002496 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002497 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002498 else if (!PyErr_Occurred()) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002499 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002500 int err;
2501 if (v == NULL)
2502 return -1;
2503 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2504 Py_DECREF(v);
2505 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002506 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002507 else
2508 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002509}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002510
2511/* Try to get a file-descriptor from a Python object. If the object
2512 is an integer or long integer, its value is returned. If not, the
2513 object's fileno() method is called if it exists; the method must return
2514 an integer or long integer, which is returned as the file descriptor value.
2515 -1 is returned on failure.
2516*/
2517
2518int PyObject_AsFileDescriptor(PyObject *o)
2519{
2520 int fd;
2521 PyObject *meth;
2522
2523 if (PyInt_Check(o)) {
2524 fd = PyInt_AsLong(o);
2525 }
2526 else if (PyLong_Check(o)) {
2527 fd = PyLong_AsLong(o);
2528 }
2529 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2530 {
2531 PyObject *fno = PyEval_CallObject(meth, NULL);
2532 Py_DECREF(meth);
2533 if (fno == NULL)
2534 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002535
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002536 if (PyInt_Check(fno)) {
2537 fd = PyInt_AsLong(fno);
2538 Py_DECREF(fno);
2539 }
2540 else if (PyLong_Check(fno)) {
2541 fd = PyLong_AsLong(fno);
2542 Py_DECREF(fno);
2543 }
2544 else {
2545 PyErr_SetString(PyExc_TypeError,
2546 "fileno() returned a non-integer");
2547 Py_DECREF(fno);
2548 return -1;
2549 }
2550 }
2551 else {
2552 PyErr_SetString(PyExc_TypeError,
2553 "argument must be an int, or have a fileno() method.");
2554 return -1;
2555 }
2556
2557 if (fd < 0) {
2558 PyErr_Format(PyExc_ValueError,
2559 "file descriptor cannot be a negative integer (%i)",
2560 fd);
2561 return -1;
2562 }
2563 return fd;
2564}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002565
Jack Jansen7b8c7542002-04-14 20:12:41 +00002566/* From here on we need access to the real fgets and fread */
2567#undef fgets
2568#undef fread
2569
2570/*
2571** Py_UniversalNewlineFgets is an fgets variation that understands
2572** all of \r, \n and \r\n conventions.
2573** The stream should be opened in binary mode.
2574** If fobj is NULL the routine always does newline conversion, and
2575** it may peek one char ahead to gobble the second char in \r\n.
2576** If fobj is non-NULL it must be a PyFileObject. In this case there
2577** is no readahead but in stead a flag is used to skip a following
2578** \n on the next read. Also, if the file is open in binary mode
2579** the whole conversion is skipped. Finally, the routine keeps track of
2580** the different types of newlines seen.
2581** Note that we need no error handling: fgets() treats error and eof
2582** identically.
2583*/
2584char *
2585Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2586{
2587 char *p = buf;
2588 int c;
2589 int newlinetypes = 0;
2590 int skipnextlf = 0;
2591 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002592
Jack Jansen7b8c7542002-04-14 20:12:41 +00002593 if (fobj) {
2594 if (!PyFile_Check(fobj)) {
2595 errno = ENXIO; /* What can you do... */
2596 return NULL;
2597 }
2598 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2599 if ( !univ_newline )
2600 return fgets(buf, n, stream);
2601 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2602 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2603 }
2604 FLOCKFILE(stream);
2605 c = 'x'; /* Shut up gcc warning */
2606 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2607 if (skipnextlf ) {
2608 skipnextlf = 0;
2609 if (c == '\n') {
2610 /* Seeing a \n here with skipnextlf true
2611 ** means we saw a \r before.
2612 */
2613 newlinetypes |= NEWLINE_CRLF;
2614 c = GETC(stream);
2615 if (c == EOF) break;
2616 } else {
2617 /*
2618 ** Note that c == EOF also brings us here,
2619 ** so we're okay if the last char in the file
2620 ** is a CR.
2621 */
2622 newlinetypes |= NEWLINE_CR;
2623 }
2624 }
2625 if (c == '\r') {
2626 /* A \r is translated into a \n, and we skip
2627 ** an adjacent \n, if any. We don't set the
2628 ** newlinetypes flag until we've seen the next char.
2629 */
2630 skipnextlf = 1;
2631 c = '\n';
2632 } else if ( c == '\n') {
2633 newlinetypes |= NEWLINE_LF;
2634 }
2635 *p++ = c;
2636 if (c == '\n') break;
2637 }
2638 if ( c == EOF && skipnextlf )
2639 newlinetypes |= NEWLINE_CR;
2640 FUNLOCKFILE(stream);
2641 *p = '\0';
2642 if (fobj) {
2643 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2644 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2645 } else if ( skipnextlf ) {
2646 /* If we have no file object we cannot save the
2647 ** skipnextlf flag. We have to readahead, which
2648 ** will cause a pause if we're reading from an
2649 ** interactive stream, but that is very unlikely
2650 ** unless we're doing something silly like
2651 ** execfile("/dev/tty").
2652 */
2653 c = GETC(stream);
2654 if ( c != '\n' )
2655 ungetc(c, stream);
2656 }
2657 if (p == buf)
2658 return NULL;
2659 return buf;
2660}
2661
2662/*
2663** Py_UniversalNewlineFread is an fread variation that understands
2664** all of \r, \n and \r\n conventions.
2665** The stream should be opened in binary mode.
2666** fobj must be a PyFileObject. In this case there
2667** is no readahead but in stead a flag is used to skip a following
2668** \n on the next read. Also, if the file is open in binary mode
2669** the whole conversion is skipped. Finally, the routine keeps track of
2670** the different types of newlines seen.
2671*/
2672size_t
Tim Peters058b1412002-04-21 07:29:14 +00002673Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002674 FILE *stream, PyObject *fobj)
2675{
Tim Peters058b1412002-04-21 07:29:14 +00002676 char *dst = buf;
2677 PyFileObject *f = (PyFileObject *)fobj;
2678 int newlinetypes, skipnextlf;
2679
2680 assert(buf != NULL);
2681 assert(stream != NULL);
2682
Jack Jansen7b8c7542002-04-14 20:12:41 +00002683 if (!fobj || !PyFile_Check(fobj)) {
2684 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002685 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002686 }
Tim Peters058b1412002-04-21 07:29:14 +00002687 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002688 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002689 newlinetypes = f->f_newlinetypes;
2690 skipnextlf = f->f_skipnextlf;
2691 /* Invariant: n is the number of bytes remaining to be filled
2692 * in the buffer.
2693 */
2694 while (n) {
2695 size_t nread;
2696 int shortread;
2697 char *src = dst;
2698
2699 nread = fread(dst, 1, n, stream);
2700 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002701 if (nread == 0)
2702 break;
2703
Tim Peterse1682a82002-04-21 18:15:20 +00002704 n -= nread; /* assuming 1 byte out for each in; will adjust */
2705 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002706 while (nread--) {
2707 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002708 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002709 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002710 *dst++ = '\n';
2711 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002712 }
2713 else if (skipnextlf && c == '\n') {
2714 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002715 skipnextlf = 0;
2716 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002717 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002718 }
2719 else {
2720 /* Normal char to be stored in buffer. Also
2721 * update the newlinetypes flag if either this
2722 * is an LF or the previous char was a CR.
2723 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002724 if (c == '\n')
2725 newlinetypes |= NEWLINE_LF;
2726 else if (skipnextlf)
2727 newlinetypes |= NEWLINE_CR;
2728 *dst++ = c;
2729 skipnextlf = 0;
2730 }
2731 }
Tim Peters058b1412002-04-21 07:29:14 +00002732 if (shortread) {
2733 /* If this is EOF, update type flags. */
2734 if (skipnextlf && feof(stream))
2735 newlinetypes |= NEWLINE_CR;
2736 break;
2737 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002738 }
Tim Peters058b1412002-04-21 07:29:14 +00002739 f->f_newlinetypes = newlinetypes;
2740 f->f_skipnextlf = skipnextlf;
2741 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002742}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002743
2744#ifdef __cplusplus
2745}
2746#endif