blob: f479501581e447eeafcc4b4c895bd17835714d5e [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Andrew MacIntyrec4874392002-02-26 11:36:35 +000019#if defined(PYOS_OS2) && defined(PYCC_GCC)
20#include <io.h>
21#endif
22
Gregory P. Smithdd96db62008-06-09 04:58:54 +000023#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000024
Andrew M. Kuchling00b6a5c2010-02-22 23:10:52 +000025#ifdef HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000026#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000027#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028
Jack Jansen7b8c7542002-04-14 20:12:41 +000029#ifdef HAVE_GETC_UNLOCKED
30#define GETC(f) getc_unlocked(f)
31#define FLOCKFILE(f) flockfile(f)
32#define FUNLOCKFILE(f) funlockfile(f)
33#else
34#define GETC(f) getc(f)
35#define FLOCKFILE(f)
36#define FUNLOCKFILE(f)
37#endif
38
Jack Jansen7b8c7542002-04-14 20:12:41 +000039/* Bits in f_newlinetypes */
40#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
41#define NEWLINE_CR 1 /* \r newline seen */
42#define NEWLINE_LF 2 /* \n newline seen */
43#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000044
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000045/*
46 * These macros release the GIL while preventing the f_close() function being
47 * called in the interval between them. For that purpose, a running total of
48 * the number of currently running unlocked code sections is kept in
49 * the unlocked_count field of the PyFileObject. The close() method raises
50 * an IOError if that field is non-zero. See issue #815646, #595601.
51 */
52
53#define FILE_BEGIN_ALLOW_THREADS(fobj) \
54{ \
55 fobj->unlocked_count++; \
56 Py_BEGIN_ALLOW_THREADS
57
58#define FILE_END_ALLOW_THREADS(fobj) \
59 Py_END_ALLOW_THREADS \
60 fobj->unlocked_count--; \
61 assert(fobj->unlocked_count >= 0); \
62}
63
64#define FILE_ABORT_ALLOW_THREADS(fobj) \
65 Py_BLOCK_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0);
68
Anthony Baxterac6bd462006-04-13 02:06:09 +000069#ifdef __cplusplus
70extern "C" {
71#endif
72
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000074PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000078 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080}
81
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000082void PyFile_IncUseCount(PyFileObject *fobj)
83{
84 fobj->unlocked_count++;
85}
86
87void PyFile_DecUseCount(PyFileObject *fobj)
88{
89 fobj->unlocked_count--;
90 assert(fobj->unlocked_count >= 0);
91}
92
Guido van Rossumc0b618a1997-05-02 03:12:38 +000093PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000094PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000095{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000097 return NULL;
98 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000100}
101
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000102/* This is a safe wrapper around PyObject_Print to print to the FILE
103 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
104 about PyFileObject. */
105static int
106file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
107{
108 int result;
109 PyFile_IncUseCount(f);
110 result = PyObject_Print(op, f->f_fp, flags);
111 PyFile_DecUseCount(f);
112 return result;
113}
114
Neil Schemenauered19b882002-03-23 02:06:50 +0000115/* On Unix, fopen will succeed for directories.
116 In Python, there should be no file objects referring to
117 directories, so we need a check. */
118
119static PyFileObject*
120dircheck(PyFileObject* f)
121{
122#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
123 struct stat buf;
124 if (f->f_fp == NULL)
125 return f;
126 if (fstat(fileno(f->f_fp), &buf) == 0 &&
127 S_ISDIR(buf.st_mode)) {
Neil Schemenauered19b882002-03-23 02:06:50 +0000128 char *msg = strerror(EISDIR);
Benjamin Petersonfe231b02008-12-29 17:47:42 +0000129 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
130 EISDIR, msg, f->f_name);
Neil Schemenauered19b882002-03-23 02:06:50 +0000131 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000132 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000133 return NULL;
134 }
135#endif
136 return f;
137}
138
Tim Peters59c9a642001-09-13 05:38:56 +0000139
140static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000141fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
142 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000144 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000145 assert(f != NULL);
146 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000147 assert(f->f_fp == NULL);
148
149 Py_DECREF(f->f_name);
150 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000151 Py_DECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000152 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000153
Neal Norwitzb337bb52006-07-17 00:55:45 +0000154 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000155 f->f_name = name;
156
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000157 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000158
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000159 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000160 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000161 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000162 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000163 f->f_univ_newline = (strchr(mode, 'U') != NULL);
164 f->f_newlinetypes = NEWLINE_UNKNOWN;
165 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000166 Py_INCREF(Py_None);
167 f->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +0000168 Py_INCREF(Py_None);
169 f->f_errors = Py_None;
Antoine Pitroubb445a12010-02-05 17:05:54 +0000170 f->readable = f->writable = 0;
171 if (strchr(mode, 'r') != NULL || f->f_univ_newline)
172 f->readable = 1;
173 if (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL)
174 f->writable = 1;
175 if (strchr(mode, '+') != NULL)
176 f->readable = f->writable = 1;
Tim Petersf1827cf2003-09-07 03:30:18 +0000177
Neal Norwitzb337bb52006-07-17 00:55:45 +0000178 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000181 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000185#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
186#define Py_VERIFY_WINNT
187/* The CRT on windows compiled with Visual Studio 2005 and higher may
188 * assert if given invalid mode strings. This is all fine and well
189 * in static languages like C where the mode string is typcially hard
190 * coded. But in Python, were we pass in the mode string from the user,
191 * we need to verify it first manually
192 */
193static int _PyVerify_Mode_WINNT(const char *mode)
194{
195 /* See if mode string is valid on Windows to avoid hard assertions */
196 /* remove leading spacese */
197 int singles = 0;
198 int pairs = 0;
199 int encoding = 0;
200 const char *s, *c;
201
202 while(*mode == ' ') /* strip initial spaces */
203 ++mode;
204 if (!strchr("rwa", *mode)) /* must start with one of these */
205 return 0;
206 while (*++mode) {
207 if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
208 continue;
209 s = "+TD"; /* each of this can appear only once */
210 c = strchr(s, *mode);
211 if (c) {
212 ptrdiff_t idx = s-c;
213 if (singles & (1<<idx))
214 return 0;
215 singles |= (1<<idx);
216 continue;
217 }
218 s = "btcnSR"; /* only one of each letter in the pairs allowed */
219 c = strchr(s, *mode);
220 if (c) {
221 ptrdiff_t idx = (s-c)/2;
222 if (pairs & (1<<idx))
223 return 0;
224 pairs |= (1<<idx);
225 continue;
226 }
227 if (*mode == ',') {
228 encoding = 1;
229 break;
230 }
231 return 0; /* found an invalid char */
232 }
233
234 if (encoding) {
235 char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
236 while (*mode == ' ')
237 ++mode;
238 /* find 'ccs =' */
239 if (strncmp(mode, "ccs", 3))
240 return 0;
241 mode += 3;
242 while (*mode == ' ')
243 ++mode;
244 if (*mode != '=')
245 return 0;
246 while (*mode == ' ')
247 ++mode;
248 for(encoding = 0; encoding<_countof(e); ++encoding) {
249 size_t l = strlen(e[encoding]);
250 if (!strncmp(mode, e[encoding], l)) {
251 mode += l; /* found a valid encoding */
252 break;
253 }
254 }
255 if (encoding == _countof(e))
256 return 0;
257 }
258 /* skip trailing spaces */
259 while (*mode == ' ')
260 ++mode;
261
262 return *mode == '\0'; /* must be at the end of the string */
263}
264#endif
265
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000266/* check for known incorrect mode strings - problem is, platforms are
267 free to accept any mode characters they like and are supposed to
268 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000269 universal newline support is expressly forbidden by PEP 278.
270 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000271 won't know what it is. Non-zero return signals an exception */
272int
273_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000274{
Georg Brandl7b90e162006-05-18 07:01:27 +0000275 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000276 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000277
Georg Brandl7b90e162006-05-18 07:01:27 +0000278 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000279 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000280 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000281 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000282
Georg Brandl7b90e162006-05-18 07:01:27 +0000283 upos = strchr(mode, 'U');
284 if (upos) {
285 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000286
Georg Brandl7b90e162006-05-18 07:01:27 +0000287 if (mode[0] == 'w' || mode[0] == 'a') {
288 PyErr_Format(PyExc_ValueError, "universal newline "
289 "mode can only be used with modes "
290 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000291 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000292 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000293
294 if (mode[0] != 'r') {
295 memmove(mode+1, mode, strlen(mode)+1);
296 mode[0] = 'r';
297 }
298
299 if (!strchr(mode, 'b')) {
300 memmove(mode+2, mode+1, strlen(mode));
301 mode[1] = 'b';
302 }
303 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
304 PyErr_Format(PyExc_ValueError, "mode string must begin with "
305 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000306 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000307 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000308#ifdef Py_VERIFY_WINNT
309 /* additional checks on NT with visual studio 2005 and higher */
310 if (!_PyVerify_Mode_WINNT(mode)) {
311 PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
312 return -1;
313 }
314#endif
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000315 return 0;
316}
317
Tim Peters59c9a642001-09-13 05:38:56 +0000318static PyObject *
319open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320{
Georg Brandl7b90e162006-05-18 07:01:27 +0000321 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000322 assert(f != NULL);
323 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000324#ifdef MS_WINDOWS
325 /* windows ignores the passed name in order to support Unicode */
326 assert(f->f_name != NULL);
327#else
Tim Peters59c9a642001-09-13 05:38:56 +0000328 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000329#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000330 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000331 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000332
Georg Brandl7b90e162006-05-18 07:01:27 +0000333 /* probably need to replace 'U' by 'rb' */
334 newmode = PyMem_MALLOC(strlen(mode) + 3);
335 if (!newmode) {
336 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000337 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000338 }
339 strcpy(newmode, mode);
340
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000341 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000342 f = NULL;
343 goto cleanup;
344 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000345
Tim Peters8fa45672001-09-13 21:01:29 +0000346 /* rexec.py can't stop a user from getting the file() constructor --
347 all they have to do is get *any* file object f, and then do
348 type(f). Here we prevent them from doing damage with it. */
349 if (PyEval_GetRestricted()) {
350 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000351 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000352 f = NULL;
353 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000354 }
Tim Petersa27a1502001-11-09 20:59:14 +0000355 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000356
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000357#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000358 if (PyUnicode_Check(f->f_name)) {
359 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000360 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000361 if (f->f_name && wmode) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000362 FILE_BEGIN_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000363 /* PyUnicode_AS_UNICODE OK without thread
364 lock as it is a simple dereference. */
365 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
366 PyUnicode_AS_UNICODE(wmode));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000367 FILE_END_ALLOW_THREADS(f)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000368 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000369 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000370 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000371#endif
372 if (NULL == f->f_fp && NULL != name) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000373 FILE_BEGIN_ALLOW_THREADS(f)
Georg Brandl7b90e162006-05-18 07:01:27 +0000374 f->f_fp = fopen(name, newmode);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000375 FILE_END_ALLOW_THREADS(f)
Skip Montanaro51ffac62004-06-11 04:49:03 +0000376 }
377
Guido van Rossuma08095a1991-02-13 23:25:27 +0000378 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000379#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000380 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
381 * across all Windows flavors. When it sets EINVAL varies
382 * across Windows flavors, the exact conditions aren't
383 * documented, and the answer lies in the OS's implementation
384 * of Win32's CreateFile function (whose source is secret).
385 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000386 * Starting with Visual Studio .NET 2005, EINVAL is correctly
387 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000388 */
389 if (errno == 0) /* bad mode string */
390 errno = EINVAL;
391 else if (errno == EINVAL) /* unknown, but not a mode string */
392 errno = ENOENT;
393#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000394 /* EINVAL is returned when an invalid filename or
395 * an invalid mode is supplied. */
Amaury Forgeot d'Arc17617a02008-09-25 20:52:56 +0000396 if (errno == EINVAL) {
397 PyObject *v;
398 char message[100];
399 PyOS_snprintf(message, 100,
400 "invalid mode ('%.50s') or filename", mode);
401 v = Py_BuildValue("(isO)", errno, message, f->f_name);
402 if (v != NULL) {
403 PyErr_SetObject(PyExc_IOError, v);
404 Py_DECREF(v);
405 }
406 }
Jeremy Hylton41c83212001-11-09 16:17:24 +0000407 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000408 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000409 f = NULL;
410 }
Tim Peters2ea91112002-04-08 04:13:12 +0000411 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000412 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000413
414cleanup:
415 PyMem_FREE(newmode);
416
Tim Peters59c9a642001-09-13 05:38:56 +0000417 return (PyObject *)f;
418}
419
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000420static PyObject *
421close_the_file(PyFileObject *f)
422{
423 int sts = 0;
424 int (*local_close)(FILE *);
425 FILE *local_fp = f->f_fp;
426 if (local_fp != NULL) {
427 local_close = f->f_close;
428 if (local_close != NULL && f->unlocked_count > 0) {
429 if (f->ob_refcnt > 0) {
430 PyErr_SetString(PyExc_IOError,
431 "close() called during concurrent "
432 "operation on the same file object.");
433 } else {
434 /* This should not happen unless someone is
435 * carelessly playing with the PyFileObject
436 * struct fields and/or its associated FILE
437 * pointer. */
438 PyErr_SetString(PyExc_SystemError,
439 "PyFileObject locking error in "
440 "destructor (refcnt <= 0 at close).");
441 }
442 return NULL;
443 }
444 /* NULL out the FILE pointer before releasing the GIL, because
445 * it will not be valid anymore after the close() function is
446 * called. */
447 f->f_fp = NULL;
448 if (local_close != NULL) {
449 Py_BEGIN_ALLOW_THREADS
450 errno = 0;
451 sts = (*local_close)(local_fp);
452 Py_END_ALLOW_THREADS
453 if (sts == EOF)
454 return PyErr_SetFromErrno(PyExc_IOError);
455 if (sts != 0)
456 return PyInt_FromLong((long)sts);
457 }
458 }
459 Py_RETURN_NONE;
460}
461
Tim Peters59c9a642001-09-13 05:38:56 +0000462PyObject *
463PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
464{
Tim Peters44410012001-09-14 03:26:08 +0000465 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
466 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000467 if (f != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000468 PyObject *o_name = PyString_FromString(name);
Neal Norwitzb337bb52006-07-17 00:55:45 +0000469 if (o_name == NULL)
470 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000471 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000472 Py_DECREF(f);
473 f = NULL;
474 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000475 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000476 }
477 return (PyObject *) f;
478}
479
480PyObject *
481PyFile_FromString(char *name, char *mode)
482{
483 extern int fclose(FILE *);
484 PyFileObject *f;
485
486 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
487 if (f != NULL) {
488 if (open_the_file(f, name, mode) == NULL) {
489 Py_DECREF(f);
490 f = NULL;
491 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000492 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000494}
495
Guido van Rossumb6775db1994-08-01 11:34:53 +0000496void
Fred Drakefd99de62000-07-09 05:02:18 +0000497PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000498{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000499 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000500 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000501 int type;
502 switch (bufsize) {
503 case 0:
504 type = _IONBF;
505 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000506#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000507 case 1:
508 type = _IOLBF;
509 bufsize = BUFSIZ;
510 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000511#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000512 default:
513 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000514#ifndef HAVE_SETVBUF
515 bufsize = BUFSIZ;
516#endif
517 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000518 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000519 fflush(file->f_fp);
520 if (type == _IONBF) {
521 PyMem_Free(file->f_setbuf);
522 file->f_setbuf = NULL;
523 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000524 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
525 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000526 }
527#ifdef HAVE_SETVBUF
528 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000529#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000530 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000531#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000532 }
533}
534
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000535/* Set the encoding used to output Unicode strings.
Martin v. Löwis99815892008-06-01 07:20:46 +0000536 Return 1 on success, 0 on failure. */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000537
538int
539PyFile_SetEncoding(PyObject *f, const char *enc)
540{
Martin v. Löwis99815892008-06-01 07:20:46 +0000541 return PyFile_SetEncodingAndErrors(f, enc, NULL);
542}
543
544int
545PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
546{
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000547 PyFileObject *file = (PyFileObject*)f;
Martin v. Löwis99815892008-06-01 07:20:46 +0000548 PyObject *str, *oerrors;
Thomas Woutersafea5292007-01-23 13:42:00 +0000549
550 assert(PyFile_Check(f));
Gregory P. Smith99a3dce2008-06-10 17:42:36 +0000551 str = PyString_FromString(enc);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000552 if (!str)
553 return 0;
Martin v. Löwis99815892008-06-01 07:20:46 +0000554 if (errors) {
555 oerrors = PyString_FromString(errors);
556 if (!oerrors) {
557 Py_DECREF(str);
558 return 0;
559 }
560 } else {
561 oerrors = Py_None;
562 Py_INCREF(Py_None);
563 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000564 Py_DECREF(file->f_encoding);
565 file->f_encoding = str;
Martin v. Löwis99815892008-06-01 07:20:46 +0000566 Py_DECREF(file->f_errors);
567 file->f_errors = oerrors;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000568 return 1;
569}
570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000572err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000573{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000575 return NULL;
576}
577
Antoine Pitroubb445a12010-02-05 17:05:54 +0000578static PyObject *
579err_mode(char *action)
580{
581 PyErr_Format(PyExc_IOError, "File not open for %s", action);
582 return NULL;
583}
584
Thomas Woutersc45251a2006-02-12 11:53:32 +0000585/* Refuse regular file I/O if there's data in the iteration-buffer.
586 * Mixing them would cause data to arrive out of order, as the read*
587 * methods don't use the iteration buffer. */
588static PyObject *
589err_iterbuffered(void)
590{
591 PyErr_SetString(PyExc_ValueError,
592 "Mixing iteration and read methods would lose data");
593 return NULL;
594}
595
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000596static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000597
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598/* Methods */
599
600static void
Fred Drakefd99de62000-07-09 05:02:18 +0000601file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000603 PyObject *ret;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000604 if (f->weakreflist != NULL)
605 PyObject_ClearWeakRefs((PyObject *) f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000606 ret = close_the_file(f);
607 if (!ret) {
608 PySys_WriteStderr("close failed in file object destructor:\n");
609 PyErr_Print();
610 }
611 else {
612 Py_DECREF(ret);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000613 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000614 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000615 Py_XDECREF(f->f_name);
616 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000617 Py_XDECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000618 Py_XDECREF(f->f_errors);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000619 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000620 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621}
622
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000624file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000625{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000626 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000627#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000628 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000629 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000630 const char *name_str = name ? PyString_AsString(name) : "?";
631 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000632 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000633 name_str,
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000634 PyString_AsString(f->f_mode),
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000635 f);
636 Py_XDECREF(name);
637 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000638#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000639 } else {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000640 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000641 f->f_fp == NULL ? "closed" : "open",
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000642 PyString_AsString(f->f_name),
643 PyString_AsString(f->f_mode),
Barry Warsaw7ce36942001-08-24 18:34:26 +0000644 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000645 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646}
647
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000648static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000649file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000650{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000651 PyObject *sts = close_the_file(f);
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000652 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000653 f->f_setbuf = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000654 return sts;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655}
656
Trent Mickf29f47b2000-08-11 19:02:59 +0000657
Guido van Rossumb8552162001-09-05 14:58:11 +0000658/* Our very own off_t-like type, 64-bit if possible */
659#if !defined(HAVE_LARGEFILE_SUPPORT)
660typedef off_t Py_off_t;
661#elif SIZEOF_OFF_T >= 8
662typedef off_t Py_off_t;
663#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000664typedef fpos_t Py_off_t;
665#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000666#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000667#endif
668
669
Trent Mickf29f47b2000-08-11 19:02:59 +0000670/* a portable fseek() function
671 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000672static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000673_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000674{
Guido van Rossumb8552162001-09-05 14:58:11 +0000675#if !defined(HAVE_LARGEFILE_SUPPORT)
676 return fseek(fp, offset, whence);
677#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000678 return fseeko(fp, offset, whence);
679#elif defined(HAVE_FSEEK64)
680 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000681#elif defined(__BEOS__)
682 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000683#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000684 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
685 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000686 fpos_t pos;
687 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000688 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000689#ifdef MS_WINDOWS
690 fflush(fp);
691 if (_lseeki64(fileno(fp), 0, 2) == -1)
692 return -1;
693#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000694 if (fseek(fp, 0, SEEK_END) != 0)
695 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000696#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000697 /* fall through */
698 case SEEK_CUR:
699 if (fgetpos(fp, &pos) != 0)
700 return -1;
701 offset += pos;
702 break;
703 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000704 }
705 return fsetpos(fp, &offset);
706#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000707#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000708#endif
709}
710
711
712/* a portable ftell() function
713 Return -1 on failure with errno set appropriately, current file
714 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000715static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000716_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000717{
Guido van Rossumb8552162001-09-05 14:58:11 +0000718#if !defined(HAVE_LARGEFILE_SUPPORT)
719 return ftell(fp);
720#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
721 return ftello(fp);
722#elif defined(HAVE_FTELL64)
723 return ftell64(fp);
724#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000725 fpos_t pos;
726 if (fgetpos(fp, &pos) != 0)
727 return -1;
728 return pos;
729#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000730#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000731#endif
732}
733
734
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000736file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000738 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000739 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000740 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000741 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000742
Guido van Rossumd7297e61992-07-06 14:19:26 +0000743 if (f->f_fp == NULL)
744 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000745 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000746 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000747 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000748 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000749 off_index = PyNumber_Index(offobj);
750 if (!off_index) {
751 if (!PyFloat_Check(offobj))
752 return NULL;
753 /* Deprecated in 2.6 */
754 PyErr_Clear();
Benjamin Petersonf19a7b92008-04-27 18:40:21 +0000755 if (PyErr_WarnEx(PyExc_DeprecationWarning,
756 "integer argument expected, got float",
757 1) < 0)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000758 return NULL;
759 off_index = offobj;
760 Py_INCREF(offobj);
761 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000762#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000763 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000764#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000765 offset = PyLong_Check(off_index) ?
766 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000767#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000768 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000769 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000770 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000771
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000772 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000773 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000774 ret = _portable_fseek(f->f_fp, offset, whence);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000775 FILE_END_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000776
Guido van Rossumff4949e1992-08-05 19:58:53 +0000777 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000779 clearerr(f->f_fp);
780 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000781 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000782 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783 Py_INCREF(Py_None);
784 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000785}
786
Trent Mickf29f47b2000-08-11 19:02:59 +0000787
Guido van Rossumd7047b31995-01-02 19:07:15 +0000788#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000790file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000791{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000792 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000793 PyObject *newsizeobj = NULL;
794 Py_off_t initialpos;
795 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000796
Guido van Rossumd7047b31995-01-02 19:07:15 +0000797 if (f->f_fp == NULL)
798 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +0000799 if (!f->writable)
800 return err_mode("writing");
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000801 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000802 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000803
Tim Petersf1827cf2003-09-07 03:30:18 +0000804 /* Get current file position. If the file happens to be open for
805 * update and the last operation was an input operation, C doesn't
806 * define what the later fflush() will do, but we promise truncate()
807 * won't change the current position (and fflush() *does* change it
808 * then at least on Windows). The easiest thing is to capture
809 * current pos now and seek back to it at the end.
810 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000811 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000812 errno = 0;
813 initialpos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000814 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000815 if (initialpos == -1)
816 goto onioerror;
817
Tim Petersfb05db22002-03-11 00:24:00 +0000818 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000819 * specified value.
820 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000821 if (newsizeobj != NULL) {
822#if !defined(HAVE_LARGEFILE_SUPPORT)
823 newsize = PyInt_AsLong(newsizeobj);
824#else
825 newsize = PyLong_Check(newsizeobj) ?
826 PyLong_AsLongLong(newsizeobj) :
827 PyInt_AsLong(newsizeobj);
828#endif
829 if (PyErr_Occurred())
830 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000831 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000832 else /* default to current position */
833 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000834
Tim Petersf1827cf2003-09-07 03:30:18 +0000835 /* Flush the stream. We're mixing stream-level I/O with lower-level
836 * I/O, and a flush may be necessary to synch both platform views
837 * of the current file state.
838 */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000839 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000840 errno = 0;
841 ret = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000842 FILE_END_ALLOW_THREADS(f)
Tim Petersfb05db22002-03-11 00:24:00 +0000843 if (ret != 0)
844 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000845
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000846#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000847 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000848 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000849 {
Tim Petersfb05db22002-03-11 00:24:00 +0000850 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000851
Tim Petersf1827cf2003-09-07 03:30:18 +0000852 /* Have to move current pos to desired endpoint on Windows. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000853 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000854 errno = 0;
855 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000856 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000857 if (ret)
858 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000859
Tim Peters8f01b682002-03-12 03:04:44 +0000860 /* Truncate. Note that this may grow the file! */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000861 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters8f01b682002-03-12 03:04:44 +0000862 errno = 0;
863 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000864 ret = hFile == (HANDLE)-1;
865 if (ret == 0) {
866 ret = SetEndOfFile(hFile) == 0;
867 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000868 errno = EACCES;
869 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000870 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000871 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000872 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000873 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000874#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000875 FILE_BEGIN_ALLOW_THREADS(f)
Trent Mickf29f47b2000-08-11 19:02:59 +0000876 errno = 0;
877 ret = ftruncate(fileno(f->f_fp), newsize);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000878 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000879 if (ret != 0)
880 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000881#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000882
Tim Petersf1827cf2003-09-07 03:30:18 +0000883 /* Restore original file position. */
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000884 FILE_BEGIN_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000885 errno = 0;
886 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000887 FILE_END_ALLOW_THREADS(f)
Tim Petersf1827cf2003-09-07 03:30:18 +0000888 if (ret)
889 goto onioerror;
890
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000891 Py_INCREF(Py_None);
892 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000893
894onioerror:
895 PyErr_SetFromErrno(PyExc_IOError);
896 clearerr(f->f_fp);
897 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000898}
899#endif /* HAVE_FTRUNCATE */
900
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000901static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000902file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000903{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000904 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000905
Guido van Rossumd7297e61992-07-06 14:19:26 +0000906 if (f->f_fp == NULL)
907 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000908 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000909 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000910 pos = _portable_ftell(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000911 FILE_END_ALLOW_THREADS(f)
912
Trent Mickf29f47b2000-08-11 19:02:59 +0000913 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000914 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000915 clearerr(f->f_fp);
916 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000917 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000918 if (f->f_skipnextlf) {
919 int c;
920 c = GETC(f->f_fp);
921 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000922 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000923 pos++;
924 f->f_skipnextlf = 0;
925 } else if (c != EOF) ungetc(c, f->f_fp);
926 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000927#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000928 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000929#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000930 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000931#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000932}
933
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000934static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000935file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000936{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000937 if (f->f_fp == NULL)
938 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000939 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000940}
941
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000942static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000943file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000944{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000945 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000946
Guido van Rossumd7297e61992-07-06 14:19:26 +0000947 if (f->f_fp == NULL)
948 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000949 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000950 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000951 res = fflush(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000952 FILE_END_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000953 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000955 clearerr(f->f_fp);
956 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000957 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000958 Py_INCREF(Py_None);
959 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000960}
961
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000962static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000963file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000964{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000965 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000966 if (f->f_fp == NULL)
967 return err_closed();
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000968 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumff4949e1992-08-05 19:58:53 +0000969 res = isatty((int)fileno(f->f_fp));
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000970 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000971 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000972}
973
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000974
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000975#if BUFSIZ < 8192
976#define SMALLCHUNK 8192
977#else
978#define SMALLCHUNK BUFSIZ
979#endif
980
Guido van Rossum3c259041999-01-14 19:00:14 +0000981#if SIZEOF_INT < 4
982#define BIGCHUNK (512 * 32)
983#else
984#define BIGCHUNK (512 * 1024)
985#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000986
987static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000988new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000989{
990#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000991 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000992 struct stat st;
993 if (fstat(fileno(f->f_fp), &st) == 0) {
994 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000995 /* The following is not a bug: we really need to call lseek()
996 *and* ftell(). The reason is that some stdio libraries
997 mistakenly flush their buffer when ftell() is called and
998 the lseek() call it makes fails, thereby throwing away
999 data that cannot be recovered in any way. To avoid this,
1000 we first test lseek(), and only call ftell() if lseek()
1001 works. We can't use the lseek() value either, because we
1002 need to take the amount of buffered data into account.
1003 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +00001004 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +00001005 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +00001006 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +00001007 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +00001008 if (pos < 0)
1009 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001010 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +00001011 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +00001012 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001013 }
1014#endif
1015 if (currentsize > SMALLCHUNK) {
1016 /* Keep doubling until we reach BIGCHUNK;
1017 then keep adding BIGCHUNK. */
1018 if (currentsize <= BIGCHUNK)
1019 return currentsize + currentsize;
1020 else
1021 return currentsize + BIGCHUNK;
1022 }
1023 return currentsize + SMALLCHUNK;
1024}
1025
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001026#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1027#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1028#else
1029#ifdef EWOULDBLOCK
1030#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1031#else
1032#ifdef EAGAIN
1033#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1034#else
1035#define BLOCKED_ERRNO(x) 0
1036#endif
1037#endif
1038#endif
1039
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001040static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001041file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001042{
Guido van Rossum789a1611997-05-10 22:33:55 +00001043 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001044 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001045 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +00001046
Guido van Rossumd7297e61992-07-06 14:19:26 +00001047 if (f->f_fp == NULL)
1048 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001049 if (!f->readable)
1050 return err_mode("reading");
Thomas Woutersc45251a2006-02-12 11:53:32 +00001051 /* refuse to mix with f.next() */
1052 if (f->f_buf != NULL &&
1053 (f->f_bufend - f->f_bufptr) > 0 &&
1054 f->f_buf[0] != '\0')
1055 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001056 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +00001057 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001058 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +00001059 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001060 else
1061 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001062 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001063 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001064 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001065 return NULL;
1066 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001067 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001068 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001069 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001070 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001071 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001072 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001073 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001074 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001075 buffersize - bytesread, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001076 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001077 if (chunksize == 0) {
1078 if (!ferror(f->f_fp))
1079 break;
Guido van Rossum6263d541997-05-10 22:07:25 +00001080 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001081 /* When in non-blocking mode, data shouldn't
1082 * be discarded if a blocking signal was
1083 * received. That will also happen if
1084 * chunksize != 0, but bytesread < buffersize. */
1085 if (bytesread > 0 && BLOCKED_ERRNO(errno))
1086 break;
1087 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +00001088 Py_DECREF(v);
1089 return NULL;
1090 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001091 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001092 if (bytesread < buffersize) {
1093 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001094 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001095 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001096 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +00001097 buffersize = new_buffersize(f, buffersize);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001098 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001099 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001100 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +00001101 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001102 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001103 }
1104 }
Benjamin Petersonbea424a2010-04-03 00:57:33 +00001105 if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
1106 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001107 return v;
1108}
1109
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001110static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001111file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001112{
1113 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114 Py_ssize_t ntodo;
1115 Py_ssize_t ndone, nnow;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001116 Py_buffer pbuf;
Tim Peters86821b22001-01-07 21:19:34 +00001117
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001118 if (f->f_fp == NULL)
1119 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001120 if (!f->readable)
1121 return err_mode("reading");
Thomas Woutersc45251a2006-02-12 11:53:32 +00001122 /* refuse to mix with f.next() */
1123 if (f->f_buf != NULL &&
1124 (f->f_bufend - f->f_bufptr) > 0 &&
1125 f->f_buf[0] != '\0')
1126 return err_iterbuffered();
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001127 if (!PyArg_ParseTuple(args, "w*", &pbuf))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001128 return NULL;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001129 ptr = pbuf.buf;
1130 ntodo = pbuf.len;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001131 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001132 while (ntodo > 0) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001133 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001134 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +00001135 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001136 (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001137 FILE_END_ALLOW_THREADS(f)
Guido van Rossum6263d541997-05-10 22:07:25 +00001138 if (nnow == 0) {
1139 if (!ferror(f->f_fp))
1140 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001141 PyErr_SetFromErrno(PyExc_IOError);
1142 clearerr(f->f_fp);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001143 PyBuffer_Release(&pbuf);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001144 return NULL;
1145 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001146 ndone += nnow;
1147 ntodo -= nnow;
1148 }
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001149 PyBuffer_Release(&pbuf);
Neal Norwitz076d1e02006-08-21 18:20:10 +00001150 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001151}
1152
Tim Peters86821b22001-01-07 21:19:34 +00001153/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +00001154Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +00001155
1156Under MSVC 6:
1157
Tim Peters1c733232001-01-08 04:02:07 +00001158+ MS threadsafe getc is very slow (multiple layers of function calls before+
1159 after each character, to lock+unlock the stream).
1160+ The stream-locking functions are MS-internal -- can't access them from user
1161 code.
1162+ There's nothing Tim could find in the MS C or platform SDK libraries that
1163 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +00001164+ MS fgets locks/unlocks only once per line; it's the only hook we have.
1165
1166So we use fgets for speed(!), despite that it's painful.
1167
1168MS realloc is also slow.
1169
Tim Petersf29b64d2001-01-15 06:33:19 +00001170Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1171have):
1172 Linux a wash
1173 Solaris a wash
1174 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +00001175
Tim Petersf29b64d2001-01-15 06:33:19 +00001176CAUTION: The C std isn't clear about this: in those cases where fgets
1177writes something into the buffer, can it write into any position beyond the
1178required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1179known on which it does; and it would be a strange way to code fgets. Still,
1180getline_via_fgets may not work correctly if it does. The std test
1181test_bufio.py should fail if platform fgets() routinely writes beyond the
1182trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +00001183**************************************************************************/
1184
Tim Petersf29b64d2001-01-15 06:33:19 +00001185/* Use this routine if told to, or by default on non-get_unlocked()
1186 * platforms unless told not to. Yikes! Let's spell that out:
1187 * On a platform with getc_unlocked():
1188 * By default, use getc_unlocked().
1189 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1190 * On a platform without getc_unlocked():
1191 * By default, use fgets().
1192 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1193 */
1194#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1195#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001196#endif
1197
Tim Petersf29b64d2001-01-15 06:33:19 +00001198#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1199#undef USE_FGETS_IN_GETLINE
1200#endif
1201
1202#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +00001203static PyObject*
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001204getline_via_fgets(PyFileObject *f, FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +00001205{
Tim Peters15b83852001-01-08 00:53:12 +00001206/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001207 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1208 * to fill this much of the buffer with a known value in order to figure out
1209 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1210 * than "most" lines, we waste time filling unused buffer slots. 100 is
1211 * surely adequate for most peoples' email archives, chewing over source code,
1212 * etc -- "regular old text files".
1213 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1214 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1215 * cautions about boosting that. 300 was chosen because the worst real-life
1216 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1217 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001218 */
Tim Peters142297a2001-01-15 10:36:56 +00001219#define INITBUFSIZE 100
1220#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001221 char* p; /* temp */
1222 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001223 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001224 char* pvfree; /* address of next free slot */
1225 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001226 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1227 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001228 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001229 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001230
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001231 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001232 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001233 */
Tim Peters142297a2001-01-15 10:36:56 +00001234 total_v_size = INITBUFSIZE; /* start small and pray */
1235 pvfree = buf;
1236 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001237 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters142297a2001-01-15 10:36:56 +00001238 pvend = buf + total_v_size;
1239 nfree = pvend - pvfree;
1240 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001241 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1242 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001243 FILE_END_ALLOW_THREADS(f)
Tim Peters15b83852001-01-08 00:53:12 +00001244
Tim Peters142297a2001-01-15 10:36:56 +00001245 if (p == NULL) {
1246 clearerr(fp);
1247 if (PyErr_CheckSignals())
1248 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001249 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001250 return v;
1251 }
Tim Peters142297a2001-01-15 10:36:56 +00001252 /* fgets read *something* */
1253 p = memchr(pvfree, '\n', nfree);
1254 if (p != NULL) {
1255 /* Did the \n come from fgets or from us?
1256 * Since fgets stops at the first \n, and then writes
1257 * \0, if it's from fgets a \0 must be next. But if
1258 * that's so, it could not have come from us, since
1259 * the \n's we filled the buffer with have only more
1260 * \n's to the right.
1261 */
1262 if (p+1 < pvend && *(p+1) == '\0') {
1263 /* It's from fgets: we win! In particular,
1264 * we haven't done any mallocs yet, and can
1265 * build the final result on the first try.
1266 */
1267 ++p; /* include \n from fgets */
1268 }
1269 else {
1270 /* Must be from us: fgets didn't fill the
1271 * buffer and didn't find a newline, so it
1272 * must be the last and newline-free line of
1273 * the file.
1274 */
1275 assert(p > pvfree && *(p-1) == '\0');
1276 --p; /* don't include \0 from fgets */
1277 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001278 v = PyString_FromStringAndSize(buf, p - buf);
Tim Peters142297a2001-01-15 10:36:56 +00001279 return v;
1280 }
1281 /* yuck: fgets overwrote all the newlines, i.e. the entire
1282 * buffer. So this line isn't over yet, or maybe it is but
1283 * we're exactly at EOF. If we haven't already, try using the
1284 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001285 */
Tim Peters142297a2001-01-15 10:36:56 +00001286 assert(*(pvend-1) == '\0');
1287 if (pvfree == buf) {
1288 pvfree = pvend - 1; /* overwrite trailing null */
1289 total_v_size = MAXBUFSIZE;
1290 }
1291 else
1292 break;
Tim Peters86821b22001-01-07 21:19:34 +00001293 }
Tim Peters142297a2001-01-15 10:36:56 +00001294
1295 /* The stack buffer isn't big enough; malloc a string object and read
1296 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001297 */
Tim Petersddea2082002-03-23 10:03:50 +00001298 total_v_size = MAXBUFSIZE << 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001299 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001300 if (v == NULL)
1301 return v;
1302 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001303 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1304 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001305
1306 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001307 * after setting p one beyond the end of the line. The code here is
1308 * very much like the code above, except reads into v's buffer; see
1309 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001310 */
1311 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001312 FILE_BEGIN_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001313 pvend = BUF(v) + total_v_size;
1314 nfree = pvend - pvfree;
1315 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001316 assert(nfree < INT_MAX);
1317 p = fgets(pvfree, (int)nfree, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001318 FILE_END_ALLOW_THREADS(f)
Tim Peters86821b22001-01-07 21:19:34 +00001319
1320 if (p == NULL) {
1321 clearerr(fp);
1322 if (PyErr_CheckSignals()) {
1323 Py_DECREF(v);
1324 return NULL;
1325 }
1326 p = pvfree;
1327 break;
1328 }
Tim Peters86821b22001-01-07 21:19:34 +00001329 p = memchr(pvfree, '\n', nfree);
1330 if (p != NULL) {
1331 if (p+1 < pvend && *(p+1) == '\0') {
1332 /* \n came from fgets */
1333 ++p;
1334 break;
1335 }
1336 /* \n came from us; last line of file, no newline */
1337 assert(p > pvfree && *(p-1) == '\0');
1338 --p;
1339 break;
1340 }
1341 /* expand buffer and try again */
1342 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001343 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001344 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001345 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001346 /* check for overflow */
1347 if (total_v_size <= prev_v_size ||
1348 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001349 PyErr_SetString(PyExc_OverflowError,
1350 "line is longer than a Python string can hold");
1351 Py_DECREF(v);
1352 return NULL;
1353 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001354 if (_PyString_Resize(&v, (int)total_v_size) < 0)
Tim Peters86821b22001-01-07 21:19:34 +00001355 return NULL;
1356 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001357 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001358 }
Benjamin Petersonbea424a2010-04-03 00:57:33 +00001359 if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
1360 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +00001361 return v;
1362#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001363#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001364}
Tim Petersf29b64d2001-01-15 06:33:19 +00001365#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001366
Guido van Rossum0bd24411991-04-04 15:21:57 +00001367/* Internal routine to get a line.
1368 Size argument interpretation:
1369 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001370 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001371*/
1372
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001374get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001375{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001376 FILE *fp = f->f_fp;
1377 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001378 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001379 size_t total_v_size; /* total # of slots in buffer */
1380 size_t used_v_size; /* # used slots in buffer */
1381 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001382 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001383 int newlinetypes = f->f_newlinetypes;
1384 int skipnextlf = f->f_skipnextlf;
1385 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001386
Jack Jansen7b8c7542002-04-14 20:12:41 +00001387#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001388 if (n <= 0 && !univ_newline )
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001389 return getline_via_fgets(f, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001390#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001391 total_v_size = n > 0 ? n : 100;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001392 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001393 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001394 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001395 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001396 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001397
Guido van Rossumce5ba841991-03-06 13:06:18 +00001398 for (;;) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001399 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001400 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001401 if (univ_newline) {
1402 c = 'x'; /* Shut up gcc warning */
1403 while ( buf != end && (c = GETC(fp)) != EOF ) {
1404 if (skipnextlf ) {
1405 skipnextlf = 0;
1406 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001407 /* Seeing a \n here with
1408 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001409 * saw a \r before.
1410 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001411 newlinetypes |= NEWLINE_CRLF;
1412 c = GETC(fp);
1413 if (c == EOF) break;
1414 } else {
1415 newlinetypes |= NEWLINE_CR;
1416 }
1417 }
1418 if (c == '\r') {
1419 skipnextlf = 1;
1420 c = '\n';
1421 } else if ( c == '\n')
1422 newlinetypes |= NEWLINE_LF;
1423 *buf++ = c;
1424 if (c == '\n') break;
1425 }
1426 if ( c == EOF && skipnextlf )
1427 newlinetypes |= NEWLINE_CR;
1428 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001429 while ((c = GETC(fp)) != EOF &&
1430 (*buf++ = c) != '\n' &&
1431 buf != end)
1432 ;
1433 FUNLOCKFILE(fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001434 FILE_END_ALLOW_THREADS(f)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001435 f->f_newlinetypes = newlinetypes;
1436 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001437 if (c == '\n')
1438 break;
1439 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001440 if (ferror(fp)) {
1441 PyErr_SetFromErrno(PyExc_IOError);
1442 clearerr(fp);
1443 Py_DECREF(v);
1444 return NULL;
1445 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001446 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001447 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001448 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001449 return NULL;
1450 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001451 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001452 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001453 /* Must be because buf == end */
1454 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001455 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001456 used_v_size = total_v_size;
1457 increment = total_v_size >> 2; /* mild exponential growth */
1458 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001459 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001460 PyErr_SetString(PyExc_OverflowError,
1461 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001462 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001463 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001464 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001465 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001466 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001467 buf = BUF(v) + used_v_size;
1468 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001469 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001470
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001471 used_v_size = buf - BUF(v);
Benjamin Petersonbea424a2010-04-03 00:57:33 +00001472 if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
1473 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001474 return v;
1475}
1476
Guido van Rossum0bd24411991-04-04 15:21:57 +00001477/* External C interface */
1478
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001479PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001480PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001481{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001482 PyObject *result;
1483
Guido van Rossum3165fe61992-09-25 21:59:05 +00001484 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001485 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001486 return NULL;
1487 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001488
1489 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001490 PyFileObject *fo = (PyFileObject *)f;
1491 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001492 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001493 if (!fo->readable)
1494 return err_mode("reading");
Thomas Woutersc45251a2006-02-12 11:53:32 +00001495 /* refuse to mix with f.next() */
1496 if (fo->f_buf != NULL &&
1497 (fo->f_bufend - fo->f_bufptr) > 0 &&
1498 fo->f_buf[0] != '\0')
1499 return err_iterbuffered();
1500 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001501 }
1502 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001503 PyObject *reader;
1504 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001505
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001506 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001507 if (reader == NULL)
1508 return NULL;
1509 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001510 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001511 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001512 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001513 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001514 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001515 return NULL;
1516 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001517 result = PyEval_CallObject(reader, args);
1518 Py_DECREF(reader);
1519 Py_DECREF(args);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001520 if (result != NULL && !PyString_Check(result) &&
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001521 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001522 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001523 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001524 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001525 "object.readline() returned non-string");
1526 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001527 }
1528
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001529 if (n < 0 && result != NULL && PyString_Check(result)) {
1530 char *s = PyString_AS_STRING(result);
1531 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001532 if (len == 0) {
1533 Py_DECREF(result);
1534 result = NULL;
1535 PyErr_SetString(PyExc_EOFError,
1536 "EOF when reading a line");
1537 }
1538 else if (s[len-1] == '\n') {
Benjamin Petersonbea424a2010-04-03 00:57:33 +00001539 if (result->ob_refcnt == 1) {
1540 if (_PyString_Resize(&result, len-1))
1541 return NULL;
1542 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001543 else {
1544 PyObject *v;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001545 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001546 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001547 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001548 }
1549 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001550 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001551#ifdef Py_USING_UNICODE
1552 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1553 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001554 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001555 if (len == 0) {
1556 Py_DECREF(result);
1557 result = NULL;
1558 PyErr_SetString(PyExc_EOFError,
1559 "EOF when reading a line");
1560 }
1561 else if (s[len-1] == '\n') {
1562 if (result->ob_refcnt == 1)
1563 PyUnicode_Resize(&result, len-1);
1564 else {
1565 PyObject *v;
1566 v = PyUnicode_FromUnicode(s, len-1);
1567 Py_DECREF(result);
1568 result = v;
1569 }
1570 }
1571 }
1572#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001573 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001574}
1575
1576/* Python method */
1577
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001578static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001579file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001580{
Guido van Rossum789a1611997-05-10 22:33:55 +00001581 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001582
Guido van Rossumd7297e61992-07-06 14:19:26 +00001583 if (f->f_fp == NULL)
1584 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001585 if (!f->readable)
1586 return err_mode("reading");
Thomas Woutersc45251a2006-02-12 11:53:32 +00001587 /* refuse to mix with f.next() */
1588 if (f->f_buf != NULL &&
1589 (f->f_bufend - f->f_bufptr) > 0 &&
1590 f->f_buf[0] != '\0')
1591 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001592 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001593 return NULL;
1594 if (n == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001595 return PyString_FromString("");
Guido van Rossum789a1611997-05-10 22:33:55 +00001596 if (n < 0)
1597 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001598 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001599}
1600
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001601static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001602file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001603{
Guido van Rossum789a1611997-05-10 22:33:55 +00001604 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001605 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001606 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001607 char small_buffer[SMALLCHUNK];
1608 char *buffer = small_buffer;
1609 size_t buffersize = SMALLCHUNK;
1610 PyObject *big_buffer = NULL;
1611 size_t nfilled = 0;
1612 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001613 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001614 char *p, *q, *end;
1615 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001616 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001617
Guido van Rossumd7297e61992-07-06 14:19:26 +00001618 if (f->f_fp == NULL)
1619 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001620 if (!f->readable)
1621 return err_mode("reading");
Thomas Woutersc45251a2006-02-12 11:53:32 +00001622 /* refuse to mix with f.next() */
1623 if (f->f_buf != NULL &&
1624 (f->f_bufend - f->f_bufptr) > 0 &&
1625 f->f_buf[0] != '\0')
1626 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001627 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001628 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001629 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001630 return NULL;
1631 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001632 if (shortread)
1633 nread = 0;
1634 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001635 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001636 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001637 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001638 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001639 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001640 shortread = (nread < buffersize-nfilled);
1641 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001642 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001643 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001644 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001645 break;
1646 PyErr_SetFromErrno(PyExc_IOError);
1647 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001648 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001649 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001650 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001651 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001652 if (p == NULL) {
1653 /* Need a larger buffer to fit this line */
1654 nfilled += nread;
1655 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001656 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001657 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001658 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001659 goto error;
1660 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001661 if (big_buffer == NULL) {
1662 /* Create the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001663 big_buffer = PyString_FromStringAndSize(
Guido van Rossum6263d541997-05-10 22:07:25 +00001664 NULL, buffersize);
1665 if (big_buffer == NULL)
1666 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001667 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001668 memcpy(buffer, small_buffer, nfilled);
1669 }
1670 else {
1671 /* Grow the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001672 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
Jack Jansen7b8c7542002-04-14 20:12:41 +00001673 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001674 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001675 }
1676 continue;
1677 }
1678 end = buffer+nfilled+nread;
1679 q = buffer;
1680 do {
1681 /* Process complete lines */
1682 p++;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001683 line = PyString_FromStringAndSize(q, p-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001684 if (line == NULL)
1685 goto error;
1686 err = PyList_Append(list, line);
1687 Py_DECREF(line);
1688 if (err != 0)
1689 goto error;
1690 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001691 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001692 } while (p != NULL);
1693 /* Move the remaining incomplete line to the start */
1694 nfilled = end-q;
1695 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001696 if (sizehint > 0)
1697 if (totalread >= (size_t)sizehint)
1698 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001699 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001700 if (nfilled != 0) {
1701 /* Partial last line */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001702 line = PyString_FromStringAndSize(buffer, nfilled);
Guido van Rossum6263d541997-05-10 22:07:25 +00001703 if (line == NULL)
1704 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001705 if (sizehint > 0) {
1706 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001707 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001708 if (rest == NULL) {
1709 Py_DECREF(line);
1710 goto error;
1711 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001712 PyString_Concat(&line, rest);
Guido van Rossum789a1611997-05-10 22:33:55 +00001713 Py_DECREF(rest);
1714 if (line == NULL)
1715 goto error;
1716 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001717 err = PyList_Append(list, line);
1718 Py_DECREF(line);
1719 if (err != 0)
1720 goto error;
1721 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001722
1723cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001724 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001725 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001726
1727error:
1728 Py_CLEAR(list);
1729 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001730}
1731
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001732static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001733file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001734{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001735 Py_buffer pbuf;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001736 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001737 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001738 if (f->f_fp == NULL)
1739 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001740 if (!f->writable)
1741 return err_mode("writing");
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001742 if (f->f_binary) {
1743 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1744 return NULL;
1745 s = pbuf.buf;
1746 n = pbuf.len;
1747 } else
1748 if (!PyArg_ParseTuple(args, "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001749 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001750 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001751 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001752 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001753 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001754 FILE_END_ALLOW_THREADS(f)
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001755 if (f->f_binary)
1756 PyBuffer_Release(&pbuf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001757 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001758 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001759 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001760 return NULL;
1761 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001762 Py_INCREF(Py_None);
1763 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001764}
1765
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001766static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001767file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001768{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001769#define CHUNKSIZE 1000
1770 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001771 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001772 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001773 int index, islist;
1774 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001775
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001776 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001777 if (f->f_fp == NULL)
1778 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001779 if (!f->writable)
1780 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001781
1782 result = NULL;
1783 list = NULL;
1784 islist = PyList_Check(seq);
1785 if (islist)
1786 it = NULL;
1787 else {
1788 it = PyObject_GetIter(seq);
1789 if (it == NULL) {
1790 PyErr_SetString(PyExc_TypeError,
1791 "writelines() requires an iterable argument");
1792 return NULL;
1793 }
1794 /* From here on, fail by going to error, to reclaim "it". */
1795 list = PyList_New(CHUNKSIZE);
1796 if (list == NULL)
1797 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001798 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001799
1800 /* Strategy: slurp CHUNKSIZE lines into a private list,
1801 checking that they are all strings, then write that list
1802 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001803 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001804 if (islist) {
1805 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001806 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001807 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001808 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001809 j = PyList_GET_SIZE(list);
1810 }
1811 else {
1812 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001813 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001814 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001815 if (PyErr_Occurred())
1816 goto error;
1817 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001818 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001819 PyList_SetItem(list, j, line);
1820 }
1821 }
1822 if (j == 0)
1823 break;
1824
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001825 /* Check that all entries are indeed strings. If not,
1826 apply the same rules as for file.write() and
1827 convert the results to strings. This is slow, but
1828 seems to be the only way since all conversion APIs
1829 could potentially execute Python code. */
1830 for (i = 0; i < j; i++) {
1831 PyObject *v = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001832 if (!PyString_Check(v)) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001833 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001834 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001835 PyObject_AsReadBuffer(v,
1836 (const void**)&buffer,
1837 &len)) ||
1838 PyObject_AsCharBuffer(v,
1839 &buffer,
1840 &len))) {
1841 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001842 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001843 goto error;
1844 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001845 line = PyString_FromStringAndSize(buffer,
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001846 len);
1847 if (line == NULL)
1848 goto error;
1849 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001850 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001851 }
1852 }
1853
1854 /* Since we are releasing the global lock, the
1855 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001856 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001857 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001858 errno = 0;
1859 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001860 line = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001861 len = PyString_GET_SIZE(line);
1862 nwritten = fwrite(PyString_AS_STRING(line),
Guido van Rossumee70ad12000-03-13 16:27:06 +00001863 1, len, f->f_fp);
1864 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001865 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001866 PyErr_SetFromErrno(PyExc_IOError);
1867 clearerr(f->f_fp);
1868 goto error;
1869 }
1870 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001871 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001872
1873 if (j < CHUNKSIZE)
1874 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001875 }
1876
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001877 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001878 result = Py_None;
1879 error:
1880 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001881 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001882 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001883#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001884}
1885
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001886static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001887file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001888{
1889 if (f->f_fp == NULL)
1890 return err_closed();
1891 Py_INCREF(f);
1892 return (PyObject *)f;
1893}
1894
Georg Brandl98b40ad2006-06-08 14:50:21 +00001895static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001896file_xreadlines(PyFileObject *f)
1897{
1898 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1899 "try 'for line in f' instead", 1) < 0)
1900 return NULL;
1901 return file_self(f);
1902}
1903
1904static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001905file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001906{
Georg Brandlad61bc82008-02-23 15:11:18 +00001907 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001908 if (!ret)
1909 /* If error occurred, pass through */
1910 return NULL;
1911 Py_DECREF(ret);
1912 /* We cannot return the result of close since a true
1913 * value will be interpreted as "yes, swallow the
1914 * exception if one was raised inside the with block". */
1915 Py_RETURN_NONE;
1916}
1917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001918PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001919"readline([size]) -> next line from the file, as a string.\n"
1920"\n"
1921"Retain newline. A non-negative size argument limits the maximum\n"
1922"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001923"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001925PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001926"read([size]) -> read at most size bytes, returned as a string.\n"
1927"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001928"If the size argument is negative or omitted, read until EOF is reached.\n"
1929"Notice that when in non-blocking mode, less data than what was requested\n"
1930"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001932PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001933"write(str) -> None. Write string str to file.\n"
1934"\n"
1935"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001936"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001938PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001939"fileno() -> integer \"file descriptor\".\n"
1940"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001941"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001943PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001944"seek(offset[, whence]) -> None. Move to new file position.\n"
1945"\n"
1946"Argument offset is a byte count. Optional argument whence defaults to\n"
1947"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1948"(move relative to current position, positive or negative), and 2 (move\n"
1949"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001950"seeking beyond the end of a file). If the file is opened in text mode,\n"
1951"only offsets returned by tell() are legal. Use of other offsets causes\n"
1952"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001953"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001954"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001955
Guido van Rossumd7047b31995-01-02 19:07:15 +00001956#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001957PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001958"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1959"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001960"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001961#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001963PyDoc_STRVAR(tell_doc,
1964"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001966PyDoc_STRVAR(readinto_doc,
1967"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001968
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001969PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001970"readlines([size]) -> list of strings, each a line from the file.\n"
1971"\n"
1972"Call readline() repeatedly and return a list of the lines so read.\n"
1973"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001974"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001975
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001976PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001977"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001978"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001979"For backward compatibility. File objects now include the performance\n"
1980"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001981
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001982PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001983"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001984"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001985"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001987
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001988PyDoc_STRVAR(flush_doc,
1989"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001990
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001991PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001992"close() -> None or (perhaps) an integer. Close the file.\n"
1993"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001994"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001995"further I/O operations. close() may be called more than once without\n"
1996"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001999PyDoc_STRVAR(isatty_doc,
2000"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00002001
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002002PyDoc_STRVAR(enter_doc,
2003 "__enter__() -> self.");
2004
Georg Brandl98b40ad2006-06-08 14:50:21 +00002005PyDoc_STRVAR(exit_doc,
2006 "__exit__(*excinfo) -> None. Closes the file.");
2007
Tim Petersefc3a3a2001-09-20 07:55:22 +00002008static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00002009 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2010 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2011 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2012 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2013 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002014#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00002015 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002016#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00002017 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2018 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
Georg Brandla9916b52008-05-17 22:11:54 +00002019 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2020 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2021 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00002022 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2023 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2024 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002025 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00002026 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00002027 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002028};
2029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002031
Guido van Rossum6f799372001-09-20 20:46:19 +00002032static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00002033 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00002034 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00002035 {"name", T_OBJECT, OFF(f_name), RO,
2036 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002037 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2038 "file encoding"},
Martin v. Löwis99815892008-06-01 07:20:46 +00002039 {"errors", T_OBJECT, OFF(f_errors), RO,
2040 "Unicode error handler"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00002041 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002042 {NULL} /* Sentinel */
2043};
2044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002045static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002047{
Guido van Rossum77f6a652002-04-03 22:41:51 +00002048 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002049}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002050static PyObject *
2051get_newlines(PyFileObject *f, void *closure)
2052{
2053 switch (f->f_newlinetypes) {
2054 case NEWLINE_UNKNOWN:
2055 Py_INCREF(Py_None);
2056 return Py_None;
2057 case NEWLINE_CR:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002058 return PyString_FromString("\r");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002059 case NEWLINE_LF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002060 return PyString_FromString("\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002061 case NEWLINE_CR|NEWLINE_LF:
2062 return Py_BuildValue("(ss)", "\r", "\n");
2063 case NEWLINE_CRLF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002064 return PyString_FromString("\r\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002065 case NEWLINE_CR|NEWLINE_CRLF:
2066 return Py_BuildValue("(ss)", "\r", "\r\n");
2067 case NEWLINE_LF|NEWLINE_CRLF:
2068 return Py_BuildValue("(ss)", "\n", "\r\n");
2069 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2070 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2071 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00002072 PyErr_Format(PyExc_SystemError,
2073 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00002074 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00002075 return NULL;
2076 }
2077}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002078
Georg Brandl65bb42d2008-03-21 20:38:24 +00002079static PyObject *
2080get_softspace(PyFileObject *f, void *closure)
2081{
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002082 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002083 return NULL;
2084 return PyInt_FromLong(f->f_softspace);
2085}
2086
2087static int
2088set_softspace(PyFileObject *f, PyObject *value)
2089{
2090 int new;
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002091 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002092 return -1;
2093
2094 if (value == NULL) {
2095 PyErr_SetString(PyExc_TypeError,
2096 "can't delete softspace attribute");
2097 return -1;
2098 }
2099
2100 new = PyInt_AsLong(value);
2101 if (new == -1 && PyErr_Occurred())
2102 return -1;
2103 f->f_softspace = new;
2104 return 0;
2105}
2106
Guido van Rossum32d34c82001-09-20 21:45:26 +00002107static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00002108 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00002109 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00002110 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00002111 {"softspace", (getter)get_softspace, (setter)set_softspace,
2112 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 {0},
2114};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002115
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002116static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002117drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002118{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002119 if (f->f_buf != NULL) {
2120 PyMem_Free(f->f_buf);
2121 f->f_buf = NULL;
2122 }
Guido van Rossum65967252001-04-21 13:20:18 +00002123}
2124
Tim Petersf1827cf2003-09-07 03:30:18 +00002125/* Make sure that file has a readahead buffer with at least one byte
2126 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002127 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002128static int
2129readahead(PyFileObject *f, int bufsize)
2130{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002131 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002132
2133 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00002134 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002135 return 0;
2136 else
2137 drop_readahead(f);
2138 }
Anthony Baxter377be112006-04-11 06:54:30 +00002139 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00002140 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002141 return -1;
2142 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002143 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002144 errno = 0;
2145 chunksize = Py_UniversalNewlineFread(
2146 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002147 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002148 if (chunksize == 0) {
2149 if (ferror(f->f_fp)) {
2150 PyErr_SetFromErrno(PyExc_IOError);
2151 clearerr(f->f_fp);
2152 drop_readahead(f);
2153 return -1;
2154 }
2155 }
2156 f->f_bufptr = f->f_buf;
2157 f->f_bufend = f->f_buf + chunksize;
2158 return 0;
2159}
2160
2161/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002162 uninitialized bytes followed by the remainder of the line. Don't be
2163 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002164 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2165
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002166static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002167readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2168{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002169 PyStringObject* s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002170 char *bufptr;
2171 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002172 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002173
2174 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002175 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002176 return NULL;
2177
2178 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002179 if (len == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002180 return (PyStringObject *)
2181 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002182 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002183 if (bufptr != NULL) {
2184 bufptr++; /* Count the '\n' */
2185 len = bufptr - f->f_bufptr;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002186 s = (PyStringObject *)
2187 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002188 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002189 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002190 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002191 f->f_bufptr = bufptr;
2192 if (bufptr == f->f_bufend)
2193 drop_readahead(f);
2194 } else {
2195 bufptr = f->f_bufptr;
2196 buf = f->f_buf;
2197 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002198 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002199 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002200 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002201 if (s == NULL) {
2202 PyMem_Free(buf);
2203 return NULL;
2204 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002205 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002206 PyMem_Free(buf);
2207 }
2208 return s;
2209}
2210
2211/* A larger buffer size may actually decrease performance. */
2212#define READAHEAD_BUFSIZE 8192
2213
2214static PyObject *
2215file_iternext(PyFileObject *f)
2216{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002217 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002218
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002219 if (f->f_fp == NULL)
2220 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00002221 if (!f->readable)
2222 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002223
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002224 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002225 if (l == NULL || PyString_GET_SIZE(l) == 0) {
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002226 Py_XDECREF(l);
2227 return NULL;
2228 }
2229 return (PyObject *)l;
2230}
2231
2232
Tim Peters59c9a642001-09-13 05:38:56 +00002233static PyObject *
2234file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2235{
Tim Peters44410012001-09-14 03:26:08 +00002236 PyObject *self;
2237 static PyObject *not_yet_string;
2238
2239 assert(type != NULL && type->tp_alloc != NULL);
2240
2241 if (not_yet_string == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002242 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002243 if (not_yet_string == NULL)
2244 return NULL;
2245 }
2246
2247 self = type->tp_alloc(type, 0);
2248 if (self != NULL) {
2249 /* Always fill in the name and mode, so that nobody else
2250 needs to special-case NULLs there. */
2251 Py_INCREF(not_yet_string);
2252 ((PyFileObject *)self)->f_name = not_yet_string;
2253 Py_INCREF(not_yet_string);
2254 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002255 Py_INCREF(Py_None);
2256 ((PyFileObject *)self)->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +00002257 Py_INCREF(Py_None);
2258 ((PyFileObject *)self)->f_errors = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002259 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002260 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002261 }
2262 return self;
2263}
2264
2265static int
2266file_init(PyObject *self, PyObject *args, PyObject *kwds)
2267{
2268 PyFileObject *foself = (PyFileObject *)self;
2269 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002270 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002271 char *name = NULL;
2272 char *mode = "r";
2273 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002274 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002275#ifdef MS_WINDOWS
Hirokazu Yamamotoa3c56092009-06-28 10:23:00 +00002276 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002277#endif
Tim Peters44410012001-09-14 03:26:08 +00002278
2279 assert(PyFile_Check(self));
2280 if (foself->f_fp != NULL) {
2281 /* Have to close the existing file first. */
2282 PyObject *closeresult = file_close(foself);
2283 if (closeresult == NULL)
2284 return -1;
2285 Py_DECREF(closeresult);
2286 }
Tim Peters59c9a642001-09-13 05:38:56 +00002287
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002288#ifdef MS_WINDOWS
Hirokazu Yamamotoa3c56092009-06-28 10:23:00 +00002289 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2290 kwlist, &po, &mode, &bufsize)) {
2291 wideargument = 1;
2292 if (fill_file_fields(foself, NULL, po, mode,
2293 fclose) == NULL)
2294 goto Error;
2295 } else {
2296 /* Drop the argument parsing error as narrow
2297 strings are also valid. */
2298 PyErr_Clear();
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002299 }
2300#endif
2301
2302 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002303 PyObject *o_name;
2304
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002305 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2306 Py_FileSystemDefaultEncoding,
2307 &name,
2308 &mode, &bufsize))
2309 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002310
2311 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002312 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2313 kwlist, &o_name, &mode,
2314 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002315 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002316
2317 if (fill_file_fields(foself, NULL, o_name, mode,
2318 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002319 goto Error;
2320 }
Tim Peters44410012001-09-14 03:26:08 +00002321 if (open_the_file(foself, name, mode) == NULL)
2322 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002323 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002324 PyFile_SetBufSize(self, bufsize);
2325 goto Done;
2326
2327Error:
2328 ret = -1;
2329 /* fall through */
2330Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002331 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002332 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002333}
2334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002335PyDoc_VAR(file_doc) =
2336PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002337"file(name[, mode[, buffering]]) -> file object\n"
2338"\n"
2339"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2340"writing or appending. The file will be created if it doesn't exist\n"
2341"when opened for writing or appending; it will be truncated when\n"
2342"opened for writing. Add a 'b' to the mode for binary files.\n"
2343"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2344"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002345"buffered, and larger numbers specify the buffer size. The preferred way\n"
2346"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002347)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002348PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002349"Add a 'U' to mode to open the file for input with universal newline\n"
2350"support. Any line ending in the input file will be seen as a '\\n'\n"
2351"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2352"the value for this attribute is one of None (no newline read yet),\n"
2353"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2354"\n"
2355"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002356);
Tim Peters59c9a642001-09-13 05:38:56 +00002357
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002358PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002359 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002360 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002361 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002362 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002363 (destructor)file_dealloc, /* tp_dealloc */
2364 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365 0, /* tp_getattr */
2366 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002367 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002368 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002369 0, /* tp_as_number */
2370 0, /* tp_as_sequence */
2371 0, /* tp_as_mapping */
2372 0, /* tp_hash */
2373 0, /* tp_call */
2374 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002376 /* softspace is writable: we must supply tp_setattro */
2377 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002378 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002379 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002380 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 0, /* tp_traverse */
2382 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002383 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002384 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002385 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002386 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387 file_methods, /* tp_methods */
2388 file_memberlist, /* tp_members */
2389 file_getsetlist, /* tp_getset */
2390 0, /* tp_base */
2391 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002392 0, /* tp_descr_get */
2393 0, /* tp_descr_set */
2394 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002395 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002396 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002397 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002398 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002399};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002400
2401/* Interface for the 'soft space' between print items. */
2402
2403int
Fred Drakefd99de62000-07-09 05:02:18 +00002404PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002405{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002406 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002407 if (f == NULL) {
2408 /* Do nothing */
2409 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002410 else if (PyFile_Check(f)) {
2411 oldflag = ((PyFileObject *)f)->f_softspace;
2412 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002413 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002414 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002415 PyObject *v;
2416 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002417 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002418 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002419 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002420 if (PyInt_Check(v))
2421 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002422 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002423 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002424 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002425 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002426 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002427 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002428 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002429 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2430 PyErr_Clear();
2431 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002432 }
2433 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002434 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002435}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002436
2437/* Interfaces to write objects/strings to file-like objects */
2438
2439int
Fred Drakefd99de62000-07-09 05:02:18 +00002440PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002441{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002442 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002443 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002444 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002445 return -1;
2446 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002447 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002448 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002449#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002450 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002451 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002452#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002453 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002454 err_closed();
2455 return -1;
2456 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002457#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002458 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002459 PyUnicode_Check(v) && enc != Py_None) {
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002460 char *cenc = PyString_AS_STRING(enc);
Martin v. Löwis99815892008-06-01 07:20:46 +00002461 char *errors = fobj->f_errors == Py_None ?
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002462 "strict" : PyString_AS_STRING(fobj->f_errors);
Martin v. Löwis99815892008-06-01 07:20:46 +00002463 value = PyUnicode_AsEncodedString(v, cenc, errors);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002464 if (value == NULL)
2465 return -1;
2466 } else {
2467 value = v;
2468 Py_INCREF(value);
2469 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002470 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002471 Py_DECREF(value);
2472 return result;
2473#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002474 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002475#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002476 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002477 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002478 if (writer == NULL)
2479 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002480 if (flags & Py_PRINT_RAW) {
2481 if (PyUnicode_Check(v)) {
2482 value = v;
2483 Py_INCREF(value);
2484 } else
2485 value = PyObject_Str(v);
2486 }
2487 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002488 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002489 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002490 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002491 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002492 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002493 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002494 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002495 Py_DECREF(value);
2496 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002497 return -1;
2498 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002499 result = PyEval_CallObject(writer, args);
2500 Py_DECREF(args);
2501 Py_DECREF(value);
2502 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002503 if (result == NULL)
2504 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002505 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002506 return 0;
2507}
2508
Guido van Rossum27a60b11997-05-22 22:25:11 +00002509int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002510PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002511{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002512
Guido van Rossum3165fe61992-09-25 21:59:05 +00002513 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002514 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002515 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002516 PyErr_SetString(PyExc_SystemError,
2517 "null file for PyFile_WriteString");
2518 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002519 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002520 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002521 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002522 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002523 if (fp == NULL) {
2524 err_closed();
2525 return -1;
2526 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002527 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002528 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002529 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002530 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002531 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002532 else if (!PyErr_Occurred()) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002533 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002534 int err;
2535 if (v == NULL)
2536 return -1;
2537 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2538 Py_DECREF(v);
2539 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002540 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002541 else
2542 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002543}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002544
2545/* Try to get a file-descriptor from a Python object. If the object
2546 is an integer or long integer, its value is returned. If not, the
2547 object's fileno() method is called if it exists; the method must return
2548 an integer or long integer, which is returned as the file descriptor value.
2549 -1 is returned on failure.
2550*/
2551
2552int PyObject_AsFileDescriptor(PyObject *o)
2553{
2554 int fd;
2555 PyObject *meth;
2556
2557 if (PyInt_Check(o)) {
2558 fd = PyInt_AsLong(o);
2559 }
2560 else if (PyLong_Check(o)) {
2561 fd = PyLong_AsLong(o);
2562 }
2563 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2564 {
2565 PyObject *fno = PyEval_CallObject(meth, NULL);
2566 Py_DECREF(meth);
2567 if (fno == NULL)
2568 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002569
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002570 if (PyInt_Check(fno)) {
2571 fd = PyInt_AsLong(fno);
2572 Py_DECREF(fno);
2573 }
2574 else if (PyLong_Check(fno)) {
2575 fd = PyLong_AsLong(fno);
2576 Py_DECREF(fno);
2577 }
2578 else {
2579 PyErr_SetString(PyExc_TypeError,
2580 "fileno() returned a non-integer");
2581 Py_DECREF(fno);
2582 return -1;
2583 }
2584 }
2585 else {
2586 PyErr_SetString(PyExc_TypeError,
2587 "argument must be an int, or have a fileno() method.");
2588 return -1;
2589 }
2590
2591 if (fd < 0) {
2592 PyErr_Format(PyExc_ValueError,
2593 "file descriptor cannot be a negative integer (%i)",
2594 fd);
2595 return -1;
2596 }
2597 return fd;
2598}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002599
Jack Jansen7b8c7542002-04-14 20:12:41 +00002600/* From here on we need access to the real fgets and fread */
2601#undef fgets
2602#undef fread
2603
2604/*
2605** Py_UniversalNewlineFgets is an fgets variation that understands
2606** all of \r, \n and \r\n conventions.
2607** The stream should be opened in binary mode.
2608** If fobj is NULL the routine always does newline conversion, and
2609** it may peek one char ahead to gobble the second char in \r\n.
2610** If fobj is non-NULL it must be a PyFileObject. In this case there
2611** is no readahead but in stead a flag is used to skip a following
2612** \n on the next read. Also, if the file is open in binary mode
2613** the whole conversion is skipped. Finally, the routine keeps track of
2614** the different types of newlines seen.
2615** Note that we need no error handling: fgets() treats error and eof
2616** identically.
2617*/
2618char *
2619Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2620{
2621 char *p = buf;
2622 int c;
2623 int newlinetypes = 0;
2624 int skipnextlf = 0;
2625 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002626
Jack Jansen7b8c7542002-04-14 20:12:41 +00002627 if (fobj) {
2628 if (!PyFile_Check(fobj)) {
2629 errno = ENXIO; /* What can you do... */
2630 return NULL;
2631 }
2632 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2633 if ( !univ_newline )
2634 return fgets(buf, n, stream);
2635 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2636 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2637 }
2638 FLOCKFILE(stream);
2639 c = 'x'; /* Shut up gcc warning */
2640 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2641 if (skipnextlf ) {
2642 skipnextlf = 0;
2643 if (c == '\n') {
2644 /* Seeing a \n here with skipnextlf true
2645 ** means we saw a \r before.
2646 */
2647 newlinetypes |= NEWLINE_CRLF;
2648 c = GETC(stream);
2649 if (c == EOF) break;
2650 } else {
2651 /*
2652 ** Note that c == EOF also brings us here,
2653 ** so we're okay if the last char in the file
2654 ** is a CR.
2655 */
2656 newlinetypes |= NEWLINE_CR;
2657 }
2658 }
2659 if (c == '\r') {
2660 /* A \r is translated into a \n, and we skip
2661 ** an adjacent \n, if any. We don't set the
2662 ** newlinetypes flag until we've seen the next char.
2663 */
2664 skipnextlf = 1;
2665 c = '\n';
2666 } else if ( c == '\n') {
2667 newlinetypes |= NEWLINE_LF;
2668 }
2669 *p++ = c;
2670 if (c == '\n') break;
2671 }
2672 if ( c == EOF && skipnextlf )
2673 newlinetypes |= NEWLINE_CR;
2674 FUNLOCKFILE(stream);
2675 *p = '\0';
2676 if (fobj) {
2677 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2678 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2679 } else if ( skipnextlf ) {
2680 /* If we have no file object we cannot save the
2681 ** skipnextlf flag. We have to readahead, which
2682 ** will cause a pause if we're reading from an
2683 ** interactive stream, but that is very unlikely
2684 ** unless we're doing something silly like
2685 ** execfile("/dev/tty").
2686 */
2687 c = GETC(stream);
2688 if ( c != '\n' )
2689 ungetc(c, stream);
2690 }
2691 if (p == buf)
2692 return NULL;
2693 return buf;
2694}
2695
2696/*
2697** Py_UniversalNewlineFread is an fread variation that understands
2698** all of \r, \n and \r\n conventions.
2699** The stream should be opened in binary mode.
2700** fobj must be a PyFileObject. In this case there
2701** is no readahead but in stead a flag is used to skip a following
2702** \n on the next read. Also, if the file is open in binary mode
2703** the whole conversion is skipped. Finally, the routine keeps track of
2704** the different types of newlines seen.
2705*/
2706size_t
Tim Peters058b1412002-04-21 07:29:14 +00002707Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002708 FILE *stream, PyObject *fobj)
2709{
Tim Peters058b1412002-04-21 07:29:14 +00002710 char *dst = buf;
2711 PyFileObject *f = (PyFileObject *)fobj;
2712 int newlinetypes, skipnextlf;
2713
2714 assert(buf != NULL);
2715 assert(stream != NULL);
2716
Jack Jansen7b8c7542002-04-14 20:12:41 +00002717 if (!fobj || !PyFile_Check(fobj)) {
2718 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002719 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002720 }
Tim Peters058b1412002-04-21 07:29:14 +00002721 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002722 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002723 newlinetypes = f->f_newlinetypes;
2724 skipnextlf = f->f_skipnextlf;
2725 /* Invariant: n is the number of bytes remaining to be filled
2726 * in the buffer.
2727 */
2728 while (n) {
2729 size_t nread;
2730 int shortread;
2731 char *src = dst;
2732
2733 nread = fread(dst, 1, n, stream);
2734 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002735 if (nread == 0)
2736 break;
2737
Tim Peterse1682a82002-04-21 18:15:20 +00002738 n -= nread; /* assuming 1 byte out for each in; will adjust */
2739 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002740 while (nread--) {
2741 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002742 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002743 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002744 *dst++ = '\n';
2745 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002746 }
2747 else if (skipnextlf && c == '\n') {
2748 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002749 skipnextlf = 0;
2750 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002751 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002752 }
2753 else {
2754 /* Normal char to be stored in buffer. Also
2755 * update the newlinetypes flag if either this
2756 * is an LF or the previous char was a CR.
2757 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002758 if (c == '\n')
2759 newlinetypes |= NEWLINE_LF;
2760 else if (skipnextlf)
2761 newlinetypes |= NEWLINE_CR;
2762 *dst++ = c;
2763 skipnextlf = 0;
2764 }
2765 }
Tim Peters058b1412002-04-21 07:29:14 +00002766 if (shortread) {
2767 /* If this is EOF, update type flags. */
2768 if (skipnextlf && feof(stream))
2769 newlinetypes |= NEWLINE_CR;
2770 break;
2771 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002772 }
Tim Peters058b1412002-04-21 07:29:14 +00002773 f->f_newlinetypes = newlinetypes;
2774 f->f_skipnextlf = skipnextlf;
2775 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002776}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002777
2778#ifdef __cplusplus
2779}
2780#endif