blob: ff307453c2145769b49cdd87fa5cfef6d1ec7de7 [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
Mark Hammondc2e85bd2002-10-03 05:10:39 +000019#ifdef _MSC_VER
20/* Need GetVersion to see if on NT so safe to use _wfopen */
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#endif /* _MSC_VER */
24
Andrew MacIntyrec4874392002-02-26 11:36:35 +000025#if defined(PYOS_OS2) && defined(PYCC_GCC)
26#include <io.h>
27#endif
28
Gregory P. Smithdd96db62008-06-09 04:58:54 +000029#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000030
Guido van Rossumff7e83d1999-08-27 20:39:37 +000031#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000032#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000033#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Jack Jansen7b8c7542002-04-14 20:12:41 +000035#ifdef HAVE_GETC_UNLOCKED
36#define GETC(f) getc_unlocked(f)
37#define FLOCKFILE(f) flockfile(f)
38#define FUNLOCKFILE(f) funlockfile(f)
39#else
40#define GETC(f) getc(f)
41#define FLOCKFILE(f)
42#define FUNLOCKFILE(f)
43#endif
44
Jack Jansen7b8c7542002-04-14 20:12:41 +000045/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000050
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000051/*
52 * These macros release the GIL while preventing the f_close() function being
53 * called in the interval between them. For that purpose, a running total of
54 * the number of currently running unlocked code sections is kept in
55 * the unlocked_count field of the PyFileObject. The close() method raises
56 * an IOError if that field is non-zero. See issue #815646, #595601.
57 */
58
59#define FILE_BEGIN_ALLOW_THREADS(fobj) \
60{ \
61 fobj->unlocked_count++; \
62 Py_BEGIN_ALLOW_THREADS
63
64#define FILE_END_ALLOW_THREADS(fobj) \
65 Py_END_ALLOW_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0); \
68}
69
70#define FILE_ABORT_ALLOW_THREADS(fobj) \
71 Py_BLOCK_THREADS \
72 fobj->unlocked_count--; \
73 assert(fobj->unlocked_count >= 0);
74
Anthony Baxterac6bd462006-04-13 02:06:09 +000075#ifdef __cplusplus
76extern "C" {
77#endif
78
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000080PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000081{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000082 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000084 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086}
87
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000088void PyFile_IncUseCount(PyFileObject *fobj)
89{
90 fobj->unlocked_count++;
91}
92
93void PyFile_DecUseCount(PyFileObject *fobj)
94{
95 fobj->unlocked_count--;
96 assert(fobj->unlocked_count >= 0);
97}
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000100PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000103 return NULL;
104 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000106}
107
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000108/* This is a safe wrapper around PyObject_Print to print to the FILE
109 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
110 about PyFileObject. */
111static int
112file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
113{
114 int result;
115 PyFile_IncUseCount(f);
116 result = PyObject_Print(op, f->f_fp, flags);
117 PyFile_DecUseCount(f);
118 return result;
119}
120
Neil Schemenauered19b882002-03-23 02:06:50 +0000121/* On Unix, fopen will succeed for directories.
122 In Python, there should be no file objects referring to
123 directories, so we need a check. */
124
125static PyFileObject*
126dircheck(PyFileObject* f)
127{
128#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
129 struct stat buf;
130 if (f->f_fp == NULL)
131 return f;
132 if (fstat(fileno(f->f_fp), &buf) == 0 &&
133 S_ISDIR(buf.st_mode)) {
Neil Schemenauered19b882002-03-23 02:06:50 +0000134 char *msg = strerror(EISDIR);
Benjamin Petersonfe231b02008-12-29 17:47:42 +0000135 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
136 EISDIR, msg, f->f_name);
Neil Schemenauered19b882002-03-23 02:06:50 +0000137 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000138 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000139 return NULL;
140 }
141#endif
142 return f;
143}
144
Tim Peters59c9a642001-09-13 05:38:56 +0000145
146static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000147fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
148 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000150 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000151 assert(f != NULL);
152 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000153 assert(f->f_fp == NULL);
154
155 Py_DECREF(f->f_name);
156 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000157 Py_DECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000158 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000159
Neal Norwitzb337bb52006-07-17 00:55:45 +0000160 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000161 f->f_name = name;
162
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000163 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000164
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000165 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000166 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000167 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000168 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000169 f->f_univ_newline = (strchr(mode, 'U') != NULL);
170 f->f_newlinetypes = NEWLINE_UNKNOWN;
171 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000172 Py_INCREF(Py_None);
173 f->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +0000174 Py_INCREF(Py_None);
175 f->f_errors = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000176
Neal Norwitzb337bb52006-07-17 00:55:45 +0000177 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000180 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000182}
183
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000184#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
185#define Py_VERIFY_WINNT
186/* The CRT on windows compiled with Visual Studio 2005 and higher may
187 * assert if given invalid mode strings. This is all fine and well
188 * in static languages like C where the mode string is typcially hard
189 * coded. But in Python, were we pass in the mode string from the user,
190 * we need to verify it first manually
191 */
192static int _PyVerify_Mode_WINNT(const char *mode)
193{
194 /* See if mode string is valid on Windows to avoid hard assertions */
195 /* remove leading spacese */
196 int singles = 0;
197 int pairs = 0;
198 int encoding = 0;
199 const char *s, *c;
200
201 while(*mode == ' ') /* strip initial spaces */
202 ++mode;
203 if (!strchr("rwa", *mode)) /* must start with one of these */
204 return 0;
205 while (*++mode) {
206 if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
207 continue;
208 s = "+TD"; /* each of this can appear only once */
209 c = strchr(s, *mode);
210 if (c) {
211 ptrdiff_t idx = s-c;
212 if (singles & (1<<idx))
213 return 0;
214 singles |= (1<<idx);
215 continue;
216 }
217 s = "btcnSR"; /* only one of each letter in the pairs allowed */
218 c = strchr(s, *mode);
219 if (c) {
220 ptrdiff_t idx = (s-c)/2;
221 if (pairs & (1<<idx))
222 return 0;
223 pairs |= (1<<idx);
224 continue;
225 }
226 if (*mode == ',') {
227 encoding = 1;
228 break;
229 }
230 return 0; /* found an invalid char */
231 }
232
233 if (encoding) {
234 char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
235 while (*mode == ' ')
236 ++mode;
237 /* find 'ccs =' */
238 if (strncmp(mode, "ccs", 3))
239 return 0;
240 mode += 3;
241 while (*mode == ' ')
242 ++mode;
243 if (*mode != '=')
244 return 0;
245 while (*mode == ' ')
246 ++mode;
247 for(encoding = 0; encoding<_countof(e); ++encoding) {
248 size_t l = strlen(e[encoding]);
249 if (!strncmp(mode, e[encoding], l)) {
250 mode += l; /* found a valid encoding */
251 break;
252 }
253 }
254 if (encoding == _countof(e))
255 return 0;
256 }
257 /* skip trailing spaces */
258 while (*mode == ' ')
259 ++mode;
260
261 return *mode == '\0'; /* must be at the end of the string */
262}
263#endif
264
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000265/* check for known incorrect mode strings - problem is, platforms are
266 free to accept any mode characters they like and are supposed to
267 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000268 universal newline support is expressly forbidden by PEP 278.
269 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000270 won't know what it is. Non-zero return signals an exception */
271int
272_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000273{
Georg Brandl7b90e162006-05-18 07:01:27 +0000274 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000275 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000276
Georg Brandl7b90e162006-05-18 07:01:27 +0000277 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000278 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000279 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000280 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000281
Georg Brandl7b90e162006-05-18 07:01:27 +0000282 upos = strchr(mode, 'U');
283 if (upos) {
284 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000285
Georg Brandl7b90e162006-05-18 07:01:27 +0000286 if (mode[0] == 'w' || mode[0] == 'a') {
287 PyErr_Format(PyExc_ValueError, "universal newline "
288 "mode can only be used with modes "
289 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000290 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000291 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000292
293 if (mode[0] != 'r') {
294 memmove(mode+1, mode, strlen(mode)+1);
295 mode[0] = 'r';
296 }
297
298 if (!strchr(mode, 'b')) {
299 memmove(mode+2, mode+1, strlen(mode));
300 mode[1] = 'b';
301 }
302 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
303 PyErr_Format(PyExc_ValueError, "mode string must begin with "
304 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000305 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000306 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000307#ifdef Py_VERIFY_WINNT
308 /* additional checks on NT with visual studio 2005 and higher */
309 if (!_PyVerify_Mode_WINNT(mode)) {
310 PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
311 return -1;
312 }
313#endif
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000314 return 0;
315}
316
Tim Peters59c9a642001-09-13 05:38:56 +0000317static PyObject *
318open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319{
Georg Brandl7b90e162006-05-18 07:01:27 +0000320 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000321 assert(f != NULL);
322 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000323#ifdef MS_WINDOWS
324 /* windows ignores the passed name in order to support Unicode */
325 assert(f->f_name != NULL);
326#else
Tim Peters59c9a642001-09-13 05:38:56 +0000327 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000328#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000329 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000330 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000331
Georg Brandl7b90e162006-05-18 07:01:27 +0000332 /* probably need to replace 'U' by 'rb' */
333 newmode = PyMem_MALLOC(strlen(mode) + 3);
334 if (!newmode) {
335 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000336 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000337 }
338 strcpy(newmode, mode);
339
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000340 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000341 f = NULL;
342 goto cleanup;
343 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000344
Tim Peters8fa45672001-09-13 21:01:29 +0000345 /* rexec.py can't stop a user from getting the file() constructor --
346 all they have to do is get *any* file object f, and then do
347 type(f). Here we prevent them from doing damage with it. */
348 if (PyEval_GetRestricted()) {
349 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000350 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000351 f = NULL;
352 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000353 }
Tim Petersa27a1502001-11-09 20:59:14 +0000354 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000355
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000356#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000357 if (PyUnicode_Check(f->f_name)) {
358 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000359 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000360 if (f->f_name && wmode) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000361 FILE_BEGIN_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000362 /* PyUnicode_AS_UNICODE OK without thread
363 lock as it is a simple dereference. */
364 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
365 PyUnicode_AS_UNICODE(wmode));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000366 FILE_END_ALLOW_THREADS(f)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000367 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000368 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000369 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000370#endif
371 if (NULL == f->f_fp && NULL != name) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000372 FILE_BEGIN_ALLOW_THREADS(f)
Georg Brandl7b90e162006-05-18 07:01:27 +0000373 f->f_fp = fopen(name, newmode);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000374 FILE_END_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000375 }
376
Guido van Rossuma08095a1991-02-13 23:25:27 +0000377 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000378#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000379 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
380 * across all Windows flavors. When it sets EINVAL varies
381 * across Windows flavors, the exact conditions aren't
382 * documented, and the answer lies in the OS's implementation
383 * of Win32's CreateFile function (whose source is secret).
384 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000385 * Starting with Visual Studio .NET 2005, EINVAL is correctly
386 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000387 */
388 if (errno == 0) /* bad mode string */
389 errno = EINVAL;
390 else if (errno == EINVAL) /* unknown, but not a mode string */
391 errno = ENOENT;
392#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000393 /* EINVAL is returned when an invalid filename or
394 * an invalid mode is supplied. */
Amaury Forgeot d'Arc17617a02008-09-25 20:52:56 +0000395 if (errno == EINVAL) {
396 PyObject *v;
397 char message[100];
398 PyOS_snprintf(message, 100,
399 "invalid mode ('%.50s') or filename", mode);
400 v = Py_BuildValue("(isO)", errno, message, f->f_name);
401 if (v != NULL) {
402 PyErr_SetObject(PyExc_IOError, v);
403 Py_DECREF(v);
404 }
405 }
Jeremy Hylton41c83212001-11-09 16:17:24 +0000406 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000407 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000408 f = NULL;
409 }
Tim Peters2ea91112002-04-08 04:13:12 +0000410 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000411 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000412
413cleanup:
414 PyMem_FREE(newmode);
415
Tim Peters59c9a642001-09-13 05:38:56 +0000416 return (PyObject *)f;
417}
418
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000419static PyObject *
420close_the_file(PyFileObject *f)
421{
422 int sts = 0;
423 int (*local_close)(FILE *);
424 FILE *local_fp = f->f_fp;
425 if (local_fp != NULL) {
426 local_close = f->f_close;
427 if (local_close != NULL && f->unlocked_count > 0) {
428 if (f->ob_refcnt > 0) {
429 PyErr_SetString(PyExc_IOError,
430 "close() called during concurrent "
431 "operation on the same file object.");
432 } else {
433 /* This should not happen unless someone is
434 * carelessly playing with the PyFileObject
435 * struct fields and/or its associated FILE
436 * pointer. */
437 PyErr_SetString(PyExc_SystemError,
438 "PyFileObject locking error in "
439 "destructor (refcnt <= 0 at close).");
440 }
441 return NULL;
442 }
443 /* NULL out the FILE pointer before releasing the GIL, because
444 * it will not be valid anymore after the close() function is
445 * called. */
446 f->f_fp = NULL;
447 if (local_close != NULL) {
448 Py_BEGIN_ALLOW_THREADS
449 errno = 0;
450 sts = (*local_close)(local_fp);
451 Py_END_ALLOW_THREADS
452 if (sts == EOF)
453 return PyErr_SetFromErrno(PyExc_IOError);
454 if (sts != 0)
455 return PyInt_FromLong((long)sts);
456 }
457 }
458 Py_RETURN_NONE;
459}
460
Tim Peters59c9a642001-09-13 05:38:56 +0000461PyObject *
462PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
463{
Tim Peters44410012001-09-14 03:26:08 +0000464 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
465 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000466 if (f != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000467 PyObject *o_name = PyString_FromString(name);
Neal Norwitzb337bb52006-07-17 00:55:45 +0000468 if (o_name == NULL)
469 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000470 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000471 Py_DECREF(f);
472 f = NULL;
473 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000474 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000475 }
476 return (PyObject *) f;
477}
478
479PyObject *
480PyFile_FromString(char *name, char *mode)
481{
482 extern int fclose(FILE *);
483 PyFileObject *f;
484
485 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
486 if (f != NULL) {
487 if (open_the_file(f, name, mode) == NULL) {
488 Py_DECREF(f);
489 f = NULL;
490 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000491 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493}
494
Guido van Rossumb6775db1994-08-01 11:34:53 +0000495void
Fred Drakefd99de62000-07-09 05:02:18 +0000496PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000497{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000498 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000499 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000500 int type;
501 switch (bufsize) {
502 case 0:
503 type = _IONBF;
504 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000505#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000506 case 1:
507 type = _IOLBF;
508 bufsize = BUFSIZ;
509 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000510#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000511 default:
512 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000513#ifndef HAVE_SETVBUF
514 bufsize = BUFSIZ;
515#endif
516 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000517 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000518 fflush(file->f_fp);
519 if (type == _IONBF) {
520 PyMem_Free(file->f_setbuf);
521 file->f_setbuf = NULL;
522 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000523 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
524 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000525 }
526#ifdef HAVE_SETVBUF
527 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000528#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000529 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000530#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000531 }
532}
533
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000534/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000535 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000536
537int
538PyFile_SetEncoding(PyObject *f, const char *enc)
539{
Martin v. Löwis99815892008-06-01 07:20:46 +0000540 return PyFile_SetEncodingAndErrors(f, enc, NULL);
541}
542
543int
544PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
545{
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000546 PyFileObject *file = (PyFileObject*)f;
Martin v. Löwis99815892008-06-01 07:20:46 +0000547 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000548
549 assert(PyFile_Check(f));
Gregory P. Smith99a3dce2008-06-10 17:42:36 +0000550 str = PyString_FromString(enc);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000551 if (!str)
552 return 0;
Martin v. Löwis99815892008-06-01 07:20:46 +0000553 if (errors) {
554 oerrors = PyString_FromString(errors);
555 if (!oerrors) {
556 Py_DECREF(str);
557 return 0;
558 }
559 } else {
560 oerrors = Py_None;
561 Py_INCREF(Py_None);
562 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000563 Py_DECREF(file->f_encoding);
564 file->f_encoding = str;
Martin v. Löwis99815892008-06-01 07:20:46 +0000565 Py_DECREF(file->f_errors);
566 file->f_errors = oerrors;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000567 return 1;
568}
569
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000570static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000571err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000572{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000573 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000574 return NULL;
575}
576
Thomas Woutersc45251a2006-02-12 11:53:32 +0000577/* Refuse regular file I/O if there's data in the iteration-buffer.
578 * Mixing them would cause data to arrive out of order, as the read*
579 * methods don't use the iteration buffer. */
580static PyObject *
581err_iterbuffered(void)
582{
583 PyErr_SetString(PyExc_ValueError,
584 "Mixing iteration and read methods would lose data");
585 return NULL;
586}
587
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000588static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000589
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590/* Methods */
591
592static void
Fred Drakefd99de62000-07-09 05:02:18 +0000593file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000595 PyObject *ret;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000596 if (f->weakreflist != NULL)
597 PyObject_ClearWeakRefs((PyObject *) f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000598 ret = close_the_file(f);
599 if (!ret) {
600 PySys_WriteStderr("close failed in file object destructor:\n");
601 PyErr_Print();
602 }
603 else {
604 Py_DECREF(ret);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000605 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000606 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000607 Py_XDECREF(f->f_name);
608 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000609 Py_XDECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000610 Py_XDECREF(f->f_errors);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000611 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000612 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613}
614
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000616file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000618 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000619#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000620 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000621 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000622 const char *name_str = name ? PyString_AsString(name) : "?";
623 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000624 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000625 name_str,
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000626 PyString_AsString(f->f_mode),
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000627 f);
628 Py_XDECREF(name);
629 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000630#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000631 } else {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000632 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000633 f->f_fp == NULL ? "closed" : "open",
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000634 PyString_AsString(f->f_name),
635 PyString_AsString(f->f_mode),
Barry Warsaw7ce36942001-08-24 18:34:26 +0000636 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000637 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638}
639
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000641file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000643 PyObject *sts = close_the_file(f);
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000644 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000645 f->f_setbuf = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000646 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647}
648
Trent Mickf29f47b2000-08-11 19:02:59 +0000649
Guido van Rossumb8552162001-09-05 14:58:11 +0000650/* Our very own off_t-like type, 64-bit if possible */
651#if !defined(HAVE_LARGEFILE_SUPPORT)
652typedef off_t Py_off_t;
653#elif SIZEOF_OFF_T >= 8
654typedef off_t Py_off_t;
655#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000656typedef fpos_t Py_off_t;
657#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000658#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000659#endif
660
661
Trent Mickf29f47b2000-08-11 19:02:59 +0000662/* a portable fseek() function
663 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000664static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000665_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000666{
Guido van Rossumb8552162001-09-05 14:58:11 +0000667#if !defined(HAVE_LARGEFILE_SUPPORT)
668 return fseek(fp, offset, whence);
669#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000670 return fseeko(fp, offset, whence);
671#elif defined(HAVE_FSEEK64)
672 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000673#elif defined(__BEOS__)
674 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000675#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000676 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
677 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000678 fpos_t pos;
679 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000680 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000681#ifdef MS_WINDOWS
682 fflush(fp);
683 if (_lseeki64(fileno(fp), 0, 2) == -1)
684 return -1;
685#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000686 if (fseek(fp, 0, SEEK_END) != 0)
687 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000688#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000689 /* fall through */
690 case SEEK_CUR:
691 if (fgetpos(fp, &pos) != 0)
692 return -1;
693 offset += pos;
694 break;
695 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000696 }
697 return fsetpos(fp, &offset);
698#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000699#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000700#endif
701}
702
703
704/* a portable ftell() function
705 Return -1 on failure with errno set appropriately, current file
706 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000707static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000708_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000709{
Guido van Rossumb8552162001-09-05 14:58:11 +0000710#if !defined(HAVE_LARGEFILE_SUPPORT)
711 return ftell(fp);
712#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
713 return ftello(fp);
714#elif defined(HAVE_FTELL64)
715 return ftell64(fp);
716#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000717 fpos_t pos;
718 if (fgetpos(fp, &pos) != 0)
719 return -1;
720 return pos;
721#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000722#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000723#endif
724}
725
726
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000727static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000728file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000730 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000731 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000732 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000733 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000734
Guido van Rossumd7297e61992-07-06 14:19:26 +0000735 if (f->f_fp == NULL)
736 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000737 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000738 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000739 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000740 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000741 off_index = PyNumber_Index(offobj);
742 if (!off_index) {
743 if (!PyFloat_Check(offobj))
744 return NULL;
745 /* Deprecated in 2.6 */
746 PyErr_Clear();
Benjamin Petersonf19a7b92008-04-27 18:40:21 +0000747 if (PyErr_WarnEx(PyExc_DeprecationWarning,
748 "integer argument expected, got float",
749 1) < 0)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000750 return NULL;
751 off_index = offobj;
752 Py_INCREF(offobj);
753 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000754#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000755 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000756#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000757 offset = PyLong_Check(off_index) ?
758 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000759#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000760 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000761 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000762 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000763
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000764 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000765 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000766 ret = _portable_fseek(f->f_fp, offset, whence);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000767 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000768
Guido van Rossumff4949e1992-08-05 19:58:53 +0000769 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000770 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000771 clearerr(f->f_fp);
772 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000773 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000774 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000775 Py_INCREF(Py_None);
776 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000777}
778
Trent Mickf29f47b2000-08-11 19:02:59 +0000779
Guido van Rossumd7047b31995-01-02 19:07:15 +0000780#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000781static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000782file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000783{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000784 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000785 PyObject *newsizeobj = NULL;
786 Py_off_t initialpos;
787 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000788
Guido van Rossumd7047b31995-01-02 19:07:15 +0000789 if (f->f_fp == NULL)
790 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000791 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000792 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000793
Tim Petersf1827cf2003-09-07 03:30:18 +0000794 /* Get current file position. If the file happens to be open for
795 * update and the last operation was an input operation, C doesn't
796 * define what the later fflush() will do, but we promise truncate()
797 * won't change the current position (and fflush() *does* change it
798 * then at least on Windows). The easiest thing is to capture
799 * current pos now and seek back to it at the end.
800 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000801 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000802 errno = 0;
803 initialpos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000804 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000805 if (initialpos == -1)
806 goto onioerror;
807
Tim Petersfb05db22002-03-11 00:24:00 +0000808 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000809 * specified value.
810 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000811 if (newsizeobj != NULL) {
812#if !defined(HAVE_LARGEFILE_SUPPORT)
813 newsize = PyInt_AsLong(newsizeobj);
814#else
815 newsize = PyLong_Check(newsizeobj) ?
816 PyLong_AsLongLong(newsizeobj) :
817 PyInt_AsLong(newsizeobj);
818#endif
819 if (PyErr_Occurred())
820 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000821 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000822 else /* default to current position */
823 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000824
Tim Petersf1827cf2003-09-07 03:30:18 +0000825 /* Flush the stream. We're mixing stream-level I/O with lower-level
826 * I/O, and a flush may be necessary to synch both platform views
827 * of the current file state.
828 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000829 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000830 errno = 0;
831 ret = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000832 FILE_END_ALLOW_THREADS(f)
Tim Petersfb05db22002-03-11 00:24:00 +0000833 if (ret != 0)
834 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000835
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000836#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000837 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000838 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000839 {
Tim Petersfb05db22002-03-11 00:24:00 +0000840 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000841
Tim Petersf1827cf2003-09-07 03:30:18 +0000842 /* Have to move current pos to desired endpoint on Windows. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000843 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000844 errno = 0;
845 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000846 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000847 if (ret)
848 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000849
Tim Peters8f01b682002-03-12 03:04:44 +0000850 /* Truncate. Note that this may grow the file! */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000851 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters8f01b682002-03-12 03:04:44 +0000852 errno = 0;
853 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000854 ret = hFile == (HANDLE)-1;
855 if (ret == 0) {
856 ret = SetEndOfFile(hFile) == 0;
857 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000858 errno = EACCES;
859 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000860 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000861 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000862 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000863 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000864#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000865 FILE_BEGIN_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000866 errno = 0;
867 ret = ftruncate(fileno(f->f_fp), newsize);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000868 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000869 if (ret != 0)
870 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000871#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000872
Tim Petersf1827cf2003-09-07 03:30:18 +0000873 /* Restore original file position. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000874 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000875 errno = 0;
876 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000877 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000878 if (ret)
879 goto onioerror;
880
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000881 Py_INCREF(Py_None);
882 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000883
884onioerror:
885 PyErr_SetFromErrno(PyExc_IOError);
886 clearerr(f->f_fp);
887 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000888}
889#endif /* HAVE_FTRUNCATE */
890
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000891static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000892file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000893{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000894 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000895
Guido van Rossumd7297e61992-07-06 14:19:26 +0000896 if (f->f_fp == NULL)
897 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000898 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000899 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000900 pos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000901 FILE_END_ALLOW_THREADS(f)
902
Trent Mickf29f47b2000-08-11 19:02:59 +0000903 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000904 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000905 clearerr(f->f_fp);
906 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000907 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000908 if (f->f_skipnextlf) {
909 int c;
910 c = GETC(f->f_fp);
911 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000912 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000913 pos++;
914 f->f_skipnextlf = 0;
915 } else if (c != EOF) ungetc(c, f->f_fp);
916 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000917#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000918 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000919#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000920 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000921#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000922}
923
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000924static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000925file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000926{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000927 if (f->f_fp == NULL)
928 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000929 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000930}
931
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000932static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000933file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000934{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000935 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000936
Guido van Rossumd7297e61992-07-06 14:19:26 +0000937 if (f->f_fp == NULL)
938 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000939 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000940 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000941 res = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000942 FILE_END_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000943 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000944 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000945 clearerr(f->f_fp);
946 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000947 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000948 Py_INCREF(Py_None);
949 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000950}
951
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000952static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000953file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000954{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000955 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000956 if (f->f_fp == NULL)
957 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000958 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000959 res = isatty((int)fileno(f->f_fp));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000960 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000961 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000962}
963
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000964
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000965#if BUFSIZ < 8192
966#define SMALLCHUNK 8192
967#else
968#define SMALLCHUNK BUFSIZ
969#endif
970
Guido van Rossum3c259041999-01-14 19:00:14 +0000971#if SIZEOF_INT < 4
972#define BIGCHUNK (512 * 32)
973#else
974#define BIGCHUNK (512 * 1024)
975#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000976
977static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000978new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000979{
980#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000981 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000982 struct stat st;
983 if (fstat(fileno(f->f_fp), &st) == 0) {
984 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000985 /* The following is not a bug: we really need to call lseek()
986 *and* ftell(). The reason is that some stdio libraries
987 mistakenly flush their buffer when ftell() is called and
988 the lseek() call it makes fails, thereby throwing away
989 data that cannot be recovered in any way. To avoid this,
990 we first test lseek(), and only call ftell() if lseek()
991 works. We can't use the lseek() value either, because we
992 need to take the amount of buffered data into account.
993 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000994 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000995 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000996 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000997 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000998 if (pos < 0)
999 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001000 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +00001001 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +00001002 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001003 }
1004#endif
1005 if (currentsize > SMALLCHUNK) {
1006 /* Keep doubling until we reach BIGCHUNK;
1007 then keep adding BIGCHUNK. */
1008 if (currentsize <= BIGCHUNK)
1009 return currentsize + currentsize;
1010 else
1011 return currentsize + BIGCHUNK;
1012 }
1013 return currentsize + SMALLCHUNK;
1014}
1015
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001016#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1017#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1018#else
1019#ifdef EWOULDBLOCK
1020#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1021#else
1022#ifdef EAGAIN
1023#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1024#else
1025#define BLOCKED_ERRNO(x) 0
1026#endif
1027#endif
1028#endif
1029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001030static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001031file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001032{
Guido van Rossum789a1611997-05-10 22:33:55 +00001033 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001034 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001035 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001036
Guido van Rossumd7297e61992-07-06 14:19:26 +00001037 if (f->f_fp == NULL)
1038 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001039 /* refuse to mix with f.next() */
1040 if (f->f_buf != NULL &&
1041 (f->f_bufend - f->f_bufptr) > 0 &&
1042 f->f_buf[0] != '\0')
1043 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001044 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +00001045 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001046 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +00001047 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001048 else
1049 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001050 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001051 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001052 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001053 return NULL;
1054 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001055 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001056 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001057 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001058 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001059 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001060 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001061 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001062 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001063 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001064 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001065 if (chunksize == 0) {
1066 if (!ferror(f->f_fp))
1067 break;
Guido van Rossum6263d541997-05-10 22:07:25 +00001068 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001069 /* When in non-blocking mode, data shouldn't
1070 * be discarded if a blocking signal was
1071 * received. That will also happen if
1072 * chunksize != 0, but bytesread < buffersize. */
1073 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1074 break;
1075 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +00001076 Py_DECREF(v);
1077 return NULL;
1078 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001079 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001080 if (bytesread < buffersize) {
1081 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001082 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001083 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001084 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +00001085 buffersize = new_buffersize(f, buffersize);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001086 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001087 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001088 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +00001089 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001090 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001091 }
1092 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001093 if (bytesread != buffersize)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001094 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001095 return v;
1096}
1097
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001098static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001099file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001100{
1101 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102 Py_ssize_t ntodo;
1103 Py_ssize_t ndone, nnow;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001104 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001105
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001106 if (f->f_fp == NULL)
1107 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001108 /* refuse to mix with f.next() */
1109 if (f->f_buf != NULL &&
1110 (f->f_bufend - f->f_bufptr) > 0 &&
1111 f->f_buf[0] != '\0')
1112 return err_iterbuffered();
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001113 if (!PyArg_ParseTuple(args, "w*", &pbuf))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001114 return NULL;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001115 ptr = pbuf.buf;
1116 ntodo = pbuf.len;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001117 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001118 while (ntodo > 0) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001119 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001120 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +00001121 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001122 (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001123 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001124 if (nnow == 0) {
1125 if (!ferror(f->f_fp))
1126 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001127 PyErr_SetFromErrno(PyExc_IOError);
1128 clearerr(f->f_fp);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001129 PyBuffer_Release(&pbuf);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001130 return NULL;
1131 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001132 ndone += nnow;
1133 ntodo -= nnow;
1134 }
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001135 PyBuffer_Release(&pbuf);
Neal Norwitz076d1e02006-08-21 18:20:10 +00001136 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001137}
1138
Tim Peters86821b22001-01-07 21:19:34 +00001139/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001140Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001141
1142Under MSVC 6:
1143
Tim Peters1c733232001-01-08 04:02:07 +00001144+ MS threadsafe getc is very slow (multiple layers of function calls before+
1145 after each character, to lock+unlock the stream).
1146+ The stream-locking functions are MS-internal -- can't access them from user
1147 code.
1148+ There's nothing Tim could find in the MS C or platform SDK libraries that
1149 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001150+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1151
1152So we use fgets for speed(!), despite that it's painful.
1153
1154MS realloc is also slow.
1155
Tim Petersf29b64d2001-01-15 06:33:19 +00001156Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1157have):
1158 Linux a wash
1159 Solaris a wash
1160 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001161
Tim Petersf29b64d2001-01-15 06:33:19 +00001162CAUTION: The C std isn't clear about this: in those cases where fgets
1163writes something into the buffer, can it write into any position beyond the
1164required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1165known on which it does; and it would be a strange way to code fgets. Still,
1166getline_via_fgets may not work correctly if it does. The std test
1167test_bufio.py should fail if platform fgets() routinely writes beyond the
1168trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001169**************************************************************************/
1170
Tim Petersf29b64d2001-01-15 06:33:19 +00001171/* Use this routine if told to, or by default on non-get_unlocked()
1172 * platforms unless told not to. Yikes! Let's spell that out:
1173 * On a platform with getc_unlocked():
1174 * By default, use getc_unlocked().
1175 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1176 * On a platform without getc_unlocked():
1177 * By default, use fgets().
1178 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1179 */
1180#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1181#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001182#endif
1183
Tim Petersf29b64d2001-01-15 06:33:19 +00001184#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1185#undef USE_FGETS_IN_GETLINE
1186#endif
1187
1188#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001189static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001190getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001191{
Tim Peters15b83852001-01-08 00:53:12 +00001192/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001193 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1194 * to fill this much of the buffer with a known value in order to figure out
1195 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1196 * than "most" lines, we waste time filling unused buffer slots. 100 is
1197 * surely adequate for most peoples' email archives, chewing over source code,
1198 * etc -- "regular old text files".
1199 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1200 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1201 * cautions about boosting that. 300 was chosen because the worst real-life
1202 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1203 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001204 */
Tim Peters142297a2001-01-15 10:36:56 +00001205#define INITBUFSIZE 100
1206#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001207 char* p; /* temp */
1208 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001209 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001210 char* pvfree; /* address of next free slot */
1211 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001212 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1213 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001214 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001215 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001216
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001217 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001218 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001219 */
Tim Peters142297a2001-01-15 10:36:56 +00001220 total_v_size = INITBUFSIZE; /* start small and pray */
1221 pvfree = buf;
1222 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001223 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters142297a2001-01-15 10:36:56 +00001224 pvend = buf + total_v_size;
1225 nfree = pvend - pvfree;
1226 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001227 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1228 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001229 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001230
Tim Peters142297a2001-01-15 10:36:56 +00001231 if (p == NULL) {
1232 clearerr(fp);
1233 if (PyErr_CheckSignals())
1234 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001235 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001236 return v;
1237 }
Tim Peters142297a2001-01-15 10:36:56 +00001238 /* fgets read *something* */
1239 p = memchr(pvfree, '\n', nfree);
1240 if (p != NULL) {
1241 /* Did the \n come from fgets or from us?
1242 * Since fgets stops at the first \n, and then writes
1243 * \0, if it's from fgets a \0 must be next. But if
1244 * that's so, it could not have come from us, since
1245 * the \n's we filled the buffer with have only more
1246 * \n's to the right.
1247 */
1248 if (p+1 < pvend && *(p+1) == '\0') {
1249 /* It's from fgets: we win! In particular,
1250 * we haven't done any mallocs yet, and can
1251 * build the final result on the first try.
1252 */
1253 ++p; /* include \n from fgets */
1254 }
1255 else {
1256 /* Must be from us: fgets didn't fill the
1257 * buffer and didn't find a newline, so it
1258 * must be the last and newline-free line of
1259 * the file.
1260 */
1261 assert(p > pvfree && *(p-1) == '\0');
1262 --p; /* don't include \0 from fgets */
1263 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001264 v = PyString_FromStringAndSize(buf, p - buf);
Tim Peters142297a2001-01-15 10:36:56 +00001265 return v;
1266 }
1267 /* yuck: fgets overwrote all the newlines, i.e. the entire
1268 * buffer. So this line isn't over yet, or maybe it is but
1269 * we're exactly at EOF. If we haven't already, try using the
1270 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001271 */
Tim Peters142297a2001-01-15 10:36:56 +00001272 assert(*(pvend-1) == '\0');
1273 if (pvfree == buf) {
1274 pvfree = pvend - 1; /* overwrite trailing null */
1275 total_v_size = MAXBUFSIZE;
1276 }
1277 else
1278 break;
Tim Peters86821b22001-01-07 21:19:34 +00001279 }
Tim Peters142297a2001-01-15 10:36:56 +00001280
1281 /* The stack buffer isn't big enough; malloc a string object and read
1282 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001283 */
Tim Petersddea2082002-03-23 10:03:50 +00001284 total_v_size = MAXBUFSIZE << 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001285 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001286 if (v == NULL)
1287 return v;
1288 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001289 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1290 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001291
1292 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001293 * after setting p one beyond the end of the line. The code here is
1294 * very much like the code above, except reads into v's buffer; see
1295 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001296 */
1297 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001298 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001299 pvend = BUF(v) + total_v_size;
1300 nfree = pvend - pvfree;
1301 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001302 assert(nfree < INT_MAX);
1303 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001304 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001305
1306 if (p == NULL) {
1307 clearerr(fp);
1308 if (PyErr_CheckSignals()) {
1309 Py_DECREF(v);
1310 return NULL;
1311 }
1312 p = pvfree;
1313 break;
1314 }
Tim Peters86821b22001-01-07 21:19:34 +00001315 p = memchr(pvfree, '\n', nfree);
1316 if (p != NULL) {
1317 if (p+1 < pvend && *(p+1) == '\0') {
1318 /* \n came from fgets */
1319 ++p;
1320 break;
1321 }
1322 /* \n came from us; last line of file, no newline */
1323 assert(p > pvfree && *(p-1) == '\0');
1324 --p;
1325 break;
1326 }
1327 /* expand buffer and try again */
1328 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001329 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001330 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001331 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001332 /* check for overflow */
1333 if (total_v_size <= prev_v_size ||
1334 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001335 PyErr_SetString(PyExc_OverflowError,
1336 "line is longer than a Python string can hold");
1337 Py_DECREF(v);
1338 return NULL;
1339 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001340 if (_PyString_Resize(&v, (int)total_v_size) < 0)
Tim Peters86821b22001-01-07 21:19:34 +00001341 return NULL;
1342 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001343 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001344 }
1345 if (BUF(v) + total_v_size != p)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001346 _PyString_Resize(&v, p - BUF(v));
Tim Peters86821b22001-01-07 21:19:34 +00001347 return v;
1348#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001349#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001350}
Tim Petersf29b64d2001-01-15 06:33:19 +00001351#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001352
Guido van Rossum0bd24411991-04-04 15:21:57 +00001353/* Internal routine to get a line.
1354 Size argument interpretation:
1355 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001356 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001357*/
1358
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001359static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001360get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001361{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001362 FILE *fp = f->f_fp;
1363 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001364 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001365 size_t total_v_size; /* total # of slots in buffer */
1366 size_t used_v_size; /* # used slots in buffer */
1367 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001368 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001369 int newlinetypes = f->f_newlinetypes;
1370 int skipnextlf = f->f_skipnextlf;
1371 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001372
Jack Jansen7b8c7542002-04-14 20:12:41 +00001373#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001374 if (n <= 0 && !univ_newline )
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001375 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001376#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001377 total_v_size = n > 0 ? n : 100;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001378 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001379 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001380 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001381 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001382 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001383
Guido van Rossumce5ba841991-03-06 13:06:18 +00001384 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001385 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001386 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001387 if (univ_newline) {
1388 c = 'x'; /* Shut up gcc warning */
1389 while ( buf != end && (c = GETC(fp)) != EOF ) {
1390 if (skipnextlf ) {
1391 skipnextlf = 0;
1392 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001393 /* Seeing a \n here with
1394 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001395 * saw a \r before.
1396 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001397 newlinetypes |= NEWLINE_CRLF;
1398 c = GETC(fp);
1399 if (c == EOF) break;
1400 } else {
1401 newlinetypes |= NEWLINE_CR;
1402 }
1403 }
1404 if (c == '\r') {
1405 skipnextlf = 1;
1406 c = '\n';
1407 } else if ( c == '\n')
1408 newlinetypes |= NEWLINE_LF;
1409 *buf++ = c;
1410 if (c == '\n') break;
1411 }
1412 if ( c == EOF && skipnextlf )
1413 newlinetypes |= NEWLINE_CR;
1414 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001415 while ((c = GETC(fp)) != EOF &&
1416 (*buf++ = c) != '\n' &&
1417 buf != end)
1418 ;
1419 FUNLOCKFILE(fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001420 FILE_END_ALLOW_THREADS(f)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001421 f->f_newlinetypes = newlinetypes;
1422 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001423 if (c == '\n')
1424 break;
1425 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001426 if (ferror(fp)) {
1427 PyErr_SetFromErrno(PyExc_IOError);
1428 clearerr(fp);
1429 Py_DECREF(v);
1430 return NULL;
1431 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001432 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001433 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001434 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001435 return NULL;
1436 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001437 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001438 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001439 /* Must be because buf == end */
1440 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001441 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001442 used_v_size = total_v_size;
1443 increment = total_v_size >> 2; /* mild exponential growth */
1444 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001445 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001446 PyErr_SetString(PyExc_OverflowError,
1447 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001448 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001449 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001450 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001451 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001452 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001453 buf = BUF(v) + used_v_size;
1454 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001455 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001456
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001457 used_v_size = buf - BUF(v);
1458 if (used_v_size != total_v_size)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001459 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001460 return v;
1461}
1462
Guido van Rossum0bd24411991-04-04 15:21:57 +00001463/* External C interface */
1464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001465PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001466PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001467{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001468 PyObject *result;
1469
Guido van Rossum3165fe61992-09-25 21:59:05 +00001470 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001471 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001472 return NULL;
1473 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001474
1475 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001476 PyFileObject *fo = (PyFileObject *)f;
1477 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001478 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001479 /* refuse to mix with f.next() */
1480 if (fo->f_buf != NULL &&
1481 (fo->f_bufend - fo->f_bufptr) > 0 &&
1482 fo->f_buf[0] != '\0')
1483 return err_iterbuffered();
1484 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001485 }
1486 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001487 PyObject *reader;
1488 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001489
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001491 if (reader == NULL)
1492 return NULL;
1493 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001494 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001495 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001496 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001497 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001498 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001499 return NULL;
1500 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001501 result = PyEval_CallObject(reader, args);
1502 Py_DECREF(reader);
1503 Py_DECREF(args);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001504 if (result != NULL && !PyString_Check(result) &&
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001505 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001506 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001507 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001508 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001509 "object.readline() returned non-string");
1510 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001511 }
1512
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001513 if (n < 0 && result != NULL && PyString_Check(result)) {
1514 char *s = PyString_AS_STRING(result);
1515 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001516 if (len == 0) {
1517 Py_DECREF(result);
1518 result = NULL;
1519 PyErr_SetString(PyExc_EOFError,
1520 "EOF when reading a line");
1521 }
1522 else if (s[len-1] == '\n') {
1523 if (result->ob_refcnt == 1)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001524 _PyString_Resize(&result, len-1);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001525 else {
1526 PyObject *v;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001527 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001528 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001529 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001530 }
1531 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001532 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001533#ifdef Py_USING_UNICODE
1534 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1535 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001536 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001537 if (len == 0) {
1538 Py_DECREF(result);
1539 result = NULL;
1540 PyErr_SetString(PyExc_EOFError,
1541 "EOF when reading a line");
1542 }
1543 else if (s[len-1] == '\n') {
1544 if (result->ob_refcnt == 1)
1545 PyUnicode_Resize(&result, len-1);
1546 else {
1547 PyObject *v;
1548 v = PyUnicode_FromUnicode(s, len-1);
1549 Py_DECREF(result);
1550 result = v;
1551 }
1552 }
1553 }
1554#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001555 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001556}
1557
1558/* Python method */
1559
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001560static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001561file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001562{
Guido van Rossum789a1611997-05-10 22:33:55 +00001563 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001564
Guido van Rossumd7297e61992-07-06 14:19:26 +00001565 if (f->f_fp == NULL)
1566 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001567 /* refuse to mix with f.next() */
1568 if (f->f_buf != NULL &&
1569 (f->f_bufend - f->f_bufptr) > 0 &&
1570 f->f_buf[0] != '\0')
1571 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001572 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001573 return NULL;
1574 if (n == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001575 return PyString_FromString("");
Guido van Rossum789a1611997-05-10 22:33:55 +00001576 if (n < 0)
1577 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001578 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001579}
1580
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001581static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001582file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001583{
Guido van Rossum789a1611997-05-10 22:33:55 +00001584 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001585 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001586 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001587 char small_buffer[SMALLCHUNK];
1588 char *buffer = small_buffer;
1589 size_t buffersize = SMALLCHUNK;
1590 PyObject *big_buffer = NULL;
1591 size_t nfilled = 0;
1592 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001593 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001594 char *p, *q, *end;
1595 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001596 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001597
Guido van Rossumd7297e61992-07-06 14:19:26 +00001598 if (f->f_fp == NULL)
1599 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001600 /* refuse to mix with f.next() */
1601 if (f->f_buf != NULL &&
1602 (f->f_bufend - f->f_bufptr) > 0 &&
1603 f->f_buf[0] != '\0')
1604 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001605 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001606 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001607 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001608 return NULL;
1609 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001610 if (shortread)
1611 nread = 0;
1612 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001613 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001614 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001615 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001616 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001617 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001618 shortread = (nread < buffersize-nfilled);
1619 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001620 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001621 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001622 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001623 break;
1624 PyErr_SetFromErrno(PyExc_IOError);
1625 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001626 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001627 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001628 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001629 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001630 if (p == NULL) {
1631 /* Need a larger buffer to fit this line */
1632 nfilled += nread;
1633 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001634 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001635 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001636 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001637 goto error;
1638 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001639 if (big_buffer == NULL) {
1640 /* Create the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001641 big_buffer = PyString_FromStringAndSize(
Guido van Rossum6263d541997-05-10 22:07:25 +00001642 NULL, buffersize);
1643 if (big_buffer == NULL)
1644 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001645 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001646 memcpy(buffer, small_buffer, nfilled);
1647 }
1648 else {
1649 /* Grow the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001650 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
Jack Jansen7b8c7542002-04-14 20:12:41 +00001651 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001652 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001653 }
1654 continue;
1655 }
1656 end = buffer+nfilled+nread;
1657 q = buffer;
1658 do {
1659 /* Process complete lines */
1660 p++;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001661 line = PyString_FromStringAndSize(q, p-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001662 if (line == NULL)
1663 goto error;
1664 err = PyList_Append(list, line);
1665 Py_DECREF(line);
1666 if (err != 0)
1667 goto error;
1668 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001669 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001670 } while (p != NULL);
1671 /* Move the remaining incomplete line to the start */
1672 nfilled = end-q;
1673 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001674 if (sizehint > 0)
1675 if (totalread >= (size_t)sizehint)
1676 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001677 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001678 if (nfilled != 0) {
1679 /* Partial last line */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001680 line = PyString_FromStringAndSize(buffer, nfilled);
Guido van Rossum6263d541997-05-10 22:07:25 +00001681 if (line == NULL)
1682 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001683 if (sizehint > 0) {
1684 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001685 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001686 if (rest == NULL) {
1687 Py_DECREF(line);
1688 goto error;
1689 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001690 PyString_Concat(&line, rest);
Guido van Rossum789a1611997-05-10 22:33:55 +00001691 Py_DECREF(rest);
1692 if (line == NULL)
1693 goto error;
1694 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001695 err = PyList_Append(list, line);
1696 Py_DECREF(line);
1697 if (err != 0)
1698 goto error;
1699 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001700
1701cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001702 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001703 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001704
1705error:
1706 Py_CLEAR(list);
1707 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001708}
1709
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001710static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001711file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001712{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001713 Py_buffer pbuf;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001714 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001715 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001716 if (f->f_fp == NULL)
1717 return err_closed();
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001718 if (f->f_binary) {
1719 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1720 return NULL;
1721 s = pbuf.buf;
1722 n = pbuf.len;
1723 } else
1724 if (!PyArg_ParseTuple(args, "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001725 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001726 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001727 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001728 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001729 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001730 FILE_END_ALLOW_THREADS(f)
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001731 if (f->f_binary)
1732 PyBuffer_Release(&pbuf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001733 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001734 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001735 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001736 return NULL;
1737 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001738 Py_INCREF(Py_None);
1739 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740}
1741
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001742static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001743file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001744{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001745#define CHUNKSIZE 1000
1746 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001747 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001748 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001749 int index, islist;
1750 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001751
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001752 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001753 if (f->f_fp == NULL)
1754 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001755
1756 result = NULL;
1757 list = NULL;
1758 islist = PyList_Check(seq);
1759 if (islist)
1760 it = NULL;
1761 else {
1762 it = PyObject_GetIter(seq);
1763 if (it == NULL) {
1764 PyErr_SetString(PyExc_TypeError,
1765 "writelines() requires an iterable argument");
1766 return NULL;
1767 }
1768 /* From here on, fail by going to error, to reclaim "it". */
1769 list = PyList_New(CHUNKSIZE);
1770 if (list == NULL)
1771 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001772 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001773
1774 /* Strategy: slurp CHUNKSIZE lines into a private list,
1775 checking that they are all strings, then write that list
1776 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001777 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001778 if (islist) {
1779 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001780 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001781 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001782 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001783 j = PyList_GET_SIZE(list);
1784 }
1785 else {
1786 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001787 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001788 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001789 if (PyErr_Occurred())
1790 goto error;
1791 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001792 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001793 PyList_SetItem(list, j, line);
1794 }
1795 }
1796 if (j == 0)
1797 break;
1798
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001799 /* Check that all entries are indeed strings. If not,
1800 apply the same rules as for file.write() and
1801 convert the results to strings. This is slow, but
1802 seems to be the only way since all conversion APIs
1803 could potentially execute Python code. */
1804 for (i = 0; i < j; i++) {
1805 PyObject *v = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001806 if (!PyString_Check(v)) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001807 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001808 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001809 PyObject_AsReadBuffer(v,
1810 (const void**)&buffer,
1811 &len)) ||
1812 PyObject_AsCharBuffer(v,
1813 &buffer,
1814 &len))) {
1815 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001816 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001817 goto error;
1818 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001819 line = PyString_FromStringAndSize(buffer,
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001820 len);
1821 if (line == NULL)
1822 goto error;
1823 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001824 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001825 }
1826 }
1827
1828 /* Since we are releasing the global lock, the
1829 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001830 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001831 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001832 errno = 0;
1833 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001834 line = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001835 len = PyString_GET_SIZE(line);
1836 nwritten = fwrite(PyString_AS_STRING(line),
Guido van Rossumee70ad12000-03-13 16:27:06 +00001837 1, len, f->f_fp);
1838 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001839 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001840 PyErr_SetFromErrno(PyExc_IOError);
1841 clearerr(f->f_fp);
1842 goto error;
1843 }
1844 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001845 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001846
1847 if (j < CHUNKSIZE)
1848 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001849 }
1850
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001851 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001852 result = Py_None;
1853 error:
1854 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001855 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001856 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001857#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001858}
1859
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001860static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001861file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001862{
1863 if (f->f_fp == NULL)
1864 return err_closed();
1865 Py_INCREF(f);
1866 return (PyObject *)f;
1867}
1868
Georg Brandl98b40ad2006-06-08 14:50:21 +00001869static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001870file_xreadlines(PyFileObject *f)
1871{
1872 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1873 "try 'for line in f' instead", 1) < 0)
1874 return NULL;
1875 return file_self(f);
1876}
1877
1878static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001879file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001880{
Georg Brandlad61bc82008-02-23 15:11:18 +00001881 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001882 if (!ret)
1883 /* If error occurred, pass through */
1884 return NULL;
1885 Py_DECREF(ret);
1886 /* We cannot return the result of close since a true
1887 * value will be interpreted as "yes, swallow the
1888 * exception if one was raised inside the with block". */
1889 Py_RETURN_NONE;
1890}
1891
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001892PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001893"readline([size]) -> next line from the file, as a string.\n"
1894"\n"
1895"Retain newline. A non-negative size argument limits the maximum\n"
1896"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001897"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001899PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001900"read([size]) -> read at most size bytes, returned as a string.\n"
1901"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001902"If the size argument is negative or omitted, read until EOF is reached.\n"
1903"Notice that when in non-blocking mode, less data than what was requested\n"
1904"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001906PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001907"write(str) -> None. Write string str to file.\n"
1908"\n"
1909"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001910"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001912PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001913"fileno() -> integer \"file descriptor\".\n"
1914"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001915"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001917PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001918"seek(offset[, whence]) -> None. Move to new file position.\n"
1919"\n"
1920"Argument offset is a byte count. Optional argument whence defaults to\n"
1921"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1922"(move relative to current position, positive or negative), and 2 (move\n"
1923"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001924"seeking beyond the end of a file). If the file is opened in text mode,\n"
1925"only offsets returned by tell() are legal. Use of other offsets causes\n"
1926"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001927"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001928"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001929
Guido van Rossumd7047b31995-01-02 19:07:15 +00001930#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001931PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001932"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1933"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001934"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001935#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001937PyDoc_STRVAR(tell_doc,
1938"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001940PyDoc_STRVAR(readinto_doc,
1941"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001943PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001944"readlines([size]) -> list of strings, each a line from the file.\n"
1945"\n"
1946"Call readline() repeatedly and return a list of the lines so read.\n"
1947"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001948"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001950PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001951"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001952"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001953"For backward compatibility. File objects now include the performance\n"
1954"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001956PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001957"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001958"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001959"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001960"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001961
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001962PyDoc_STRVAR(flush_doc,
1963"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001965PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001966"close() -> None or (perhaps) an integer. Close the file.\n"
1967"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001968"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001969"further I/O operations. close() may be called more than once without\n"
1970"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001972
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001973PyDoc_STRVAR(isatty_doc,
1974"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001975
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001976PyDoc_STRVAR(enter_doc,
1977 "__enter__() -> self.");
1978
Georg Brandl98b40ad2006-06-08 14:50:21 +00001979PyDoc_STRVAR(exit_doc,
1980 "__exit__(*excinfo) -> None. Closes the file.");
1981
Tim Petersefc3a3a2001-09-20 07:55:22 +00001982static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001983 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1984 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1985 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1986 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1987 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001988#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001989 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001990#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001991 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1992 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
Georg Brandla9916b52008-05-17 22:11:54 +00001993 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
1994 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
1995 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001996 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1997 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1998 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001999 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00002000 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00002001 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002002};
2003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002004#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002005
Guido van Rossum6f799372001-09-20 20:46:19 +00002006static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00002007 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00002008 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00002009 {"name", T_OBJECT, OFF(f_name), RO,
2010 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002011 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2012 "file encoding"},
Martin v. Löwis99815892008-06-01 07:20:46 +00002013 {"errors", T_OBJECT, OFF(f_errors), RO,
2014 "Unicode error handler"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00002015 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002016 {NULL} /* Sentinel */
2017};
2018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002021{
Guido van Rossum77f6a652002-04-03 22:41:51 +00002022 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002023}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002024static PyObject *
2025get_newlines(PyFileObject *f, void *closure)
2026{
2027 switch (f->f_newlinetypes) {
2028 case NEWLINE_UNKNOWN:
2029 Py_INCREF(Py_None);
2030 return Py_None;
2031 case NEWLINE_CR:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002032 return PyString_FromString("\r");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002033 case NEWLINE_LF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002034 return PyString_FromString("\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002035 case NEWLINE_CR|NEWLINE_LF:
2036 return Py_BuildValue("(ss)", "\r", "\n");
2037 case NEWLINE_CRLF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002038 return PyString_FromString("\r\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002039 case NEWLINE_CR|NEWLINE_CRLF:
2040 return Py_BuildValue("(ss)", "\r", "\r\n");
2041 case NEWLINE_LF|NEWLINE_CRLF:
2042 return Py_BuildValue("(ss)", "\n", "\r\n");
2043 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2044 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2045 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00002046 PyErr_Format(PyExc_SystemError,
2047 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00002048 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00002049 return NULL;
2050 }
2051}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002052
Georg Brandl65bb42d2008-03-21 20:38:24 +00002053static PyObject *
2054get_softspace(PyFileObject *f, void *closure)
2055{
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002056 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002057 return NULL;
2058 return PyInt_FromLong(f->f_softspace);
2059}
2060
2061static int
2062set_softspace(PyFileObject *f, PyObject *value)
2063{
2064 int new;
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002065 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002066 return -1;
2067
2068 if (value == NULL) {
2069 PyErr_SetString(PyExc_TypeError,
2070 "can't delete softspace attribute");
2071 return -1;
2072 }
2073
2074 new = PyInt_AsLong(value);
2075 if (new == -1 && PyErr_Occurred())
2076 return -1;
2077 f->f_softspace = new;
2078 return 0;
2079}
2080
Guido van Rossum32d34c82001-09-20 21:45:26 +00002081static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00002082 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00002083 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00002084 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00002085 {"softspace", (getter)get_softspace, (setter)set_softspace,
2086 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002087 {0},
2088};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002089
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002090static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002091drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002092{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002093 if (f->f_buf != NULL) {
2094 PyMem_Free(f->f_buf);
2095 f->f_buf = NULL;
2096 }
Guido van Rossum65967252001-04-21 13:20:18 +00002097}
2098
Tim Petersf1827cf2003-09-07 03:30:18 +00002099/* Make sure that file has a readahead buffer with at least one byte
2100 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002101 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002102static int
2103readahead(PyFileObject *f, int bufsize)
2104{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002105 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002106
2107 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00002108 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002109 return 0;
2110 else
2111 drop_readahead(f);
2112 }
Anthony Baxter377be112006-04-11 06:54:30 +00002113 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00002114 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002115 return -1;
2116 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002117 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002118 errno = 0;
2119 chunksize = Py_UniversalNewlineFread(
2120 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002121 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002122 if (chunksize == 0) {
2123 if (ferror(f->f_fp)) {
2124 PyErr_SetFromErrno(PyExc_IOError);
2125 clearerr(f->f_fp);
2126 drop_readahead(f);
2127 return -1;
2128 }
2129 }
2130 f->f_bufptr = f->f_buf;
2131 f->f_bufend = f->f_buf + chunksize;
2132 return 0;
2133}
2134
2135/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002136 uninitialized bytes followed by the remainder of the line. Don't be
2137 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002138 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2139
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002140static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002141readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2142{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002143 PyStringObject* s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002144 char *bufptr;
2145 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002146 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002147
2148 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002149 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002150 return NULL;
2151
2152 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002153 if (len == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002154 return (PyStringObject *)
2155 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002156 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002157 if (bufptr != NULL) {
2158 bufptr++; /* Count the '\n' */
2159 len = bufptr - f->f_bufptr;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002160 s = (PyStringObject *)
2161 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002162 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002163 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002164 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002165 f->f_bufptr = bufptr;
2166 if (bufptr == f->f_bufend)
2167 drop_readahead(f);
2168 } else {
2169 bufptr = f->f_bufptr;
2170 buf = f->f_buf;
2171 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002172 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002173 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002174 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002175 if (s == NULL) {
2176 PyMem_Free(buf);
2177 return NULL;
2178 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002179 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002180 PyMem_Free(buf);
2181 }
2182 return s;
2183}
2184
2185/* A larger buffer size may actually decrease performance. */
2186#define READAHEAD_BUFSIZE 8192
2187
2188static PyObject *
2189file_iternext(PyFileObject *f)
2190{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002191 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002192
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002193 if (f->f_fp == NULL)
2194 return err_closed();
2195
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002196 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002197 if (l == NULL || PyString_GET_SIZE(l) == 0) {
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002198 Py_XDECREF(l);
2199 return NULL;
2200 }
2201 return (PyObject *)l;
2202}
2203
2204
Tim Peters59c9a642001-09-13 05:38:56 +00002205static PyObject *
2206file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2207{
Tim Peters44410012001-09-14 03:26:08 +00002208 PyObject *self;
2209 static PyObject *not_yet_string;
2210
2211 assert(type != NULL && type->tp_alloc != NULL);
2212
2213 if (not_yet_string == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002214 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002215 if (not_yet_string == NULL)
2216 return NULL;
2217 }
2218
2219 self = type->tp_alloc(type, 0);
2220 if (self != NULL) {
2221 /* Always fill in the name and mode, so that nobody else
2222 needs to special-case NULLs there. */
2223 Py_INCREF(not_yet_string);
2224 ((PyFileObject *)self)->f_name = not_yet_string;
2225 Py_INCREF(not_yet_string);
2226 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002227 Py_INCREF(Py_None);
2228 ((PyFileObject *)self)->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +00002229 Py_INCREF(Py_None);
2230 ((PyFileObject *)self)->f_errors = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002231 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002232 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002233 }
2234 return self;
2235}
2236
2237static int
2238file_init(PyObject *self, PyObject *args, PyObject *kwds)
2239{
2240 PyFileObject *foself = (PyFileObject *)self;
2241 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002242 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002243 char *name = NULL;
2244 char *mode = "r";
2245 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002246 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00002247
2248 assert(PyFile_Check(self));
2249 if (foself->f_fp != NULL) {
2250 /* Have to close the existing file first. */
2251 PyObject *closeresult = file_close(foself);
2252 if (closeresult == NULL)
2253 return -1;
2254 Py_DECREF(closeresult);
2255 }
Tim Peters59c9a642001-09-13 05:38:56 +00002256
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002257#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002258 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2259 PyObject *po;
2260 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2261 kwlist, &po, &mode, &bufsize)) {
2262 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002263 if (fill_file_fields(foself, NULL, po, mode,
2264 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002265 goto Error;
2266 } else {
2267 /* Drop the argument parsing error as narrow
2268 strings are also valid. */
2269 PyErr_Clear();
2270 }
2271 }
2272#endif
2273
2274 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002275 PyObject *o_name;
2276
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002277 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2278 Py_FileSystemDefaultEncoding,
2279 &name,
2280 &mode, &bufsize))
2281 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002282
2283 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002284 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2285 kwlist, &o_name, &mode,
2286 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002287 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002288
2289 if (fill_file_fields(foself, NULL, o_name, mode,
2290 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002291 goto Error;
2292 }
Tim Peters44410012001-09-14 03:26:08 +00002293 if (open_the_file(foself, name, mode) == NULL)
2294 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002295 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002296 PyFile_SetBufSize(self, bufsize);
2297 goto Done;
2298
2299Error:
2300 ret = -1;
2301 /* fall through */
2302Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002303 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002304 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002305}
2306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002307PyDoc_VAR(file_doc) =
2308PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002309"file(name[, mode[, buffering]]) -> file object\n"
2310"\n"
2311"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2312"writing or appending. The file will be created if it doesn't exist\n"
2313"when opened for writing or appending; it will be truncated when\n"
2314"opened for writing. Add a 'b' to the mode for binary files.\n"
2315"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2316"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002317"buffered, and larger numbers specify the buffer size. The preferred way\n"
2318"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002319)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002320PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002321"Add a 'U' to mode to open the file for input with universal newline\n"
2322"support. Any line ending in the input file will be seen as a '\\n'\n"
2323"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2324"the value for this attribute is one of None (no newline read yet),\n"
2325"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2326"\n"
2327"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002328);
Tim Peters59c9a642001-09-13 05:38:56 +00002329
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002330PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002331 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002332 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002333 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002334 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002335 (destructor)file_dealloc, /* tp_dealloc */
2336 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002337 0, /* tp_getattr */
2338 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002339 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002341 0, /* tp_as_number */
2342 0, /* tp_as_sequence */
2343 0, /* tp_as_mapping */
2344 0, /* tp_hash */
2345 0, /* tp_call */
2346 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002348 /* softspace is writable: we must supply tp_setattro */
2349 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002350 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002351 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002352 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353 0, /* tp_traverse */
2354 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002355 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002356 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002357 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002358 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359 file_methods, /* tp_methods */
2360 file_memberlist, /* tp_members */
2361 file_getsetlist, /* tp_getset */
2362 0, /* tp_base */
2363 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002364 0, /* tp_descr_get */
2365 0, /* tp_descr_set */
2366 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002367 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002368 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002369 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002370 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002371};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002372
2373/* Interface for the 'soft space' between print items. */
2374
2375int
Fred Drakefd99de62000-07-09 05:02:18 +00002376PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002377{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002378 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002379 if (f == NULL) {
2380 /* Do nothing */
2381 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002382 else if (PyFile_Check(f)) {
2383 oldflag = ((PyFileObject *)f)->f_softspace;
2384 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002385 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002386 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002387 PyObject *v;
2388 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002389 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002390 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002391 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002392 if (PyInt_Check(v))
2393 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002394 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002395 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002396 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002397 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002398 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002399 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002400 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002401 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2402 PyErr_Clear();
2403 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002404 }
2405 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002406 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002407}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002408
2409/* Interfaces to write objects/strings to file-like objects */
2410
2411int
Fred Drakefd99de62000-07-09 05:02:18 +00002412PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002413{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002414 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002415 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002416 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002417 return -1;
2418 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002419 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002420 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002421#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002422 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002423 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002424#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002425 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002426 err_closed();
2427 return -1;
2428 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002429#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002430 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002431 PyUnicode_Check(v) && enc != Py_None) {
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002432 char *cenc = PyString_AS_STRING(enc);
Martin v. Löwis99815892008-06-01 07:20:46 +00002433 char *errors = fobj->f_errors == Py_None ?
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002434 "strict" : PyString_AS_STRING(fobj->f_errors);
Martin v. Löwis99815892008-06-01 07:20:46 +00002435 value = PyUnicode_AsEncodedString(v, cenc, errors);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002436 if (value == NULL)
2437 return -1;
2438 } else {
2439 value = v;
2440 Py_INCREF(value);
2441 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002442 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002443 Py_DECREF(value);
2444 return result;
2445#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002446 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002447#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002448 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002449 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002450 if (writer == NULL)
2451 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002452 if (flags & Py_PRINT_RAW) {
2453 if (PyUnicode_Check(v)) {
2454 value = v;
2455 Py_INCREF(value);
2456 } else
2457 value = PyObject_Str(v);
2458 }
2459 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002460 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002461 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002462 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002463 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002464 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002465 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002466 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002467 Py_DECREF(value);
2468 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002469 return -1;
2470 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002471 result = PyEval_CallObject(writer, args);
2472 Py_DECREF(args);
2473 Py_DECREF(value);
2474 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002475 if (result == NULL)
2476 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002477 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002478 return 0;
2479}
2480
Guido van Rossum27a60b11997-05-22 22:25:11 +00002481int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002482PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002483{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002484
Guido van Rossum3165fe61992-09-25 21:59:05 +00002485 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002486 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002487 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002488 PyErr_SetString(PyExc_SystemError,
2489 "null file for PyFile_WriteString");
2490 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002491 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002492 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002493 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002494 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002495 if (fp == NULL) {
2496 err_closed();
2497 return -1;
2498 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002499 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002500 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002501 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002502 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002503 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002504 else if (!PyErr_Occurred()) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002505 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002506 int err;
2507 if (v == NULL)
2508 return -1;
2509 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2510 Py_DECREF(v);
2511 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002512 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002513 else
2514 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002515}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002516
2517/* Try to get a file-descriptor from a Python object. If the object
2518 is an integer or long integer, its value is returned. If not, the
2519 object's fileno() method is called if it exists; the method must return
2520 an integer or long integer, which is returned as the file descriptor value.
2521 -1 is returned on failure.
2522*/
2523
2524int PyObject_AsFileDescriptor(PyObject *o)
2525{
2526 int fd;
2527 PyObject *meth;
2528
2529 if (PyInt_Check(o)) {
2530 fd = PyInt_AsLong(o);
2531 }
2532 else if (PyLong_Check(o)) {
2533 fd = PyLong_AsLong(o);
2534 }
2535 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2536 {
2537 PyObject *fno = PyEval_CallObject(meth, NULL);
2538 Py_DECREF(meth);
2539 if (fno == NULL)
2540 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002541
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002542 if (PyInt_Check(fno)) {
2543 fd = PyInt_AsLong(fno);
2544 Py_DECREF(fno);
2545 }
2546 else if (PyLong_Check(fno)) {
2547 fd = PyLong_AsLong(fno);
2548 Py_DECREF(fno);
2549 }
2550 else {
2551 PyErr_SetString(PyExc_TypeError,
2552 "fileno() returned a non-integer");
2553 Py_DECREF(fno);
2554 return -1;
2555 }
2556 }
2557 else {
2558 PyErr_SetString(PyExc_TypeError,
2559 "argument must be an int, or have a fileno() method.");
2560 return -1;
2561 }
2562
2563 if (fd < 0) {
2564 PyErr_Format(PyExc_ValueError,
2565 "file descriptor cannot be a negative integer (%i)",
2566 fd);
2567 return -1;
2568 }
2569 return fd;
2570}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002571
Jack Jansen7b8c7542002-04-14 20:12:41 +00002572/* From here on we need access to the real fgets and fread */
2573#undef fgets
2574#undef fread
2575
2576/*
2577** Py_UniversalNewlineFgets is an fgets variation that understands
2578** all of \r, \n and \r\n conventions.
2579** The stream should be opened in binary mode.
2580** If fobj is NULL the routine always does newline conversion, and
2581** it may peek one char ahead to gobble the second char in \r\n.
2582** If fobj is non-NULL it must be a PyFileObject. In this case there
2583** is no readahead but in stead a flag is used to skip a following
2584** \n on the next read. Also, if the file is open in binary mode
2585** the whole conversion is skipped. Finally, the routine keeps track of
2586** the different types of newlines seen.
2587** Note that we need no error handling: fgets() treats error and eof
2588** identically.
2589*/
2590char *
2591Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2592{
2593 char *p = buf;
2594 int c;
2595 int newlinetypes = 0;
2596 int skipnextlf = 0;
2597 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002598
Jack Jansen7b8c7542002-04-14 20:12:41 +00002599 if (fobj) {
2600 if (!PyFile_Check(fobj)) {
2601 errno = ENXIO; /* What can you do... */
2602 return NULL;
2603 }
2604 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2605 if ( !univ_newline )
2606 return fgets(buf, n, stream);
2607 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2608 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2609 }
2610 FLOCKFILE(stream);
2611 c = 'x'; /* Shut up gcc warning */
2612 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2613 if (skipnextlf ) {
2614 skipnextlf = 0;
2615 if (c == '\n') {
2616 /* Seeing a \n here with skipnextlf true
2617 ** means we saw a \r before.
2618 */
2619 newlinetypes |= NEWLINE_CRLF;
2620 c = GETC(stream);
2621 if (c == EOF) break;
2622 } else {
2623 /*
2624 ** Note that c == EOF also brings us here,
2625 ** so we're okay if the last char in the file
2626 ** is a CR.
2627 */
2628 newlinetypes |= NEWLINE_CR;
2629 }
2630 }
2631 if (c == '\r') {
2632 /* A \r is translated into a \n, and we skip
2633 ** an adjacent \n, if any. We don't set the
2634 ** newlinetypes flag until we've seen the next char.
2635 */
2636 skipnextlf = 1;
2637 c = '\n';
2638 } else if ( c == '\n') {
2639 newlinetypes |= NEWLINE_LF;
2640 }
2641 *p++ = c;
2642 if (c == '\n') break;
2643 }
2644 if ( c == EOF && skipnextlf )
2645 newlinetypes |= NEWLINE_CR;
2646 FUNLOCKFILE(stream);
2647 *p = '\0';
2648 if (fobj) {
2649 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2650 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2651 } else if ( skipnextlf ) {
2652 /* If we have no file object we cannot save the
2653 ** skipnextlf flag. We have to readahead, which
2654 ** will cause a pause if we're reading from an
2655 ** interactive stream, but that is very unlikely
2656 ** unless we're doing something silly like
2657 ** execfile("/dev/tty").
2658 */
2659 c = GETC(stream);
2660 if ( c != '\n' )
2661 ungetc(c, stream);
2662 }
2663 if (p == buf)
2664 return NULL;
2665 return buf;
2666}
2667
2668/*
2669** Py_UniversalNewlineFread is an fread variation that understands
2670** all of \r, \n and \r\n conventions.
2671** The stream should be opened in binary mode.
2672** fobj must be a PyFileObject. In this case there
2673** is no readahead but in stead a flag is used to skip a following
2674** \n on the next read. Also, if the file is open in binary mode
2675** the whole conversion is skipped. Finally, the routine keeps track of
2676** the different types of newlines seen.
2677*/
2678size_t
Tim Peters058b1412002-04-21 07:29:14 +00002679Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002680 FILE *stream, PyObject *fobj)
2681{
Tim Peters058b1412002-04-21 07:29:14 +00002682 char *dst = buf;
2683 PyFileObject *f = (PyFileObject *)fobj;
2684 int newlinetypes, skipnextlf;
2685
2686 assert(buf != NULL);
2687 assert(stream != NULL);
2688
Jack Jansen7b8c7542002-04-14 20:12:41 +00002689 if (!fobj || !PyFile_Check(fobj)) {
2690 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002691 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002692 }
Tim Peters058b1412002-04-21 07:29:14 +00002693 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002694 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002695 newlinetypes = f->f_newlinetypes;
2696 skipnextlf = f->f_skipnextlf;
2697 /* Invariant: n is the number of bytes remaining to be filled
2698 * in the buffer.
2699 */
2700 while (n) {
2701 size_t nread;
2702 int shortread;
2703 char *src = dst;
2704
2705 nread = fread(dst, 1, n, stream);
2706 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002707 if (nread == 0)
2708 break;
2709
Tim Peterse1682a82002-04-21 18:15:20 +00002710 n -= nread; /* assuming 1 byte out for each in; will adjust */
2711 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002712 while (nread--) {
2713 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002714 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002715 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002716 *dst++ = '\n';
2717 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002718 }
2719 else if (skipnextlf && c == '\n') {
2720 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002721 skipnextlf = 0;
2722 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002723 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002724 }
2725 else {
2726 /* Normal char to be stored in buffer. Also
2727 * update the newlinetypes flag if either this
2728 * is an LF or the previous char was a CR.
2729 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002730 if (c == '\n')
2731 newlinetypes |= NEWLINE_LF;
2732 else if (skipnextlf)
2733 newlinetypes |= NEWLINE_CR;
2734 *dst++ = c;
2735 skipnextlf = 0;
2736 }
2737 }
Tim Peters058b1412002-04-21 07:29:14 +00002738 if (shortread) {
2739 /* If this is EOF, update type flags. */
2740 if (skipnextlf && feof(stream))
2741 newlinetypes |= NEWLINE_CR;
2742 break;
2743 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002744 }
Tim Peters058b1412002-04-21 07:29:14 +00002745 f->f_newlinetypes = newlinetypes;
2746 f->f_skipnextlf = skipnextlf;
2747 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002748}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002749
2750#ifdef __cplusplus
2751}
2752#endif