blob: 6456368bf20438fdb087f7e54c2427525b0374be [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Andrew MacIntyrec4874392002-02-26 11:36:35 +000019#if defined(PYOS_OS2) && defined(PYCC_GCC)
20#include <io.h>
21#endif
22
Gregory P. Smithdd96db62008-06-09 04:58:54 +000023#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000024
Guido van Rossumff7e83d1999-08-27 20:39:37 +000025#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000026#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000027#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028
Jack Jansen7b8c7542002-04-14 20:12:41 +000029#ifdef HAVE_GETC_UNLOCKED
30#define GETC(f) getc_unlocked(f)
31#define FLOCKFILE(f) flockfile(f)
32#define FUNLOCKFILE(f) funlockfile(f)
33#else
34#define GETC(f) getc(f)
35#define FLOCKFILE(f)
36#define FUNLOCKFILE(f)
37#endif
38
Jack Jansen7b8c7542002-04-14 20:12:41 +000039/* Bits in f_newlinetypes */
40#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
41#define NEWLINE_CR 1 /* \r newline seen */
42#define NEWLINE_LF 2 /* \n newline seen */
43#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000044
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000045/*
46 * These macros release the GIL while preventing the f_close() function being
47 * called in the interval between them. For that purpose, a running total of
48 * the number of currently running unlocked code sections is kept in
49 * the unlocked_count field of the PyFileObject. The close() method raises
50 * an IOError if that field is non-zero. See issue #815646, #595601.
51 */
52
53#define FILE_BEGIN_ALLOW_THREADS(fobj) \
54{ \
55 fobj->unlocked_count++; \
56 Py_BEGIN_ALLOW_THREADS
57
58#define FILE_END_ALLOW_THREADS(fobj) \
59 Py_END_ALLOW_THREADS \
60 fobj->unlocked_count--; \
61 assert(fobj->unlocked_count >= 0); \
62}
63
64#define FILE_ABORT_ALLOW_THREADS(fobj) \
65 Py_BLOCK_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0);
68
Anthony Baxterac6bd462006-04-13 02:06:09 +000069#ifdef __cplusplus
70extern "C" {
71#endif
72
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000074PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000078 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080}
81
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +000082void PyFile_IncUseCount(PyFileObject *fobj)
83{
84 fobj->unlocked_count++;
85}
86
87void PyFile_DecUseCount(PyFileObject *fobj)
88{
89 fobj->unlocked_count--;
90 assert(fobj->unlocked_count >= 0);
91}
92
Guido van Rossumc0b618a1997-05-02 03:12:38 +000093PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000094PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000095{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000097 return NULL;
98 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +0000100}
101
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +0000102/* This is a safe wrapper around PyObject_Print to print to the FILE
103 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
104 about PyFileObject. */
105static int
106file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
107{
108 int result;
109 PyFile_IncUseCount(f);
110 result = PyObject_Print(op, f->f_fp, flags);
111 PyFile_DecUseCount(f);
112 return result;
113}
114
Neil Schemenauered19b882002-03-23 02:06:50 +0000115/* On Unix, fopen will succeed for directories.
116 In Python, there should be no file objects referring to
117 directories, so we need a check. */
118
119static PyFileObject*
120dircheck(PyFileObject* f)
121{
122#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
123 struct stat buf;
124 if (f->f_fp == NULL)
125 return f;
126 if (fstat(fileno(f->f_fp), &buf) == 0 &&
127 S_ISDIR(buf.st_mode)) {
Neil Schemenauered19b882002-03-23 02:06:50 +0000128 char *msg = strerror(EISDIR);
Benjamin Petersonfe231b02008-12-29 17:47:42 +0000129 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
130 EISDIR, msg, f->f_name);
Neil Schemenauered19b882002-03-23 02:06:50 +0000131 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000132 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000133 return NULL;
134 }
135#endif
136 return f;
137}
138
Tim Peters59c9a642001-09-13 05:38:56 +0000139
140static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000141fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
142 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000144 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000145 assert(f != NULL);
146 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000147 assert(f->f_fp == NULL);
148
149 Py_DECREF(f->f_name);
150 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000151 Py_DECREF(f->f_encoding);
Martin v. Löwis99815892008-06-01 07:20:46 +0000152 Py_DECREF(f->f_errors);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000153
Neal Norwitzb337bb52006-07-17 00:55:45 +0000154 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000155 f->f_name = name;
156
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000157 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000158
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000159 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000160 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000161 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000162 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000163 f->f_univ_newline = (strchr(mode, 'U') != NULL);
164 f->f_newlinetypes = NEWLINE_UNKNOWN;
165 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000166 Py_INCREF(Py_None);
167 f->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +0000168 Py_INCREF(Py_None);
169 f->f_errors = Py_None;
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 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +00001105 if (bytesread != buffersize)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001106 _PyString_Resize(&v, bytesread);
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 }
1359 if (BUF(v) + total_v_size != p)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001360 _PyString_Resize(&v, p - BUF(v));
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);
1472 if (used_v_size != total_v_size)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001473 _PyString_Resize(&v, used_v_size);
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') {
1539 if (result->ob_refcnt == 1)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001540 _PyString_Resize(&result, len-1);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001541 else {
1542 PyObject *v;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001543 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001544 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001545 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001546 }
1547 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001548 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001549#ifdef Py_USING_UNICODE
1550 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1551 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001552 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001553 if (len == 0) {
1554 Py_DECREF(result);
1555 result = NULL;
1556 PyErr_SetString(PyExc_EOFError,
1557 "EOF when reading a line");
1558 }
1559 else if (s[len-1] == '\n') {
1560 if (result->ob_refcnt == 1)
1561 PyUnicode_Resize(&result, len-1);
1562 else {
1563 PyObject *v;
1564 v = PyUnicode_FromUnicode(s, len-1);
1565 Py_DECREF(result);
1566 result = v;
1567 }
1568 }
1569 }
1570#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001571 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001572}
1573
1574/* Python method */
1575
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001576static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001577file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001578{
Guido van Rossum789a1611997-05-10 22:33:55 +00001579 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001580
Guido van Rossumd7297e61992-07-06 14:19:26 +00001581 if (f->f_fp == NULL)
1582 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001583 if (!f->readable)
1584 return err_mode("reading");
Thomas Woutersc45251a2006-02-12 11:53:32 +00001585 /* refuse to mix with f.next() */
1586 if (f->f_buf != NULL &&
1587 (f->f_bufend - f->f_bufptr) > 0 &&
1588 f->f_buf[0] != '\0')
1589 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001590 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001591 return NULL;
1592 if (n == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001593 return PyString_FromString("");
Guido van Rossum789a1611997-05-10 22:33:55 +00001594 if (n < 0)
1595 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001596 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001597}
1598
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001599static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001600file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001601{
Guido van Rossum789a1611997-05-10 22:33:55 +00001602 long sizehint = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001603 PyObject *list = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001604 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001605 char small_buffer[SMALLCHUNK];
1606 char *buffer = small_buffer;
1607 size_t buffersize = SMALLCHUNK;
1608 PyObject *big_buffer = NULL;
1609 size_t nfilled = 0;
1610 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001611 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001612 char *p, *q, *end;
1613 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001614 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001615
Guido van Rossumd7297e61992-07-06 14:19:26 +00001616 if (f->f_fp == NULL)
1617 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001618 if (!f->readable)
1619 return err_mode("reading");
Thomas Woutersc45251a2006-02-12 11:53:32 +00001620 /* refuse to mix with f.next() */
1621 if (f->f_buf != NULL &&
1622 (f->f_bufend - f->f_bufptr) > 0 &&
1623 f->f_buf[0] != '\0')
1624 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001625 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001626 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001627 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001628 return NULL;
1629 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001630 if (shortread)
1631 nread = 0;
1632 else {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001633 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001634 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001635 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001636 buffersize-nfilled, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001637 FILE_END_ALLOW_THREADS(f)
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001638 shortread = (nread < buffersize-nfilled);
1639 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001640 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001641 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001642 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001643 break;
1644 PyErr_SetFromErrno(PyExc_IOError);
1645 clearerr(f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001646 goto error;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001647 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001648 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001649 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001650 if (p == NULL) {
1651 /* Need a larger buffer to fit this line */
1652 nfilled += nread;
1653 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001654 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001655 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001656 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001657 goto error;
1658 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001659 if (big_buffer == NULL) {
1660 /* Create the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001661 big_buffer = PyString_FromStringAndSize(
Guido van Rossum6263d541997-05-10 22:07:25 +00001662 NULL, buffersize);
1663 if (big_buffer == NULL)
1664 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001665 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001666 memcpy(buffer, small_buffer, nfilled);
1667 }
1668 else {
1669 /* Grow the big buffer */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001670 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
Jack Jansen7b8c7542002-04-14 20:12:41 +00001671 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001672 buffer = PyString_AS_STRING(big_buffer);
Guido van Rossum6263d541997-05-10 22:07:25 +00001673 }
1674 continue;
1675 }
1676 end = buffer+nfilled+nread;
1677 q = buffer;
1678 do {
1679 /* Process complete lines */
1680 p++;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001681 line = PyString_FromStringAndSize(q, p-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001682 if (line == NULL)
1683 goto error;
1684 err = PyList_Append(list, line);
1685 Py_DECREF(line);
1686 if (err != 0)
1687 goto error;
1688 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001689 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001690 } while (p != NULL);
1691 /* Move the remaining incomplete line to the start */
1692 nfilled = end-q;
1693 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001694 if (sizehint > 0)
1695 if (totalread >= (size_t)sizehint)
1696 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001697 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001698 if (nfilled != 0) {
1699 /* Partial last line */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001700 line = PyString_FromStringAndSize(buffer, nfilled);
Guido van Rossum6263d541997-05-10 22:07:25 +00001701 if (line == NULL)
1702 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001703 if (sizehint > 0) {
1704 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001705 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001706 if (rest == NULL) {
1707 Py_DECREF(line);
1708 goto error;
1709 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001710 PyString_Concat(&line, rest);
Guido van Rossum789a1611997-05-10 22:33:55 +00001711 Py_DECREF(rest);
1712 if (line == NULL)
1713 goto error;
1714 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001715 err = PyList_Append(list, line);
1716 Py_DECREF(line);
1717 if (err != 0)
1718 goto error;
1719 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001720
1721cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001722 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001723 return list;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001724
1725error:
1726 Py_CLEAR(list);
1727 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001728}
1729
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001730static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001731file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001732{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001733 Py_buffer pbuf;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001734 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001735 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001736 if (f->f_fp == NULL)
1737 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001738 if (!f->writable)
1739 return err_mode("writing");
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001740 if (f->f_binary) {
1741 if (!PyArg_ParseTuple(args, "s*", &pbuf))
1742 return NULL;
1743 s = pbuf.buf;
1744 n = pbuf.len;
1745 } else
1746 if (!PyArg_ParseTuple(args, "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001747 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001748 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001749 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001751 n2 = fwrite(s, 1, n, f->f_fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001752 FILE_END_ALLOW_THREADS(f)
Martin v. Löwisf91d46a2008-08-12 14:49:50 +00001753 if (f->f_binary)
1754 PyBuffer_Release(&pbuf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001755 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001756 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001757 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001758 return NULL;
1759 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001760 Py_INCREF(Py_None);
1761 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001762}
1763
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001764static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001765file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001766{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001767#define CHUNKSIZE 1000
1768 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001769 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001770 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001771 int index, islist;
1772 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001773
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001774 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001775 if (f->f_fp == NULL)
1776 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00001777 if (!f->writable)
1778 return err_mode("writing");
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001779
1780 result = NULL;
1781 list = NULL;
1782 islist = PyList_Check(seq);
1783 if (islist)
1784 it = NULL;
1785 else {
1786 it = PyObject_GetIter(seq);
1787 if (it == NULL) {
1788 PyErr_SetString(PyExc_TypeError,
1789 "writelines() requires an iterable argument");
1790 return NULL;
1791 }
1792 /* From here on, fail by going to error, to reclaim "it". */
1793 list = PyList_New(CHUNKSIZE);
1794 if (list == NULL)
1795 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001796 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001797
1798 /* Strategy: slurp CHUNKSIZE lines into a private list,
1799 checking that they are all strings, then write that list
1800 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001801 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001802 if (islist) {
1803 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001804 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001805 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001806 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001807 j = PyList_GET_SIZE(list);
1808 }
1809 else {
1810 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001811 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001812 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001813 if (PyErr_Occurred())
1814 goto error;
1815 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001816 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001817 PyList_SetItem(list, j, line);
1818 }
1819 }
1820 if (j == 0)
1821 break;
1822
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001823 /* Check that all entries are indeed strings. If not,
1824 apply the same rules as for file.write() and
1825 convert the results to strings. This is slow, but
1826 seems to be the only way since all conversion APIs
1827 could potentially execute Python code. */
1828 for (i = 0; i < j; i++) {
1829 PyObject *v = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001830 if (!PyString_Check(v)) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001831 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001832 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001833 PyObject_AsReadBuffer(v,
1834 (const void**)&buffer,
1835 &len)) ||
1836 PyObject_AsCharBuffer(v,
1837 &buffer,
1838 &len))) {
1839 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001840 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001841 goto error;
1842 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001843 line = PyString_FromStringAndSize(buffer,
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001844 len);
1845 if (line == NULL)
1846 goto error;
1847 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001848 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001849 }
1850 }
1851
1852 /* Since we are releasing the global lock, the
1853 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001854 f->f_softspace = 0;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001855 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001856 errno = 0;
1857 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001858 line = PyList_GET_ITEM(list, i);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001859 len = PyString_GET_SIZE(line);
1860 nwritten = fwrite(PyString_AS_STRING(line),
Guido van Rossumee70ad12000-03-13 16:27:06 +00001861 1, len, f->f_fp);
1862 if (nwritten != len) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001863 FILE_ABORT_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001864 PyErr_SetFromErrno(PyExc_IOError);
1865 clearerr(f->f_fp);
1866 goto error;
1867 }
1868 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00001869 FILE_END_ALLOW_THREADS(f)
Guido van Rossumee70ad12000-03-13 16:27:06 +00001870
1871 if (j < CHUNKSIZE)
1872 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001873 }
1874
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001875 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001876 result = Py_None;
1877 error:
1878 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001879 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001880 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001881#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001882}
1883
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001884static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001885file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001886{
1887 if (f->f_fp == NULL)
1888 return err_closed();
1889 Py_INCREF(f);
1890 return (PyObject *)f;
1891}
1892
Georg Brandl98b40ad2006-06-08 14:50:21 +00001893static PyObject *
Georg Brandla9916b52008-05-17 22:11:54 +00001894file_xreadlines(PyFileObject *f)
1895{
1896 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1897 "try 'for line in f' instead", 1) < 0)
1898 return NULL;
1899 return file_self(f);
1900}
1901
1902static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001903file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001904{
Georg Brandlad61bc82008-02-23 15:11:18 +00001905 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001906 if (!ret)
1907 /* If error occurred, pass through */
1908 return NULL;
1909 Py_DECREF(ret);
1910 /* We cannot return the result of close since a true
1911 * value will be interpreted as "yes, swallow the
1912 * exception if one was raised inside the with block". */
1913 Py_RETURN_NONE;
1914}
1915
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001916PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001917"readline([size]) -> next line from the file, as a string.\n"
1918"\n"
1919"Retain newline. A non-negative size argument limits the maximum\n"
1920"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001921"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001923PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001924"read([size]) -> read at most size bytes, returned as a string.\n"
1925"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001926"If the size argument is negative or omitted, read until EOF is reached.\n"
1927"Notice that when in non-blocking mode, less data than what was requested\n"
1928"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001930PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001931"write(str) -> None. Write string str to file.\n"
1932"\n"
1933"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001934"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001936PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001937"fileno() -> integer \"file descriptor\".\n"
1938"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001939"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001940
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001941PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001942"seek(offset[, whence]) -> None. Move to new file position.\n"
1943"\n"
1944"Argument offset is a byte count. Optional argument whence defaults to\n"
1945"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1946"(move relative to current position, positive or negative), and 2 (move\n"
1947"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001948"seeking beyond the end of a file). If the file is opened in text mode,\n"
1949"only offsets returned by tell() are legal. Use of other offsets causes\n"
1950"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001951"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001952"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001953
Guido van Rossumd7047b31995-01-02 19:07:15 +00001954#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001955PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001956"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1957"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001958"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001959#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001960
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001961PyDoc_STRVAR(tell_doc,
1962"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001963
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001964PyDoc_STRVAR(readinto_doc,
1965"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001968"readlines([size]) -> list of strings, each a line from the file.\n"
1969"\n"
1970"Call readline() repeatedly and return a list of the lines so read.\n"
1971"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001972"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001973
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001974PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001975"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001976"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001977"For backward compatibility. File objects now include the performance\n"
1978"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001979
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001980PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001981"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001982"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001983"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001984"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986PyDoc_STRVAR(flush_doc,
1987"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001989PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001990"close() -> None or (perhaps) an integer. Close the file.\n"
1991"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001992"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001993"further I/O operations. close() may be called more than once without\n"
1994"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001995"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997PyDoc_STRVAR(isatty_doc,
1998"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001999
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002000PyDoc_STRVAR(enter_doc,
2001 "__enter__() -> self.");
2002
Georg Brandl98b40ad2006-06-08 14:50:21 +00002003PyDoc_STRVAR(exit_doc,
2004 "__exit__(*excinfo) -> None. Closes the file.");
2005
Tim Petersefc3a3a2001-09-20 07:55:22 +00002006static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00002007 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
2008 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
2009 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
2010 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
2011 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002012#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00002013 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00002014#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00002015 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
2016 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
Georg Brandla9916b52008-05-17 22:11:54 +00002017 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
2018 {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
2019 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00002020 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
2021 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
2022 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002023 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00002024 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00002025 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002026};
2027
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002028#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00002029
Guido van Rossum6f799372001-09-20 20:46:19 +00002030static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00002031 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00002032 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00002033 {"name", T_OBJECT, OFF(f_name), RO,
2034 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002035 {"encoding", T_OBJECT, OFF(f_encoding), RO,
2036 "file encoding"},
Martin v. Löwis99815892008-06-01 07:20:46 +00002037 {"errors", T_OBJECT, OFF(f_errors), RO,
2038 "Unicode error handler"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00002039 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00002040 {NULL} /* Sentinel */
2041};
2042
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002045{
Guido van Rossum77f6a652002-04-03 22:41:51 +00002046 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00002047}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002048static PyObject *
2049get_newlines(PyFileObject *f, void *closure)
2050{
2051 switch (f->f_newlinetypes) {
2052 case NEWLINE_UNKNOWN:
2053 Py_INCREF(Py_None);
2054 return Py_None;
2055 case NEWLINE_CR:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002056 return PyString_FromString("\r");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002057 case NEWLINE_LF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002058 return PyString_FromString("\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002059 case NEWLINE_CR|NEWLINE_LF:
2060 return Py_BuildValue("(ss)", "\r", "\n");
2061 case NEWLINE_CRLF:
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002062 return PyString_FromString("\r\n");
Jack Jansen7b8c7542002-04-14 20:12:41 +00002063 case NEWLINE_CR|NEWLINE_CRLF:
2064 return Py_BuildValue("(ss)", "\r", "\r\n");
2065 case NEWLINE_LF|NEWLINE_CRLF:
2066 return Py_BuildValue("(ss)", "\n", "\r\n");
2067 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
2068 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2069 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00002070 PyErr_Format(PyExc_SystemError,
2071 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00002072 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00002073 return NULL;
2074 }
2075}
Guido van Rossumb6775db1994-08-01 11:34:53 +00002076
Georg Brandl65bb42d2008-03-21 20:38:24 +00002077static PyObject *
2078get_softspace(PyFileObject *f, void *closure)
2079{
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002080 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002081 return NULL;
2082 return PyInt_FromLong(f->f_softspace);
2083}
2084
2085static int
2086set_softspace(PyFileObject *f, PyObject *value)
2087{
2088 int new;
Benjamin Peterson9f4f4812008-04-27 03:01:45 +00002089 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
Georg Brandl65bb42d2008-03-21 20:38:24 +00002090 return -1;
2091
2092 if (value == NULL) {
2093 PyErr_SetString(PyExc_TypeError,
2094 "can't delete softspace attribute");
2095 return -1;
2096 }
2097
2098 new = PyInt_AsLong(value);
2099 if (new == -1 && PyErr_Occurred())
2100 return -1;
2101 f->f_softspace = new;
2102 return 0;
2103}
2104
Guido van Rossum32d34c82001-09-20 21:45:26 +00002105static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00002106 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00002107 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00002108 "end-of-line convention used in this file"},
Georg Brandl65bb42d2008-03-21 20:38:24 +00002109 {"softspace", (getter)get_softspace, (setter)set_softspace,
2110 "flag indicating that a space needs to be printed; used by print"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 {0},
2112};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002113
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002114static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002115drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00002116{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002117 if (f->f_buf != NULL) {
2118 PyMem_Free(f->f_buf);
2119 f->f_buf = NULL;
2120 }
Guido van Rossum65967252001-04-21 13:20:18 +00002121}
2122
Tim Petersf1827cf2003-09-07 03:30:18 +00002123/* Make sure that file has a readahead buffer with at least one byte
2124 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00002125 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002126static int
2127readahead(PyFileObject *f, int bufsize)
2128{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002129 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002130
2131 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00002132 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002133 return 0;
2134 else
2135 drop_readahead(f);
2136 }
Anthony Baxter377be112006-04-11 06:54:30 +00002137 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00002138 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002139 return -1;
2140 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002141 FILE_BEGIN_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002142 errno = 0;
2143 chunksize = Py_UniversalNewlineFread(
2144 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002145 FILE_END_ALLOW_THREADS(f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002146 if (chunksize == 0) {
2147 if (ferror(f->f_fp)) {
2148 PyErr_SetFromErrno(PyExc_IOError);
2149 clearerr(f->f_fp);
2150 drop_readahead(f);
2151 return -1;
2152 }
2153 }
2154 f->f_bufptr = f->f_buf;
2155 f->f_bufend = f->f_buf + chunksize;
2156 return 0;
2157}
2158
2159/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00002160 uninitialized bytes followed by the remainder of the line. Don't be
2161 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002162 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2163
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002164static PyStringObject *
Neal Norwitzd8b995f2002-08-06 21:50:54 +00002165readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
2166{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002167 PyStringObject* s;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002168 char *bufptr;
2169 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002170 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002171
2172 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00002173 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002174 return NULL;
2175
2176 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00002177 if (len == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002178 return (PyStringObject *)
2179 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00002180 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002181 if (bufptr != NULL) {
2182 bufptr++; /* Count the '\n' */
2183 len = bufptr - f->f_bufptr;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002184 s = (PyStringObject *)
2185 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00002186 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002187 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002188 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002189 f->f_bufptr = bufptr;
2190 if (bufptr == f->f_bufend)
2191 drop_readahead(f);
2192 } else {
2193 bufptr = f->f_bufptr;
2194 buf = f->f_buf;
2195 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002196 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002197 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00002198 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002199 if (s == NULL) {
2200 PyMem_Free(buf);
2201 return NULL;
2202 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002203 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002204 PyMem_Free(buf);
2205 }
2206 return s;
2207}
2208
2209/* A larger buffer size may actually decrease performance. */
2210#define READAHEAD_BUFSIZE 8192
2211
2212static PyObject *
2213file_iternext(PyFileObject *f)
2214{
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002215 PyStringObject* l;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002216
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002217 if (f->f_fp == NULL)
2218 return err_closed();
Antoine Pitroubb445a12010-02-05 17:05:54 +00002219 if (!f->readable)
2220 return err_mode("reading");
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002221
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002222 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002223 if (l == NULL || PyString_GET_SIZE(l) == 0) {
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002224 Py_XDECREF(l);
2225 return NULL;
2226 }
2227 return (PyObject *)l;
2228}
2229
2230
Tim Peters59c9a642001-09-13 05:38:56 +00002231static PyObject *
2232file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2233{
Tim Peters44410012001-09-14 03:26:08 +00002234 PyObject *self;
2235 static PyObject *not_yet_string;
2236
2237 assert(type != NULL && type->tp_alloc != NULL);
2238
2239 if (not_yet_string == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002240 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00002241 if (not_yet_string == NULL)
2242 return NULL;
2243 }
2244
2245 self = type->tp_alloc(type, 0);
2246 if (self != NULL) {
2247 /* Always fill in the name and mode, so that nobody else
2248 needs to special-case NULLs there. */
2249 Py_INCREF(not_yet_string);
2250 ((PyFileObject *)self)->f_name = not_yet_string;
2251 Py_INCREF(not_yet_string);
2252 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002253 Py_INCREF(Py_None);
2254 ((PyFileObject *)self)->f_encoding = Py_None;
Martin v. Löwis99815892008-06-01 07:20:46 +00002255 Py_INCREF(Py_None);
2256 ((PyFileObject *)self)->f_errors = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002257 ((PyFileObject *)self)->weakreflist = NULL;
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002258 ((PyFileObject *)self)->unlocked_count = 0;
Tim Peters44410012001-09-14 03:26:08 +00002259 }
2260 return self;
2261}
2262
2263static int
2264file_init(PyObject *self, PyObject *args, PyObject *kwds)
2265{
2266 PyFileObject *foself = (PyFileObject *)self;
2267 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002268 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00002269 char *name = NULL;
2270 char *mode = "r";
2271 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002272 int wideargument = 0;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002273#ifdef MS_WINDOWS
Hirokazu Yamamotoa3c56092009-06-28 10:23:00 +00002274 PyObject *po;
Hirokazu Yamamoto5c3dd9a2009-06-29 15:52:21 +00002275#endif
Tim Peters44410012001-09-14 03:26:08 +00002276
2277 assert(PyFile_Check(self));
2278 if (foself->f_fp != NULL) {
2279 /* Have to close the existing file first. */
2280 PyObject *closeresult = file_close(foself);
2281 if (closeresult == NULL)
2282 return -1;
2283 Py_DECREF(closeresult);
2284 }
Tim Peters59c9a642001-09-13 05:38:56 +00002285
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +00002286#ifdef MS_WINDOWS
Hirokazu Yamamotoa3c56092009-06-28 10:23:00 +00002287 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2288 kwlist, &po, &mode, &bufsize)) {
2289 wideargument = 1;
2290 if (fill_file_fields(foself, NULL, po, mode,
2291 fclose) == NULL)
2292 goto Error;
2293 } else {
2294 /* Drop the argument parsing error as narrow
2295 strings are also valid. */
2296 PyErr_Clear();
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002297 }
2298#endif
2299
2300 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002301 PyObject *o_name;
2302
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002303 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2304 Py_FileSystemDefaultEncoding,
2305 &name,
2306 &mode, &bufsize))
2307 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002308
2309 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002310 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2311 kwlist, &o_name, &mode,
2312 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002313 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002314
2315 if (fill_file_fields(foself, NULL, o_name, mode,
2316 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002317 goto Error;
2318 }
Tim Peters44410012001-09-14 03:26:08 +00002319 if (open_the_file(foself, name, mode) == NULL)
2320 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002321 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002322 PyFile_SetBufSize(self, bufsize);
2323 goto Done;
2324
2325Error:
2326 ret = -1;
2327 /* fall through */
2328Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002329 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002330 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002331}
2332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002333PyDoc_VAR(file_doc) =
2334PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002335"file(name[, mode[, buffering]]) -> file object\n"
2336"\n"
2337"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2338"writing or appending. The file will be created if it doesn't exist\n"
2339"when opened for writing or appending; it will be truncated when\n"
2340"opened for writing. Add a 'b' to the mode for binary files.\n"
2341"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2342"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002343"buffered, and larger numbers specify the buffer size. The preferred way\n"
2344"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002345)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002346PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002347"Add a 'U' to mode to open the file for input with universal newline\n"
2348"support. Any line ending in the input file will be seen as a '\\n'\n"
2349"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2350"the value for this attribute is one of None (no newline read yet),\n"
2351"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2352"\n"
2353"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002354);
Tim Peters59c9a642001-09-13 05:38:56 +00002355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002356PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002357 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002358 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002359 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002360 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002361 (destructor)file_dealloc, /* tp_dealloc */
2362 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363 0, /* tp_getattr */
2364 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002365 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002366 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002367 0, /* tp_as_number */
2368 0, /* tp_as_sequence */
2369 0, /* tp_as_mapping */
2370 0, /* tp_hash */
2371 0, /* tp_call */
2372 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002374 /* softspace is writable: we must supply tp_setattro */
2375 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002376 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002377 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002378 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379 0, /* tp_traverse */
2380 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002381 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002382 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002383 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002384 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385 file_methods, /* tp_methods */
2386 file_memberlist, /* tp_members */
2387 file_getsetlist, /* tp_getset */
2388 0, /* tp_base */
2389 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002390 0, /* tp_descr_get */
2391 0, /* tp_descr_set */
2392 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002393 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002394 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002395 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002396 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002397};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002398
2399/* Interface for the 'soft space' between print items. */
2400
2401int
Fred Drakefd99de62000-07-09 05:02:18 +00002402PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002403{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002404 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002405 if (f == NULL) {
2406 /* Do nothing */
2407 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002408 else if (PyFile_Check(f)) {
2409 oldflag = ((PyFileObject *)f)->f_softspace;
2410 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002411 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002412 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002413 PyObject *v;
2414 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002415 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002416 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002417 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002418 if (PyInt_Check(v))
2419 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002420 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002421 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002422 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002423 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002424 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002425 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002426 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002427 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2428 PyErr_Clear();
2429 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002430 }
2431 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002432 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002433}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002434
2435/* Interfaces to write objects/strings to file-like objects */
2436
2437int
Fred Drakefd99de62000-07-09 05:02:18 +00002438PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002439{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002440 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002441 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002442 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002443 return -1;
2444 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002445 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002446 PyFileObject *fobj = (PyFileObject *) f;
Fred Drake086a0f72004-03-19 15:22:36 +00002447#ifdef Py_USING_UNICODE
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002448 PyObject *enc = fobj->f_encoding;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002449 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002450#endif
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002451 if (fobj->f_fp == NULL) {
Guido van Rossum3165fe61992-09-25 21:59:05 +00002452 err_closed();
2453 return -1;
2454 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002455#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002456 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002457 PyUnicode_Check(v) && enc != Py_None) {
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002458 char *cenc = PyString_AS_STRING(enc);
Martin v. Löwis99815892008-06-01 07:20:46 +00002459 char *errors = fobj->f_errors == Py_None ?
Gregory P. Smith99a3dce2008-06-10 17:42:36 +00002460 "strict" : PyString_AS_STRING(fobj->f_errors);
Martin v. Löwis99815892008-06-01 07:20:46 +00002461 value = PyUnicode_AsEncodedString(v, cenc, errors);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002462 if (value == NULL)
2463 return -1;
2464 } else {
2465 value = v;
2466 Py_INCREF(value);
2467 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002468 result = file_PyObject_Print(value, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002469 Py_DECREF(value);
2470 return result;
2471#else
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002472 return file_PyObject_Print(v, fobj, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002473#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002474 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002475 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002476 if (writer == NULL)
2477 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002478 if (flags & Py_PRINT_RAW) {
2479 if (PyUnicode_Check(v)) {
2480 value = v;
2481 Py_INCREF(value);
2482 } else
2483 value = PyObject_Str(v);
2484 }
2485 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002486 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002487 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002488 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002489 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002490 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002491 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002492 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002493 Py_DECREF(value);
2494 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002495 return -1;
2496 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002497 result = PyEval_CallObject(writer, args);
2498 Py_DECREF(args);
2499 Py_DECREF(value);
2500 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002501 if (result == NULL)
2502 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002503 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002504 return 0;
2505}
2506
Guido van Rossum27a60b11997-05-22 22:25:11 +00002507int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002508PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002509{
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002510
Guido van Rossum3165fe61992-09-25 21:59:05 +00002511 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002512 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002513 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002514 PyErr_SetString(PyExc_SystemError,
2515 "null file for PyFile_WriteString");
2516 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002517 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002518 else if (PyFile_Check(f)) {
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002519 PyFileObject *fobj = (PyFileObject *) f;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002520 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002521 if (fp == NULL) {
2522 err_closed();
2523 return -1;
2524 }
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002525 FILE_BEGIN_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002526 fputs(s, fp);
Gregory P. Smithaa63d0d2008-04-06 23:11:17 +00002527 FILE_END_ALLOW_THREADS(fobj)
Guido van Rossum27a60b11997-05-22 22:25:11 +00002528 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002529 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002530 else if (!PyErr_Occurred()) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002531 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002532 int err;
2533 if (v == NULL)
2534 return -1;
2535 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2536 Py_DECREF(v);
2537 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002538 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002539 else
2540 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002541}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002542
2543/* Try to get a file-descriptor from a Python object. If the object
2544 is an integer or long integer, its value is returned. If not, the
2545 object's fileno() method is called if it exists; the method must return
2546 an integer or long integer, which is returned as the file descriptor value.
2547 -1 is returned on failure.
2548*/
2549
2550int PyObject_AsFileDescriptor(PyObject *o)
2551{
2552 int fd;
2553 PyObject *meth;
2554
2555 if (PyInt_Check(o)) {
2556 fd = PyInt_AsLong(o);
2557 }
2558 else if (PyLong_Check(o)) {
2559 fd = PyLong_AsLong(o);
2560 }
2561 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2562 {
2563 PyObject *fno = PyEval_CallObject(meth, NULL);
2564 Py_DECREF(meth);
2565 if (fno == NULL)
2566 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002567
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002568 if (PyInt_Check(fno)) {
2569 fd = PyInt_AsLong(fno);
2570 Py_DECREF(fno);
2571 }
2572 else if (PyLong_Check(fno)) {
2573 fd = PyLong_AsLong(fno);
2574 Py_DECREF(fno);
2575 }
2576 else {
2577 PyErr_SetString(PyExc_TypeError,
2578 "fileno() returned a non-integer");
2579 Py_DECREF(fno);
2580 return -1;
2581 }
2582 }
2583 else {
2584 PyErr_SetString(PyExc_TypeError,
2585 "argument must be an int, or have a fileno() method.");
2586 return -1;
2587 }
2588
2589 if (fd < 0) {
2590 PyErr_Format(PyExc_ValueError,
2591 "file descriptor cannot be a negative integer (%i)",
2592 fd);
2593 return -1;
2594 }
2595 return fd;
2596}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002597
Jack Jansen7b8c7542002-04-14 20:12:41 +00002598/* From here on we need access to the real fgets and fread */
2599#undef fgets
2600#undef fread
2601
2602/*
2603** Py_UniversalNewlineFgets is an fgets variation that understands
2604** all of \r, \n and \r\n conventions.
2605** The stream should be opened in binary mode.
2606** If fobj is NULL the routine always does newline conversion, and
2607** it may peek one char ahead to gobble the second char in \r\n.
2608** If fobj is non-NULL it must be a PyFileObject. In this case there
2609** is no readahead but in stead a flag is used to skip a following
2610** \n on the next read. Also, if the file is open in binary mode
2611** the whole conversion is skipped. Finally, the routine keeps track of
2612** the different types of newlines seen.
2613** Note that we need no error handling: fgets() treats error and eof
2614** identically.
2615*/
2616char *
2617Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2618{
2619 char *p = buf;
2620 int c;
2621 int newlinetypes = 0;
2622 int skipnextlf = 0;
2623 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002624
Jack Jansen7b8c7542002-04-14 20:12:41 +00002625 if (fobj) {
2626 if (!PyFile_Check(fobj)) {
2627 errno = ENXIO; /* What can you do... */
2628 return NULL;
2629 }
2630 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2631 if ( !univ_newline )
2632 return fgets(buf, n, stream);
2633 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2634 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2635 }
2636 FLOCKFILE(stream);
2637 c = 'x'; /* Shut up gcc warning */
2638 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2639 if (skipnextlf ) {
2640 skipnextlf = 0;
2641 if (c == '\n') {
2642 /* Seeing a \n here with skipnextlf true
2643 ** means we saw a \r before.
2644 */
2645 newlinetypes |= NEWLINE_CRLF;
2646 c = GETC(stream);
2647 if (c == EOF) break;
2648 } else {
2649 /*
2650 ** Note that c == EOF also brings us here,
2651 ** so we're okay if the last char in the file
2652 ** is a CR.
2653 */
2654 newlinetypes |= NEWLINE_CR;
2655 }
2656 }
2657 if (c == '\r') {
2658 /* A \r is translated into a \n, and we skip
2659 ** an adjacent \n, if any. We don't set the
2660 ** newlinetypes flag until we've seen the next char.
2661 */
2662 skipnextlf = 1;
2663 c = '\n';
2664 } else if ( c == '\n') {
2665 newlinetypes |= NEWLINE_LF;
2666 }
2667 *p++ = c;
2668 if (c == '\n') break;
2669 }
2670 if ( c == EOF && skipnextlf )
2671 newlinetypes |= NEWLINE_CR;
2672 FUNLOCKFILE(stream);
2673 *p = '\0';
2674 if (fobj) {
2675 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2676 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2677 } else if ( skipnextlf ) {
2678 /* If we have no file object we cannot save the
2679 ** skipnextlf flag. We have to readahead, which
2680 ** will cause a pause if we're reading from an
2681 ** interactive stream, but that is very unlikely
2682 ** unless we're doing something silly like
2683 ** execfile("/dev/tty").
2684 */
2685 c = GETC(stream);
2686 if ( c != '\n' )
2687 ungetc(c, stream);
2688 }
2689 if (p == buf)
2690 return NULL;
2691 return buf;
2692}
2693
2694/*
2695** Py_UniversalNewlineFread is an fread variation that understands
2696** all of \r, \n and \r\n conventions.
2697** The stream should be opened in binary mode.
2698** fobj must be a PyFileObject. In this case there
2699** is no readahead but in stead a flag is used to skip a following
2700** \n on the next read. Also, if the file is open in binary mode
2701** the whole conversion is skipped. Finally, the routine keeps track of
2702** the different types of newlines seen.
2703*/
2704size_t
Tim Peters058b1412002-04-21 07:29:14 +00002705Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002706 FILE *stream, PyObject *fobj)
2707{
Tim Peters058b1412002-04-21 07:29:14 +00002708 char *dst = buf;
2709 PyFileObject *f = (PyFileObject *)fobj;
2710 int newlinetypes, skipnextlf;
2711
2712 assert(buf != NULL);
2713 assert(stream != NULL);
2714
Jack Jansen7b8c7542002-04-14 20:12:41 +00002715 if (!fobj || !PyFile_Check(fobj)) {
2716 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002717 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002718 }
Tim Peters058b1412002-04-21 07:29:14 +00002719 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002720 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002721 newlinetypes = f->f_newlinetypes;
2722 skipnextlf = f->f_skipnextlf;
2723 /* Invariant: n is the number of bytes remaining to be filled
2724 * in the buffer.
2725 */
2726 while (n) {
2727 size_t nread;
2728 int shortread;
2729 char *src = dst;
2730
2731 nread = fread(dst, 1, n, stream);
2732 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002733 if (nread == 0)
2734 break;
2735
Tim Peterse1682a82002-04-21 18:15:20 +00002736 n -= nread; /* assuming 1 byte out for each in; will adjust */
2737 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002738 while (nread--) {
2739 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002740 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002741 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002742 *dst++ = '\n';
2743 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002744 }
2745 else if (skipnextlf && c == '\n') {
2746 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002747 skipnextlf = 0;
2748 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002749 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002750 }
2751 else {
2752 /* Normal char to be stored in buffer. Also
2753 * update the newlinetypes flag if either this
2754 * is an LF or the previous char was a CR.
2755 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002756 if (c == '\n')
2757 newlinetypes |= NEWLINE_LF;
2758 else if (skipnextlf)
2759 newlinetypes |= NEWLINE_CR;
2760 *dst++ = c;
2761 skipnextlf = 0;
2762 }
2763 }
Tim Peters058b1412002-04-21 07:29:14 +00002764 if (shortread) {
2765 /* If this is EOF, update type flags. */
2766 if (skipnextlf && feof(stream))
2767 newlinetypes |= NEWLINE_CR;
2768 break;
2769 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002770 }
Tim Peters058b1412002-04-21 07:29:14 +00002771 f->f_newlinetypes = newlinetypes;
2772 f->f_skipnextlf = skipnextlf;
2773 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002774}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002775
2776#ifdef __cplusplus
2777}
2778#endif