blob: 13f64fbe3cf02500104c833d675b9ec18c453f33 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Mark Hammondc2e85bd2002-10-03 05:10:39 +000019#ifdef _MSC_VER
20/* Need GetVersion to see if on NT so safe to use _wfopen */
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#endif /* _MSC_VER */
24
Andrew MacIntyrec4874392002-02-26 11:36:35 +000025#if defined(PYOS_OS2) && defined(PYCC_GCC)
26#include <io.h>
27#endif
28
Guido van Rossumc0b618a1997-05-02 03:12:38 +000029#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000030
Guido van Rossumff7e83d1999-08-27 20:39:37 +000031#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000032#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000033#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Jack Jansen7b8c7542002-04-14 20:12:41 +000035#ifdef HAVE_GETC_UNLOCKED
36#define GETC(f) getc_unlocked(f)
37#define FLOCKFILE(f) flockfile(f)
38#define FUNLOCKFILE(f) funlockfile(f)
39#else
40#define GETC(f) getc(f)
41#define FLOCKFILE(f)
42#define FUNLOCKFILE(f)
43#endif
44
Jack Jansen7b8c7542002-04-14 20:12:41 +000045/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000050
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051#ifdef __cplusplus
52extern "C" {
53#endif
54
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000056PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000060 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062}
63
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000065PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000068 return NULL;
69 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000070 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000071}
72
Neil Schemenauered19b882002-03-23 02:06:50 +000073/* On Unix, fopen will succeed for directories.
74 In Python, there should be no file objects referring to
75 directories, so we need a check. */
76
77static PyFileObject*
78dircheck(PyFileObject* f)
79{
80#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
81 struct stat buf;
82 if (f->f_fp == NULL)
83 return f;
84 if (fstat(fileno(f->f_fp), &buf) == 0 &&
85 S_ISDIR(buf.st_mode)) {
86#ifdef HAVE_STRERROR
87 char *msg = strerror(EISDIR);
88#else
89 char *msg = "Is a directory";
90#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000091 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000092 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000093 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000094 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000095 return NULL;
96 }
97#endif
98 return f;
99}
100
Tim Peters59c9a642001-09-13 05:38:56 +0000101
102static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000103fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
104 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000107 assert(f != NULL);
108 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000109 assert(f->f_fp == NULL);
110
111 Py_DECREF(f->f_name);
112 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000113 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000114
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000115 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000116 f->f_name = name;
117
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000119
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000120 f->f_close = close;
Tim Peters59c9a642001-09-13 05:38:56 +0000121 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000122 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000123 f->f_univ_newline = (strchr(mode, 'U') != NULL);
124 f->f_newlinetypes = NEWLINE_UNKNOWN;
125 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000126 Py_INCREF(Py_None);
127 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000128
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000129 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000132 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000136/* check for known incorrect mode strings - problem is, platforms are
137 free to accept any mode characters they like and are supposed to
138 ignore stuff they don't understand... write or append mode with
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139 universal newline support is expressly forbidden by PEP 278.
140 Additionally, remove the 'U' from the mode string as platforms
141 won't know what it is. */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000142/* zero return is kewl - one is un-kewl */
143static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000144sanitize_the_mode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000145{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000146 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000147 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000148
Thomas Wouters477c8d52006-05-27 19:21:47 +0000149 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000150 PyErr_SetString(PyExc_ValueError, "empty mode string");
151 return 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000152 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000153
Thomas Wouters477c8d52006-05-27 19:21:47 +0000154 upos = strchr(mode, 'U');
155 if (upos) {
156 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000157
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158 if (mode[0] == 'w' || mode[0] == 'a') {
159 PyErr_Format(PyExc_ValueError, "universal newline "
160 "mode can only be used with modes "
161 "starting with 'r'");
162 return 1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000163 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000164
165 if (mode[0] != 'r') {
166 memmove(mode+1, mode, strlen(mode)+1);
167 mode[0] = 'r';
168 }
169
170 if (!strchr(mode, 'b')) {
171 memmove(mode+2, mode+1, strlen(mode));
172 mode[1] = 'b';
173 }
174 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
175 PyErr_Format(PyExc_ValueError, "mode string must begin with "
176 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
177 return 1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000178 }
179
180 return 0;
181}
182
Tim Peters59c9a642001-09-13 05:38:56 +0000183static PyObject *
184open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000186 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000187 assert(f != NULL);
188 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000189#ifdef MS_WINDOWS
190 /* windows ignores the passed name in order to support Unicode */
191 assert(f->f_name != NULL);
192#else
Tim Peters59c9a642001-09-13 05:38:56 +0000193 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000194#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000195 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000196 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000197
Thomas Wouters477c8d52006-05-27 19:21:47 +0000198 /* probably need to replace 'U' by 'rb' */
199 newmode = PyMem_MALLOC(strlen(mode) + 3);
200 if (!newmode) {
201 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000202 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000203 }
204 strcpy(newmode, mode);
205
206 if (sanitize_the_mode(newmode)) {
207 f = NULL;
208 goto cleanup;
209 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000210
Tim Peters8fa45672001-09-13 21:01:29 +0000211 /* rexec.py can't stop a user from getting the file() constructor --
212 all they have to do is get *any* file object f, and then do
213 type(f). Here we prevent them from doing damage with it. */
214 if (PyEval_GetRestricted()) {
215 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000216 "file() constructor not accessible in restricted mode");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000217 f = NULL;
218 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000219 }
Tim Petersa27a1502001-11-09 20:59:14 +0000220 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000221
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000222#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000223 if (PyUnicode_Check(f->f_name)) {
224 PyObject *wmode;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000225 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000226 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000227 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000228 /* PyUnicode_AS_UNICODE OK without thread
229 lock as it is a simple dereference. */
230 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
231 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000232 Py_END_ALLOW_THREADS
233 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000234 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000235 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000236#endif
237 if (NULL == f->f_fp && NULL != name) {
238 Py_BEGIN_ALLOW_THREADS
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239 f->f_fp = fopen(name, newmode);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000240 Py_END_ALLOW_THREADS
241 }
242
Guido van Rossuma08095a1991-02-13 23:25:27 +0000243 if (f->f_fp == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000244#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000245 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
246 * across all Windows flavors. When it sets EINVAL varies
247 * across Windows flavors, the exact conditions aren't
248 * documented, and the answer lies in the OS's implementation
249 * of Win32's CreateFile function (whose source is secret).
250 * Seems the best we can do is map EINVAL to ENOENT.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000251 * Starting with Visual Studio .NET 2005, EINVAL is correctly
252 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000253 */
254 if (errno == 0) /* bad mode string */
255 errno = EINVAL;
256 else if (errno == EINVAL) /* unknown, but not a mode string */
257 errno = ENOENT;
258#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000259 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000260 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000261 mode);
262 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000263 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000264 f = NULL;
265 }
Tim Peters2ea91112002-04-08 04:13:12 +0000266 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000267 f = dircheck(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000268
269cleanup:
270 PyMem_FREE(newmode);
271
Tim Peters59c9a642001-09-13 05:38:56 +0000272 return (PyObject *)f;
273}
274
275PyObject *
276PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
277{
Tim Peters44410012001-09-14 03:26:08 +0000278 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
279 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000280 if (f != NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000281 PyObject *o_name = PyString_FromString(name);
282 if (o_name == NULL)
283 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000284 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000285 Py_DECREF(f);
286 f = NULL;
287 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000288 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000289 }
290 return (PyObject *) f;
291}
292
293PyObject *
294PyFile_FromString(char *name, char *mode)
295{
296 extern int fclose(FILE *);
297 PyFileObject *f;
298
299 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
300 if (f != NULL) {
301 if (open_the_file(f, name, mode) == NULL) {
302 Py_DECREF(f);
303 f = NULL;
304 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307}
308
Guido van Rossumb6775db1994-08-01 11:34:53 +0000309void
Fred Drakefd99de62000-07-09 05:02:18 +0000310PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000311{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000312 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000313 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314 int type;
315 switch (bufsize) {
316 case 0:
317 type = _IONBF;
318 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000319#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000320 case 1:
321 type = _IOLBF;
322 bufsize = BUFSIZ;
323 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000324#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000325 default:
326 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000327#ifndef HAVE_SETVBUF
328 bufsize = BUFSIZ;
329#endif
330 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000331 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000332 fflush(file->f_fp);
333 if (type == _IONBF) {
334 PyMem_Free(file->f_setbuf);
335 file->f_setbuf = NULL;
336 } else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000337 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
338 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000339 }
340#ifdef HAVE_SETVBUF
341 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000342#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000343 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000344#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000345 }
346}
347
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000348/* Set the encoding used to output Unicode strings.
349 Returh 1 on success, 0 on failure. */
350
351int
352PyFile_SetEncoding(PyObject *f, const char *enc)
353{
354 PyFileObject *file = (PyFileObject*)f;
355 PyObject *str = PyString_FromString(enc);
Thomas Woutersb2137042007-02-01 18:02:27 +0000356
357 assert(PyFile_Check(f));
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000358 if (!str)
359 return 0;
360 Py_DECREF(file->f_encoding);
361 file->f_encoding = str;
362 return 1;
363}
364
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000366err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000367{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000369 return NULL;
370}
371
Thomas Woutersc45251a2006-02-12 11:53:32 +0000372/* Refuse regular file I/O if there's data in the iteration-buffer.
373 * Mixing them would cause data to arrive out of order, as the read*
374 * methods don't use the iteration buffer. */
375static PyObject *
376err_iterbuffered(void)
377{
378 PyErr_SetString(PyExc_ValueError,
379 "Mixing iteration and read methods would lose data");
380 return NULL;
381}
382
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000383static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000384
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385/* Methods */
386
387static void
Fred Drakefd99de62000-07-09 05:02:18 +0000388file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000390 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000391 if (f->weakreflist != NULL)
392 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000393 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000395 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000396 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000397 if (sts == EOF)
398#ifdef HAVE_STRERROR
399 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
400#else
401 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
402#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000403 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000404 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000405 Py_XDECREF(f->f_name);
406 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000407 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000408 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000409 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410}
411
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000413file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000415 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000416#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000417 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000418 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
419 const char *name_str = name ? PyString_AsString(name) : "?";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000420 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
421 f->f_fp == NULL ? "closed" : "open",
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000422 name_str,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000423 PyString_AsString(f->f_mode),
424 f);
425 Py_XDECREF(name);
426 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000427#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000428 } else {
429 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000430 f->f_fp == NULL ? "closed" : "open",
431 PyString_AsString(f->f_name),
432 PyString_AsString(f->f_mode),
433 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000434 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435}
436
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000438file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000440 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000442 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000443 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000444 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000445 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000447 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448 f->f_fp = NULL;
449 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000450 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000451 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000452 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000454 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 return PyInt_FromLong((long)sts);
456 Py_INCREF(Py_None);
457 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000458}
459
Trent Mickf29f47b2000-08-11 19:02:59 +0000460
Guido van Rossumb8552162001-09-05 14:58:11 +0000461/* Our very own off_t-like type, 64-bit if possible */
462#if !defined(HAVE_LARGEFILE_SUPPORT)
463typedef off_t Py_off_t;
464#elif SIZEOF_OFF_T >= 8
465typedef off_t Py_off_t;
466#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000467typedef fpos_t Py_off_t;
468#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000469#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000470#endif
471
472
Trent Mickf29f47b2000-08-11 19:02:59 +0000473/* a portable fseek() function
474 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000475static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000476_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000477{
Guido van Rossumb8552162001-09-05 14:58:11 +0000478#if !defined(HAVE_LARGEFILE_SUPPORT)
479 return fseek(fp, offset, whence);
480#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000481 return fseeko(fp, offset, whence);
482#elif defined(HAVE_FSEEK64)
483 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000484#elif defined(__BEOS__)
485 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000486#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000487 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
488 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000489 fpos_t pos;
490 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000491 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000492#ifdef MS_WINDOWS
493 fflush(fp);
494 if (_lseeki64(fileno(fp), 0, 2) == -1)
495 return -1;
496#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000497 if (fseek(fp, 0, SEEK_END) != 0)
498 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000499#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000500 /* fall through */
501 case SEEK_CUR:
502 if (fgetpos(fp, &pos) != 0)
503 return -1;
504 offset += pos;
505 break;
506 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000507 }
508 return fsetpos(fp, &offset);
509#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000510#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000511#endif
512}
513
514
515/* a portable ftell() function
516 Return -1 on failure with errno set appropriately, current file
517 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000518static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000519_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000520{
Guido van Rossumb8552162001-09-05 14:58:11 +0000521#if !defined(HAVE_LARGEFILE_SUPPORT)
522 return ftell(fp);
523#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
524 return ftello(fp);
525#elif defined(HAVE_FTELL64)
526 return ftell64(fp);
527#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000528 fpos_t pos;
529 if (fgetpos(fp, &pos) != 0)
530 return -1;
531 return pos;
532#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000533#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000534#endif
535}
536
537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000539file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000541 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000542 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000543 Py_off_t offset;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000544 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000545
Guido van Rossumd7297e61992-07-06 14:19:26 +0000546 if (f->f_fp == NULL)
547 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000548 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000549 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000550 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000551 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000552 off_index = PyNumber_Index(offobj);
553 if (!off_index) {
554 if (!PyFloat_Check(offobj))
555 return NULL;
556 /* Deprecated in 2.6 */
557 PyErr_Clear();
558 if (PyErr_Warn(PyExc_DeprecationWarning,
559 "integer argument expected, got float"))
560 return NULL;
561 off_index = offobj;
562 Py_INCREF(offobj);
563 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000564#if !defined(HAVE_LARGEFILE_SUPPORT)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000565 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000566#else
Thomas Wouters89f507f2006-12-13 04:49:30 +0000567 offset = PyLong_Check(off_index) ?
568 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000569#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000570 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000571 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000572 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000573
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000575 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000576 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000578
Guido van Rossumff4949e1992-08-05 19:58:53 +0000579 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000580 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000581 clearerr(f->f_fp);
582 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000583 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000584 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585 Py_INCREF(Py_None);
586 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000587}
588
Trent Mickf29f47b2000-08-11 19:02:59 +0000589
Guido van Rossumd7047b31995-01-02 19:07:15 +0000590#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000591static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000592file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000593{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000594 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000595 PyObject *newsizeobj = NULL;
596 Py_off_t initialpos;
597 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000598
Guido van Rossumd7047b31995-01-02 19:07:15 +0000599 if (f->f_fp == NULL)
600 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000601 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000602 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000603
Tim Petersf1827cf2003-09-07 03:30:18 +0000604 /* Get current file position. If the file happens to be open for
605 * update and the last operation was an input operation, C doesn't
606 * define what the later fflush() will do, but we promise truncate()
607 * won't change the current position (and fflush() *does* change it
608 * then at least on Windows). The easiest thing is to capture
609 * current pos now and seek back to it at the end.
610 */
611 Py_BEGIN_ALLOW_THREADS
612 errno = 0;
613 initialpos = _portable_ftell(f->f_fp);
614 Py_END_ALLOW_THREADS
615 if (initialpos == -1)
616 goto onioerror;
617
Tim Petersfb05db22002-03-11 00:24:00 +0000618 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000619 * specified value.
620 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000621 if (newsizeobj != NULL) {
622#if !defined(HAVE_LARGEFILE_SUPPORT)
623 newsize = PyInt_AsLong(newsizeobj);
624#else
625 newsize = PyLong_Check(newsizeobj) ?
626 PyLong_AsLongLong(newsizeobj) :
627 PyInt_AsLong(newsizeobj);
628#endif
629 if (PyErr_Occurred())
630 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000631 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000632 else /* default to current position */
633 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000634
Tim Petersf1827cf2003-09-07 03:30:18 +0000635 /* Flush the stream. We're mixing stream-level I/O with lower-level
636 * I/O, and a flush may be necessary to synch both platform views
637 * of the current file state.
638 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000640 errno = 0;
641 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000642 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000643 if (ret != 0)
644 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000645
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000646#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000647 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000648 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000649 {
Tim Petersfb05db22002-03-11 00:24:00 +0000650 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000651
Tim Petersf1827cf2003-09-07 03:30:18 +0000652 /* Have to move current pos to desired endpoint on Windows. */
653 Py_BEGIN_ALLOW_THREADS
654 errno = 0;
655 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
656 Py_END_ALLOW_THREADS
657 if (ret)
658 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000659
Tim Peters8f01b682002-03-12 03:04:44 +0000660 /* Truncate. Note that this may grow the file! */
661 Py_BEGIN_ALLOW_THREADS
662 errno = 0;
663 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000664 ret = hFile == (HANDLE)-1;
665 if (ret == 0) {
666 ret = SetEndOfFile(hFile) == 0;
667 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000668 errno = EACCES;
669 }
670 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000671 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000672 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000673 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000674#else
675 Py_BEGIN_ALLOW_THREADS
676 errno = 0;
677 ret = ftruncate(fileno(f->f_fp), newsize);
678 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000679 if (ret != 0)
680 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000681#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000682
Tim Petersf1827cf2003-09-07 03:30:18 +0000683 /* Restore original file position. */
684 Py_BEGIN_ALLOW_THREADS
685 errno = 0;
686 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
687 Py_END_ALLOW_THREADS
688 if (ret)
689 goto onioerror;
690
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691 Py_INCREF(Py_None);
692 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000693
694onioerror:
695 PyErr_SetFromErrno(PyExc_IOError);
696 clearerr(f->f_fp);
697 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000698}
699#endif /* HAVE_FTRUNCATE */
700
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000701static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000702file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000703{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000704 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000705
Guido van Rossumd7297e61992-07-06 14:19:26 +0000706 if (f->f_fp == NULL)
707 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000709 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000710 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000711 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000712 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000713 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000714 clearerr(f->f_fp);
715 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000716 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000717 if (f->f_skipnextlf) {
718 int c;
719 c = GETC(f->f_fp);
720 if (c == '\n') {
721 pos++;
722 f->f_skipnextlf = 0;
723 } else if (c != EOF) ungetc(c, f->f_fp);
724 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000725#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000726 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000727#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000728 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000729#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000730}
731
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000733file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000734{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000735 if (f->f_fp == NULL)
736 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000738}
739
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000741file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000742{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000743 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000744
Guido van Rossumd7297e61992-07-06 14:19:26 +0000745 if (f->f_fp == NULL)
746 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000747 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000748 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000749 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000750 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000751 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000753 clearerr(f->f_fp);
754 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000755 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000756 Py_INCREF(Py_None);
757 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000758}
759
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000761file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000762{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000763 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000764 if (f->f_fp == NULL)
765 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000766 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000767 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000768 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000769 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000770}
771
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000772
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000773#if BUFSIZ < 8192
774#define SMALLCHUNK 8192
775#else
776#define SMALLCHUNK BUFSIZ
777#endif
778
Guido van Rossum3c259041999-01-14 19:00:14 +0000779#if SIZEOF_INT < 4
780#define BIGCHUNK (512 * 32)
781#else
782#define BIGCHUNK (512 * 1024)
783#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000784
785static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000786new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000787{
788#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000789 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000790 struct stat st;
791 if (fstat(fileno(f->f_fp), &st) == 0) {
792 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000793 /* The following is not a bug: we really need to call lseek()
794 *and* ftell(). The reason is that some stdio libraries
795 mistakenly flush their buffer when ftell() is called and
796 the lseek() call it makes fails, thereby throwing away
797 data that cannot be recovered in any way. To avoid this,
798 we first test lseek(), and only call ftell() if lseek()
799 works. We can't use the lseek() value either, because we
800 need to take the amount of buffered data into account.
801 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000802 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000803 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000804 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000805 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000806 if (pos < 0)
807 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000808 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000809 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000810 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000811 }
812#endif
813 if (currentsize > SMALLCHUNK) {
814 /* Keep doubling until we reach BIGCHUNK;
815 then keep adding BIGCHUNK. */
816 if (currentsize <= BIGCHUNK)
817 return currentsize + currentsize;
818 else
819 return currentsize + BIGCHUNK;
820 }
821 return currentsize + SMALLCHUNK;
822}
823
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000824#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
825#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
826#else
827#ifdef EWOULDBLOCK
828#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
829#else
830#ifdef EAGAIN
831#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
832#else
833#define BLOCKED_ERRNO(x) 0
834#endif
835#endif
836#endif
837
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000838static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000839file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000840{
Guido van Rossum789a1611997-05-10 22:33:55 +0000841 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000842 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000844
Guido van Rossumd7297e61992-07-06 14:19:26 +0000845 if (f->f_fp == NULL)
846 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000847 /* refuse to mix with f.next() */
848 if (f->f_buf != NULL &&
849 (f->f_bufend - f->f_bufptr) > 0 &&
850 f->f_buf[0] != '\0')
851 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000852 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000853 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000854 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000855 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000856 else
857 buffersize = bytesrequested;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000859 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000860 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000861 return NULL;
862 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000863 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000864 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000865 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000866 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000867 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000868 Py_BEGIN_ALLOW_THREADS
869 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000870 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000871 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000872 Py_END_ALLOW_THREADS
873 if (chunksize == 0) {
874 if (!ferror(f->f_fp))
875 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000876 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000877 /* When in non-blocking mode, data shouldn't
878 * be discarded if a blocking signal was
879 * received. That will also happen if
880 * chunksize != 0, but bytesread < buffersize. */
881 if (bytesread > 0 && BLOCKED_ERRNO(errno))
882 break;
883 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000884 Py_DECREF(v);
885 return NULL;
886 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000887 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000888 if (bytesread < buffersize) {
889 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000890 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000891 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000892 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000893 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000894 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000895 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000896 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000897 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000898 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000899 }
900 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000901 if (bytesread != buffersize)
902 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000903 return v;
904}
905
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000906static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000907file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000908{
909 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000910 Py_ssize_t ntodo;
911 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000912
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000913 if (f->f_fp == NULL)
914 return err_closed();
Guido van Rossumd624f182006-04-24 13:47:05 +0000915 if (!f->f_binary) {
916 PyErr_SetString(PyExc_TypeError,
917 "readinto() requires binary mode");
918 return NULL;
919 }
Thomas Woutersc45251a2006-02-12 11:53:32 +0000920 /* refuse to mix with f.next() */
921 if (f->f_buf != NULL &&
922 (f->f_bufend - f->f_bufptr) > 0 &&
923 f->f_buf[0] != '\0')
924 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000925 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000926 return NULL;
927 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000928 while (ntodo > 0) {
929 Py_BEGIN_ALLOW_THREADS
930 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000931 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000932 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000933 Py_END_ALLOW_THREADS
934 if (nnow == 0) {
935 if (!ferror(f->f_fp))
936 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000937 PyErr_SetFromErrno(PyExc_IOError);
938 clearerr(f->f_fp);
939 return NULL;
940 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000941 ndone += nnow;
942 ntodo -= nnow;
943 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000944 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000945}
946
Tim Peters86821b22001-01-07 21:19:34 +0000947/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000948Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000949
950Under MSVC 6:
951
Tim Peters1c733232001-01-08 04:02:07 +0000952+ MS threadsafe getc is very slow (multiple layers of function calls before+
953 after each character, to lock+unlock the stream).
954+ The stream-locking functions are MS-internal -- can't access them from user
955 code.
956+ There's nothing Tim could find in the MS C or platform SDK libraries that
957 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000958+ MS fgets locks/unlocks only once per line; it's the only hook we have.
959
960So we use fgets for speed(!), despite that it's painful.
961
962MS realloc is also slow.
963
Tim Petersf29b64d2001-01-15 06:33:19 +0000964Reports from other platforms on this method vs getc_unlocked (which MS doesn't
965have):
966 Linux a wash
967 Solaris a wash
968 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000969
Tim Petersf29b64d2001-01-15 06:33:19 +0000970CAUTION: The C std isn't clear about this: in those cases where fgets
971writes something into the buffer, can it write into any position beyond the
972required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
973known on which it does; and it would be a strange way to code fgets. Still,
974getline_via_fgets may not work correctly if it does. The std test
975test_bufio.py should fail if platform fgets() routinely writes beyond the
976trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000977**************************************************************************/
978
Tim Petersf29b64d2001-01-15 06:33:19 +0000979/* Use this routine if told to, or by default on non-get_unlocked()
980 * platforms unless told not to. Yikes! Let's spell that out:
981 * On a platform with getc_unlocked():
982 * By default, use getc_unlocked().
983 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
984 * On a platform without getc_unlocked():
985 * By default, use fgets().
986 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
987 */
988#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
989#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000990#endif
991
Tim Petersf29b64d2001-01-15 06:33:19 +0000992#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
993#undef USE_FGETS_IN_GETLINE
994#endif
995
996#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000997static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000998getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000999{
Tim Peters15b83852001-01-08 00:53:12 +00001000/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001001 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1002 * to fill this much of the buffer with a known value in order to figure out
1003 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1004 * than "most" lines, we waste time filling unused buffer slots. 100 is
1005 * surely adequate for most peoples' email archives, chewing over source code,
1006 * etc -- "regular old text files".
1007 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1008 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1009 * cautions about boosting that. 300 was chosen because the worst real-life
1010 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1011 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001012 */
Tim Peters142297a2001-01-15 10:36:56 +00001013#define INITBUFSIZE 100
1014#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001015 char* p; /* temp */
1016 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001017 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001018 char* pvfree; /* address of next free slot */
1019 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001020 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1021 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001022 size_t increment; /* amount to increment the buffer */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001023 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001024
Tim Peters15b83852001-01-08 00:53:12 +00001025 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001026 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001027 */
Tim Peters142297a2001-01-15 10:36:56 +00001028 total_v_size = INITBUFSIZE; /* start small and pray */
1029 pvfree = buf;
1030 for (;;) {
1031 Py_BEGIN_ALLOW_THREADS
1032 pvend = buf + total_v_size;
1033 nfree = pvend - pvfree;
1034 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001035 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1036 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +00001037 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001038
Tim Peters142297a2001-01-15 10:36:56 +00001039 if (p == NULL) {
1040 clearerr(fp);
1041 if (PyErr_CheckSignals())
1042 return NULL;
1043 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001044 return v;
1045 }
Tim Peters142297a2001-01-15 10:36:56 +00001046 /* fgets read *something* */
1047 p = memchr(pvfree, '\n', nfree);
1048 if (p != NULL) {
1049 /* Did the \n come from fgets or from us?
1050 * Since fgets stops at the first \n, and then writes
1051 * \0, if it's from fgets a \0 must be next. But if
1052 * that's so, it could not have come from us, since
1053 * the \n's we filled the buffer with have only more
1054 * \n's to the right.
1055 */
1056 if (p+1 < pvend && *(p+1) == '\0') {
1057 /* It's from fgets: we win! In particular,
1058 * we haven't done any mallocs yet, and can
1059 * build the final result on the first try.
1060 */
1061 ++p; /* include \n from fgets */
1062 }
1063 else {
1064 /* Must be from us: fgets didn't fill the
1065 * buffer and didn't find a newline, so it
1066 * must be the last and newline-free line of
1067 * the file.
1068 */
1069 assert(p > pvfree && *(p-1) == '\0');
1070 --p; /* don't include \0 from fgets */
1071 }
1072 v = PyString_FromStringAndSize(buf, p - buf);
1073 return v;
1074 }
1075 /* yuck: fgets overwrote all the newlines, i.e. the entire
1076 * buffer. So this line isn't over yet, or maybe it is but
1077 * we're exactly at EOF. If we haven't already, try using the
1078 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001079 */
Tim Peters142297a2001-01-15 10:36:56 +00001080 assert(*(pvend-1) == '\0');
1081 if (pvfree == buf) {
1082 pvfree = pvend - 1; /* overwrite trailing null */
1083 total_v_size = MAXBUFSIZE;
1084 }
1085 else
1086 break;
Tim Peters86821b22001-01-07 21:19:34 +00001087 }
Tim Peters142297a2001-01-15 10:36:56 +00001088
1089 /* The stack buffer isn't big enough; malloc a string object and read
1090 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001091 */
Tim Petersddea2082002-03-23 10:03:50 +00001092 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001093 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001094 if (v == NULL)
1095 return v;
1096 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001097 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1098 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001099
1100 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001101 * after setting p one beyond the end of the line. The code here is
1102 * very much like the code above, except reads into v's buffer; see
1103 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001104 */
1105 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001106 Py_BEGIN_ALLOW_THREADS
1107 pvend = BUF(v) + total_v_size;
1108 nfree = pvend - pvfree;
1109 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001110 assert(nfree < INT_MAX);
1111 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001112 Py_END_ALLOW_THREADS
1113
1114 if (p == NULL) {
1115 clearerr(fp);
1116 if (PyErr_CheckSignals()) {
1117 Py_DECREF(v);
1118 return NULL;
1119 }
1120 p = pvfree;
1121 break;
1122 }
Tim Peters86821b22001-01-07 21:19:34 +00001123 p = memchr(pvfree, '\n', nfree);
1124 if (p != NULL) {
1125 if (p+1 < pvend && *(p+1) == '\0') {
1126 /* \n came from fgets */
1127 ++p;
1128 break;
1129 }
1130 /* \n came from us; last line of file, no newline */
1131 assert(p > pvfree && *(p-1) == '\0');
1132 --p;
1133 break;
1134 }
1135 /* expand buffer and try again */
1136 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001137 increment = total_v_size >> 2; /* mild exponential growth */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001138 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001139 total_v_size += increment;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001140 /* check for overflow */
1141 if (total_v_size <= prev_v_size ||
1142 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001143 PyErr_SetString(PyExc_OverflowError,
1144 "line is longer than a Python string can hold");
1145 Py_DECREF(v);
1146 return NULL;
1147 }
1148 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1149 return NULL;
1150 /* overwrite the trailing null byte */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001151 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001152 }
1153 if (BUF(v) + total_v_size != p)
1154 _PyString_Resize(&v, p - BUF(v));
1155 return v;
1156#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001157#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001158}
Tim Petersf29b64d2001-01-15 06:33:19 +00001159#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001160
Guido van Rossum0bd24411991-04-04 15:21:57 +00001161/* Internal routine to get a line.
1162 Size argument interpretation:
1163 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001164 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001165*/
1166
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001167static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001168get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001169{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001170 FILE *fp = f->f_fp;
1171 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001172 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001173 size_t total_v_size; /* total # of slots in buffer */
1174 size_t used_v_size; /* # used slots in buffer */
1175 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001176 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001177 int newlinetypes = f->f_newlinetypes;
1178 int skipnextlf = f->f_skipnextlf;
1179 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001180
Jack Jansen7b8c7542002-04-14 20:12:41 +00001181#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001182 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001183 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001184#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001185 total_v_size = n > 0 ? n : 100;
1186 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001187 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001188 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001189 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001190 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001191
Guido van Rossumce5ba841991-03-06 13:06:18 +00001192 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001193 Py_BEGIN_ALLOW_THREADS
1194 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001195 if (univ_newline) {
1196 c = 'x'; /* Shut up gcc warning */
1197 while ( buf != end && (c = GETC(fp)) != EOF ) {
1198 if (skipnextlf ) {
1199 skipnextlf = 0;
1200 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001201 /* Seeing a \n here with
1202 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001203 * saw a \r before.
1204 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001205 newlinetypes |= NEWLINE_CRLF;
1206 c = GETC(fp);
1207 if (c == EOF) break;
1208 } else {
1209 newlinetypes |= NEWLINE_CR;
1210 }
1211 }
1212 if (c == '\r') {
1213 skipnextlf = 1;
1214 c = '\n';
1215 } else if ( c == '\n')
1216 newlinetypes |= NEWLINE_LF;
1217 *buf++ = c;
1218 if (c == '\n') break;
1219 }
1220 if ( c == EOF && skipnextlf )
1221 newlinetypes |= NEWLINE_CR;
1222 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001223 while ((c = GETC(fp)) != EOF &&
1224 (*buf++ = c) != '\n' &&
1225 buf != end)
1226 ;
1227 FUNLOCKFILE(fp);
1228 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001229 f->f_newlinetypes = newlinetypes;
1230 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001231 if (c == '\n')
1232 break;
1233 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001234 if (ferror(fp)) {
1235 PyErr_SetFromErrno(PyExc_IOError);
1236 clearerr(fp);
1237 Py_DECREF(v);
1238 return NULL;
1239 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001240 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001241 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001242 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001243 return NULL;
1244 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001245 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001246 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001247 /* Must be because buf == end */
1248 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001249 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001250 used_v_size = total_v_size;
1251 increment = total_v_size >> 2; /* mild exponential growth */
1252 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001253 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001254 PyErr_SetString(PyExc_OverflowError,
1255 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001256 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001257 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001258 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001259 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001260 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001261 buf = BUF(v) + used_v_size;
1262 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001263 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001264
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001265 used_v_size = buf - BUF(v);
1266 if (used_v_size != total_v_size)
1267 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001268 return v;
1269}
1270
Guido van Rossum0bd24411991-04-04 15:21:57 +00001271/* External C interface */
1272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001273PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001274PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001275{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001276 PyObject *result;
1277
Guido van Rossum3165fe61992-09-25 21:59:05 +00001278 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001279 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001280 return NULL;
1281 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001282
1283 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001284 PyFileObject *fo = (PyFileObject *)f;
1285 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001286 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001287 /* refuse to mix with f.next() */
1288 if (fo->f_buf != NULL &&
1289 (fo->f_bufend - fo->f_bufptr) > 0 &&
1290 fo->f_buf[0] != '\0')
1291 return err_iterbuffered();
1292 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001293 }
1294 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001295 PyObject *reader;
1296 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001297
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001298 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001299 if (reader == NULL)
1300 return NULL;
1301 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001302 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001303 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001304 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001305 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001306 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001307 return NULL;
1308 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001309 result = PyEval_CallObject(reader, args);
1310 Py_DECREF(reader);
1311 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001312 if (result != NULL && !PyString_Check(result) &&
1313 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001314 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001315 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001316 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001317 "object.readline() returned non-string");
1318 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001319 }
1320
1321 if (n < 0 && result != NULL && PyString_Check(result)) {
1322 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001323 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001324 if (len == 0) {
1325 Py_DECREF(result);
1326 result = NULL;
1327 PyErr_SetString(PyExc_EOFError,
1328 "EOF when reading a line");
1329 }
1330 else if (s[len-1] == '\n') {
1331 if (result->ob_refcnt == 1)
1332 _PyString_Resize(&result, len-1);
1333 else {
1334 PyObject *v;
1335 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001336 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001337 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001338 }
1339 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001340 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001341#ifdef Py_USING_UNICODE
1342 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1343 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001344 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001345 if (len == 0) {
1346 Py_DECREF(result);
1347 result = NULL;
1348 PyErr_SetString(PyExc_EOFError,
1349 "EOF when reading a line");
1350 }
1351 else if (s[len-1] == '\n') {
1352 if (result->ob_refcnt == 1)
1353 PyUnicode_Resize(&result, len-1);
1354 else {
1355 PyObject *v;
1356 v = PyUnicode_FromUnicode(s, len-1);
1357 Py_DECREF(result);
1358 result = v;
1359 }
1360 }
1361 }
1362#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001363 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001364}
1365
1366/* Python method */
1367
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001368static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001369file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001370{
Guido van Rossum789a1611997-05-10 22:33:55 +00001371 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001372
Guido van Rossumd7297e61992-07-06 14:19:26 +00001373 if (f->f_fp == NULL)
1374 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001375 /* refuse to mix with f.next() */
1376 if (f->f_buf != NULL &&
1377 (f->f_bufend - f->f_bufptr) > 0 &&
1378 f->f_buf[0] != '\0')
1379 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001380 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001381 return NULL;
1382 if (n == 0)
1383 return PyString_FromString("");
1384 if (n < 0)
1385 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001386 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001387}
1388
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001389static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001390file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001391{
Guido van Rossum789a1611997-05-10 22:33:55 +00001392 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001393 PyObject *list;
1394 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001395 char small_buffer[SMALLCHUNK];
1396 char *buffer = small_buffer;
1397 size_t buffersize = SMALLCHUNK;
1398 PyObject *big_buffer = NULL;
1399 size_t nfilled = 0;
1400 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001401 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001402 char *p, *q, *end;
1403 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001404 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001405
Guido van Rossumd7297e61992-07-06 14:19:26 +00001406 if (f->f_fp == NULL)
1407 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001408 /* refuse to mix with f.next() */
1409 if (f->f_buf != NULL &&
1410 (f->f_bufend - f->f_bufptr) > 0 &&
1411 f->f_buf[0] != '\0')
1412 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001413 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001414 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001415 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001416 return NULL;
1417 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001418 if (shortread)
1419 nread = 0;
1420 else {
1421 Py_BEGIN_ALLOW_THREADS
1422 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001423 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001424 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001425 Py_END_ALLOW_THREADS
1426 shortread = (nread < buffersize-nfilled);
1427 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001428 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001429 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001430 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001431 break;
1432 PyErr_SetFromErrno(PyExc_IOError);
1433 clearerr(f->f_fp);
1434 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001435 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001436 list = NULL;
1437 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001438 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001439 totalread += nread;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001440 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001441 if (p == NULL) {
1442 /* Need a larger buffer to fit this line */
1443 nfilled += nread;
1444 buffersize *= 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001445 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001446 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001447 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001448 goto error;
1449 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001450 if (big_buffer == NULL) {
1451 /* Create the big buffer */
1452 big_buffer = PyString_FromStringAndSize(
1453 NULL, buffersize);
1454 if (big_buffer == NULL)
1455 goto error;
1456 buffer = PyString_AS_STRING(big_buffer);
1457 memcpy(buffer, small_buffer, nfilled);
1458 }
1459 else {
1460 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001461 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1462 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001463 buffer = PyString_AS_STRING(big_buffer);
1464 }
1465 continue;
1466 }
1467 end = buffer+nfilled+nread;
1468 q = buffer;
1469 do {
1470 /* Process complete lines */
1471 p++;
1472 line = PyString_FromStringAndSize(q, p-q);
1473 if (line == NULL)
1474 goto error;
1475 err = PyList_Append(list, line);
1476 Py_DECREF(line);
1477 if (err != 0)
1478 goto error;
1479 q = p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001480 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001481 } while (p != NULL);
1482 /* Move the remaining incomplete line to the start */
1483 nfilled = end-q;
1484 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001485 if (sizehint > 0)
1486 if (totalread >= (size_t)sizehint)
1487 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001488 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001489 if (nfilled != 0) {
1490 /* Partial last line */
1491 line = PyString_FromStringAndSize(buffer, nfilled);
1492 if (line == NULL)
1493 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001494 if (sizehint > 0) {
1495 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001496 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001497 if (rest == NULL) {
1498 Py_DECREF(line);
1499 goto error;
1500 }
1501 PyString_Concat(&line, rest);
1502 Py_DECREF(rest);
1503 if (line == NULL)
1504 goto error;
1505 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001506 err = PyList_Append(list, line);
1507 Py_DECREF(line);
1508 if (err != 0)
1509 goto error;
1510 }
1511 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001512 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001513 return list;
1514}
1515
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001516static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001517file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001518{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001519 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001520 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001521 if (f->f_fp == NULL)
1522 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001523 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001524 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001525 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001526 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001527 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001528 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001529 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001530 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001531 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001532 return NULL;
1533 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001534 Py_INCREF(Py_None);
1535 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001536}
1537
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001538static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001539file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001540{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001541#define CHUNKSIZE 1000
1542 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001543 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001544 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001545 int index, islist;
1546 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001547
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001548 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001549 if (f->f_fp == NULL)
1550 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001551
1552 result = NULL;
1553 list = NULL;
1554 islist = PyList_Check(seq);
1555 if (islist)
1556 it = NULL;
1557 else {
1558 it = PyObject_GetIter(seq);
1559 if (it == NULL) {
1560 PyErr_SetString(PyExc_TypeError,
1561 "writelines() requires an iterable argument");
1562 return NULL;
1563 }
1564 /* From here on, fail by going to error, to reclaim "it". */
1565 list = PyList_New(CHUNKSIZE);
1566 if (list == NULL)
1567 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001568 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001569
1570 /* Strategy: slurp CHUNKSIZE lines into a private list,
1571 checking that they are all strings, then write that list
1572 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001573 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001574 if (islist) {
1575 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001576 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001577 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001578 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001579 j = PyList_GET_SIZE(list);
1580 }
1581 else {
1582 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001583 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001584 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001585 if (PyErr_Occurred())
1586 goto error;
1587 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001588 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001589 PyList_SetItem(list, j, line);
1590 }
1591 }
1592 if (j == 0)
1593 break;
1594
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001595 /* Check that all entries are indeed strings. If not,
1596 apply the same rules as for file.write() and
1597 convert the results to strings. This is slow, but
1598 seems to be the only way since all conversion APIs
1599 could potentially execute Python code. */
1600 for (i = 0; i < j; i++) {
1601 PyObject *v = PyList_GET_ITEM(list, i);
1602 if (!PyString_Check(v)) {
1603 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001604 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001605 PyObject_AsReadBuffer(v,
1606 (const void**)&buffer,
1607 &len)) ||
1608 PyObject_AsCharBuffer(v,
1609 &buffer,
1610 &len))) {
1611 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001612 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001613 goto error;
1614 }
1615 line = PyString_FromStringAndSize(buffer,
1616 len);
1617 if (line == NULL)
1618 goto error;
1619 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001620 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001621 }
1622 }
1623
1624 /* Since we are releasing the global lock, the
1625 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001626 Py_BEGIN_ALLOW_THREADS
Guido van Rossumee70ad12000-03-13 16:27:06 +00001627 errno = 0;
1628 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001629 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001630 len = PyString_GET_SIZE(line);
1631 nwritten = fwrite(PyString_AS_STRING(line),
1632 1, len, f->f_fp);
1633 if (nwritten != len) {
1634 Py_BLOCK_THREADS
1635 PyErr_SetFromErrno(PyExc_IOError);
1636 clearerr(f->f_fp);
1637 goto error;
1638 }
1639 }
1640 Py_END_ALLOW_THREADS
1641
1642 if (j < CHUNKSIZE)
1643 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001644 }
1645
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001646 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001647 result = Py_None;
1648 error:
1649 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001650 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001651 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001652#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001653}
1654
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001655static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001656file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001657{
1658 if (f->f_fp == NULL)
1659 return err_closed();
1660 Py_INCREF(f);
1661 return (PyObject *)f;
1662}
1663
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001664static PyObject *
1665file_exit(PyFileObject *f, PyObject *args)
1666{
1667 PyObject *ret = file_close(f);
1668 if (!ret)
1669 /* If error occurred, pass through */
1670 return NULL;
1671 Py_DECREF(ret);
1672 /* We cannot return the result of close since a true
1673 * value will be interpreted as "yes, swallow the
1674 * exception if one was raised inside the with block". */
1675 Py_RETURN_NONE;
1676}
1677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001678PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001679"readline([size]) -> next line from the file, as a string.\n"
1680"\n"
1681"Retain newline. A non-negative size argument limits the maximum\n"
1682"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001683"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001684
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001685PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001686"read([size]) -> read at most size bytes, returned as a string.\n"
1687"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001688"If the size argument is negative or omitted, read until EOF is reached.\n"
1689"Notice that when in non-blocking mode, less data than what was requested\n"
1690"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001692PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001693"write(str) -> None. Write string str to file.\n"
1694"\n"
1695"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001696"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001698PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001699"fileno() -> integer \"file descriptor\".\n"
1700"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001701"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001703PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001704"seek(offset[, whence]) -> None. Move to new file position.\n"
1705"\n"
1706"Argument offset is a byte count. Optional argument whence defaults to\n"
1707"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1708"(move relative to current position, positive or negative), and 2 (move\n"
1709"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001710"seeking beyond the end of a file). If the file is opened in text mode,\n"
1711"only offsets returned by tell() are legal. Use of other offsets causes\n"
1712"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001713"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001714"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001715
Guido van Rossumd7047b31995-01-02 19:07:15 +00001716#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001717PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001718"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1719"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001720"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001721#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001723PyDoc_STRVAR(tell_doc,
1724"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001726PyDoc_STRVAR(readinto_doc,
1727"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001729PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001730"readlines([size]) -> list of strings, each a line from the file.\n"
1731"\n"
1732"Call readline() repeatedly and return a list of the lines so read.\n"
1733"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001734"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001736PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001737"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001738"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001739"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001740"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001742PyDoc_STRVAR(flush_doc,
1743"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001745PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001746"close() -> None or (perhaps) an integer. Close the file.\n"
1747"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001748"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001749"further I/O operations. close() may be called more than once without\n"
1750"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001751"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753PyDoc_STRVAR(isatty_doc,
1754"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001755
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001756PyDoc_STRVAR(enter_doc,
1757 "__enter__() -> self.");
1758
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001759PyDoc_STRVAR(exit_doc,
1760 "__exit__(*excinfo) -> None. Closes the file.");
1761
Tim Petersefc3a3a2001-09-20 07:55:22 +00001762static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001763 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1764 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1765 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1766 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1767 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001768#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001769 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001770#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001771 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1772 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1773 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001774 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1775 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1776 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1777 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001778 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001779 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001780 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001781};
1782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001783#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001784
Guido van Rossum6f799372001-09-20 20:46:19 +00001785static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00001786 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001787 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001788 {"name", T_OBJECT, OFF(f_name), RO,
1789 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001790 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1791 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001792 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001793 {NULL} /* Sentinel */
1794};
1795
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001796static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001798{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001799 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001800}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001801static PyObject *
1802get_newlines(PyFileObject *f, void *closure)
1803{
1804 switch (f->f_newlinetypes) {
1805 case NEWLINE_UNKNOWN:
1806 Py_INCREF(Py_None);
1807 return Py_None;
1808 case NEWLINE_CR:
1809 return PyString_FromString("\r");
1810 case NEWLINE_LF:
1811 return PyString_FromString("\n");
1812 case NEWLINE_CR|NEWLINE_LF:
1813 return Py_BuildValue("(ss)", "\r", "\n");
1814 case NEWLINE_CRLF:
1815 return PyString_FromString("\r\n");
1816 case NEWLINE_CR|NEWLINE_CRLF:
1817 return Py_BuildValue("(ss)", "\r", "\r\n");
1818 case NEWLINE_LF|NEWLINE_CRLF:
1819 return Py_BuildValue("(ss)", "\n", "\r\n");
1820 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1821 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1822 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001823 PyErr_Format(PyExc_SystemError,
1824 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001825 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001826 return NULL;
1827 }
1828}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001829
Guido van Rossum32d34c82001-09-20 21:45:26 +00001830static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001831 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001832 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001833 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 {0},
1835};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001836
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001837static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001838drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001839{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001840 if (f->f_buf != NULL) {
1841 PyMem_Free(f->f_buf);
1842 f->f_buf = NULL;
1843 }
Guido van Rossum65967252001-04-21 13:20:18 +00001844}
1845
Tim Petersf1827cf2003-09-07 03:30:18 +00001846/* Make sure that file has a readahead buffer with at least one byte
1847 (unless at EOF) and no more than bufsize. Returns negative value on
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001848 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001849static int
1850readahead(PyFileObject *f, int bufsize)
1851{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001852 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001853
1854 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001855 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001856 return 0;
1857 else
1858 drop_readahead(f);
1859 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001860 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
1861 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001862 return -1;
1863 }
1864 Py_BEGIN_ALLOW_THREADS
1865 errno = 0;
1866 chunksize = Py_UniversalNewlineFread(
1867 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1868 Py_END_ALLOW_THREADS
1869 if (chunksize == 0) {
1870 if (ferror(f->f_fp)) {
1871 PyErr_SetFromErrno(PyExc_IOError);
1872 clearerr(f->f_fp);
1873 drop_readahead(f);
1874 return -1;
1875 }
1876 }
1877 f->f_bufptr = f->f_buf;
1878 f->f_bufend = f->f_buf + chunksize;
1879 return 0;
1880}
1881
1882/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001883 uninitialized bytes followed by the remainder of the line. Don't be
1884 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001885 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1886
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001887static PyStringObject *
1888readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1889{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001890 PyStringObject* s;
1891 char *bufptr;
1892 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001893 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001894
1895 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001896 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001897 return NULL;
1898
1899 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001900 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001901 return (PyStringObject *)
1902 PyString_FromStringAndSize(NULL, skip);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001903 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001904 if (bufptr != NULL) {
1905 bufptr++; /* Count the '\n' */
1906 len = bufptr - f->f_bufptr;
1907 s = (PyStringObject *)
1908 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001909 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001910 return NULL;
1911 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1912 f->f_bufptr = bufptr;
1913 if (bufptr == f->f_bufend)
1914 drop_readahead(f);
1915 } else {
1916 bufptr = f->f_bufptr;
1917 buf = f->f_buf;
1918 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001919 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001920 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001921 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001922 if (s == NULL) {
1923 PyMem_Free(buf);
1924 return NULL;
1925 }
1926 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1927 PyMem_Free(buf);
1928 }
1929 return s;
1930}
1931
1932/* A larger buffer size may actually decrease performance. */
1933#define READAHEAD_BUFSIZE 8192
1934
1935static PyObject *
1936file_iternext(PyFileObject *f)
1937{
1938 PyStringObject* l;
1939
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001940 if (f->f_fp == NULL)
1941 return err_closed();
1942
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001943 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1944 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1945 Py_XDECREF(l);
1946 return NULL;
1947 }
1948 return (PyObject *)l;
1949}
1950
1951
Tim Peters59c9a642001-09-13 05:38:56 +00001952static PyObject *
1953file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1954{
Tim Peters44410012001-09-14 03:26:08 +00001955 PyObject *self;
1956 static PyObject *not_yet_string;
1957
1958 assert(type != NULL && type->tp_alloc != NULL);
1959
1960 if (not_yet_string == NULL) {
1961 not_yet_string = PyString_FromString("<uninitialized file>");
1962 if (not_yet_string == NULL)
1963 return NULL;
1964 }
1965
1966 self = type->tp_alloc(type, 0);
1967 if (self != NULL) {
1968 /* Always fill in the name and mode, so that nobody else
1969 needs to special-case NULLs there. */
1970 Py_INCREF(not_yet_string);
1971 ((PyFileObject *)self)->f_name = not_yet_string;
1972 Py_INCREF(not_yet_string);
1973 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001974 Py_INCREF(Py_None);
1975 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001976 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001977 }
1978 return self;
1979}
1980
1981static int
1982file_init(PyObject *self, PyObject *args, PyObject *kwds)
1983{
1984 PyFileObject *foself = (PyFileObject *)self;
1985 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001986 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001987 char *name = NULL;
1988 char *mode = "r";
1989 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001990 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001991
1992 assert(PyFile_Check(self));
1993 if (foself->f_fp != NULL) {
1994 /* Have to close the existing file first. */
1995 PyObject *closeresult = file_close(foself);
1996 if (closeresult == NULL)
1997 return -1;
1998 Py_DECREF(closeresult);
1999 }
Tim Peters59c9a642001-09-13 05:38:56 +00002000
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002001#ifdef Py_WIN_WIDE_FILENAMES
2002 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2003 PyObject *po;
2004 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2005 kwlist, &po, &mode, &bufsize)) {
2006 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002007 if (fill_file_fields(foself, NULL, po, mode,
2008 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002009 goto Error;
2010 } else {
2011 /* Drop the argument parsing error as narrow
2012 strings are also valid. */
2013 PyErr_Clear();
2014 }
2015 }
2016#endif
2017
2018 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002019 PyObject *o_name;
2020
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002021 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2022 Py_FileSystemDefaultEncoding,
2023 &name,
2024 &mode, &bufsize))
2025 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002026
2027 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002028 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2029 kwlist, &o_name, &mode,
2030 &bufsize))
Thomas Wouters89f507f2006-12-13 04:49:30 +00002031 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002032
2033 if (fill_file_fields(foself, NULL, o_name, mode,
2034 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002035 goto Error;
2036 }
Tim Peters44410012001-09-14 03:26:08 +00002037 if (open_the_file(foself, name, mode) == NULL)
2038 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002039 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002040 PyFile_SetBufSize(self, bufsize);
2041 goto Done;
2042
2043Error:
2044 ret = -1;
2045 /* fall through */
2046Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002047 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002048 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002049}
2050
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002051PyDoc_VAR(file_doc) =
2052PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002053"file(name[, mode[, buffering]]) -> file object\n"
2054"\n"
2055"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2056"writing or appending. The file will be created if it doesn't exist\n"
2057"when opened for writing or appending; it will be truncated when\n"
2058"opened for writing. Add a 'b' to the mode for binary files.\n"
2059"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2060"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002061"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002062)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002063PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002064"Add a 'U' to mode to open the file for input with universal newline\n"
2065"support. Any line ending in the input file will be seen as a '\\n'\n"
2066"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2067"the value for this attribute is one of None (no newline read yet),\n"
2068"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2069"\n"
2070"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002071);
Tim Peters59c9a642001-09-13 05:38:56 +00002072
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073PyTypeObject PyFile_Type = {
2074 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002075 0,
2076 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002077 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002078 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002079 (destructor)file_dealloc, /* tp_dealloc */
2080 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002081 0, /* tp_getattr */
2082 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002083 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002085 0, /* tp_as_number */
2086 0, /* tp_as_sequence */
2087 0, /* tp_as_mapping */
2088 0, /* tp_hash */
2089 0, /* tp_call */
2090 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum79139b22007-02-09 23:20:19 +00002092 0, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002093 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002094 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002095 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002096 0, /* tp_traverse */
2097 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002098 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002099 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002100 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002101 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 file_methods, /* tp_methods */
2103 file_memberlist, /* tp_members */
2104 file_getsetlist, /* tp_getset */
2105 0, /* tp_base */
2106 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002107 0, /* tp_descr_get */
2108 0, /* tp_descr_set */
2109 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002110 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002111 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002112 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002113 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002114};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002115
Guido van Rossum3165fe61992-09-25 21:59:05 +00002116/* Interfaces to write objects/strings to file-like objects */
2117
2118int
Fred Drakefd99de62000-07-09 05:02:18 +00002119PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002120{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002121 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002122 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002123 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002124 return -1;
2125 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126 else if (PyFile_Check(f)) {
2127 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002128#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002129 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2130 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002131#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002132 if (fp == NULL) {
2133 err_closed();
2134 return -1;
2135 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002136#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002137 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002138 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002139 char *cenc = PyString_AS_STRING(enc);
2140 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2141 if (value == NULL)
2142 return -1;
2143 } else {
2144 value = v;
2145 Py_INCREF(value);
2146 }
2147 result = PyObject_Print(value, fp, flags);
2148 Py_DECREF(value);
2149 return result;
2150#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002152#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002153 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002154 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002155 if (writer == NULL)
2156 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002157 if (flags & Py_PRINT_RAW) {
2158 if (PyUnicode_Check(v)) {
2159 value = v;
2160 Py_INCREF(value);
2161 } else
2162 value = PyObject_Str(v);
2163 }
2164 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002165 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002166 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002168 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002169 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002170 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002171 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172 Py_DECREF(value);
2173 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002174 return -1;
2175 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002176 result = PyEval_CallObject(writer, args);
2177 Py_DECREF(args);
2178 Py_DECREF(value);
2179 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002180 if (result == NULL)
2181 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002182 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002183 return 0;
2184}
2185
Guido van Rossum27a60b11997-05-22 22:25:11 +00002186int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002187PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002188{
2189 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002190 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002191 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002192 PyErr_SetString(PyExc_SystemError,
2193 "null file for PyFile_WriteString");
2194 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002195 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196 else if (PyFile_Check(f)) {
2197 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002198 if (fp == NULL) {
2199 err_closed();
2200 return -1;
2201 }
2202 fputs(s, fp);
2203 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002204 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002205 else if (!PyErr_Occurred()) {
2206 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002207 int err;
2208 if (v == NULL)
2209 return -1;
2210 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2211 Py_DECREF(v);
2212 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002213 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002214 else
2215 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002216}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002217
2218/* Try to get a file-descriptor from a Python object. If the object
2219 is an integer or long integer, its value is returned. If not, the
2220 object's fileno() method is called if it exists; the method must return
2221 an integer or long integer, which is returned as the file descriptor value.
2222 -1 is returned on failure.
2223*/
2224
2225int PyObject_AsFileDescriptor(PyObject *o)
2226{
2227 int fd;
2228 PyObject *meth;
2229
2230 if (PyInt_Check(o)) {
2231 fd = PyInt_AsLong(o);
2232 }
2233 else if (PyLong_Check(o)) {
2234 fd = PyLong_AsLong(o);
2235 }
2236 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2237 {
2238 PyObject *fno = PyEval_CallObject(meth, NULL);
2239 Py_DECREF(meth);
2240 if (fno == NULL)
2241 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002242
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002243 if (PyInt_Check(fno)) {
2244 fd = PyInt_AsLong(fno);
2245 Py_DECREF(fno);
2246 }
2247 else if (PyLong_Check(fno)) {
2248 fd = PyLong_AsLong(fno);
2249 Py_DECREF(fno);
2250 }
2251 else {
2252 PyErr_SetString(PyExc_TypeError,
2253 "fileno() returned a non-integer");
2254 Py_DECREF(fno);
2255 return -1;
2256 }
2257 }
2258 else {
2259 PyErr_SetString(PyExc_TypeError,
2260 "argument must be an int, or have a fileno() method.");
2261 return -1;
2262 }
2263
Guido van Rossumddefaf32007-01-14 03:31:43 +00002264 if (fd == -1 && PyErr_Occurred())
2265 return -1;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002266 if (fd < 0) {
2267 PyErr_Format(PyExc_ValueError,
2268 "file descriptor cannot be a negative integer (%i)",
2269 fd);
2270 return -1;
2271 }
2272 return fd;
2273}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002274
Jack Jansen7b8c7542002-04-14 20:12:41 +00002275/* From here on we need access to the real fgets and fread */
2276#undef fgets
2277#undef fread
2278
2279/*
2280** Py_UniversalNewlineFgets is an fgets variation that understands
2281** all of \r, \n and \r\n conventions.
2282** The stream should be opened in binary mode.
2283** If fobj is NULL the routine always does newline conversion, and
2284** it may peek one char ahead to gobble the second char in \r\n.
2285** If fobj is non-NULL it must be a PyFileObject. In this case there
2286** is no readahead but in stead a flag is used to skip a following
2287** \n on the next read. Also, if the file is open in binary mode
2288** the whole conversion is skipped. Finally, the routine keeps track of
2289** the different types of newlines seen.
2290** Note that we need no error handling: fgets() treats error and eof
2291** identically.
2292*/
2293char *
2294Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2295{
2296 char *p = buf;
2297 int c;
2298 int newlinetypes = 0;
2299 int skipnextlf = 0;
2300 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002301
Jack Jansen7b8c7542002-04-14 20:12:41 +00002302 if (fobj) {
2303 if (!PyFile_Check(fobj)) {
2304 errno = ENXIO; /* What can you do... */
2305 return NULL;
2306 }
2307 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2308 if ( !univ_newline )
2309 return fgets(buf, n, stream);
2310 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2311 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2312 }
2313 FLOCKFILE(stream);
2314 c = 'x'; /* Shut up gcc warning */
2315 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2316 if (skipnextlf ) {
2317 skipnextlf = 0;
2318 if (c == '\n') {
2319 /* Seeing a \n here with skipnextlf true
2320 ** means we saw a \r before.
2321 */
2322 newlinetypes |= NEWLINE_CRLF;
2323 c = GETC(stream);
2324 if (c == EOF) break;
2325 } else {
2326 /*
2327 ** Note that c == EOF also brings us here,
2328 ** so we're okay if the last char in the file
2329 ** is a CR.
2330 */
2331 newlinetypes |= NEWLINE_CR;
2332 }
2333 }
2334 if (c == '\r') {
2335 /* A \r is translated into a \n, and we skip
2336 ** an adjacent \n, if any. We don't set the
2337 ** newlinetypes flag until we've seen the next char.
2338 */
2339 skipnextlf = 1;
2340 c = '\n';
2341 } else if ( c == '\n') {
2342 newlinetypes |= NEWLINE_LF;
2343 }
2344 *p++ = c;
2345 if (c == '\n') break;
2346 }
2347 if ( c == EOF && skipnextlf )
2348 newlinetypes |= NEWLINE_CR;
2349 FUNLOCKFILE(stream);
2350 *p = '\0';
2351 if (fobj) {
2352 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2353 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2354 } else if ( skipnextlf ) {
2355 /* If we have no file object we cannot save the
2356 ** skipnextlf flag. We have to readahead, which
2357 ** will cause a pause if we're reading from an
2358 ** interactive stream, but that is very unlikely
2359 ** unless we're doing something silly like
2360 ** execfile("/dev/tty").
2361 */
2362 c = GETC(stream);
2363 if ( c != '\n' )
2364 ungetc(c, stream);
2365 }
2366 if (p == buf)
2367 return NULL;
2368 return buf;
2369}
2370
2371/*
2372** Py_UniversalNewlineFread is an fread variation that understands
2373** all of \r, \n and \r\n conventions.
2374** The stream should be opened in binary mode.
2375** fobj must be a PyFileObject. In this case there
2376** is no readahead but in stead a flag is used to skip a following
2377** \n on the next read. Also, if the file is open in binary mode
2378** the whole conversion is skipped. Finally, the routine keeps track of
2379** the different types of newlines seen.
2380*/
2381size_t
Tim Peters058b1412002-04-21 07:29:14 +00002382Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002383 FILE *stream, PyObject *fobj)
2384{
Tim Peters058b1412002-04-21 07:29:14 +00002385 char *dst = buf;
2386 PyFileObject *f = (PyFileObject *)fobj;
2387 int newlinetypes, skipnextlf;
2388
2389 assert(buf != NULL);
2390 assert(stream != NULL);
2391
Jack Jansen7b8c7542002-04-14 20:12:41 +00002392 if (!fobj || !PyFile_Check(fobj)) {
2393 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002394 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002395 }
Tim Peters058b1412002-04-21 07:29:14 +00002396 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002397 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002398 newlinetypes = f->f_newlinetypes;
2399 skipnextlf = f->f_skipnextlf;
2400 /* Invariant: n is the number of bytes remaining to be filled
2401 * in the buffer.
2402 */
2403 while (n) {
2404 size_t nread;
2405 int shortread;
2406 char *src = dst;
2407
2408 nread = fread(dst, 1, n, stream);
2409 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002410 if (nread == 0)
2411 break;
2412
Tim Peterse1682a82002-04-21 18:15:20 +00002413 n -= nread; /* assuming 1 byte out for each in; will adjust */
2414 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002415 while (nread--) {
2416 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002417 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002418 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002419 *dst++ = '\n';
2420 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002421 }
2422 else if (skipnextlf && c == '\n') {
2423 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002424 skipnextlf = 0;
2425 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002426 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002427 }
2428 else {
2429 /* Normal char to be stored in buffer. Also
2430 * update the newlinetypes flag if either this
2431 * is an LF or the previous char was a CR.
2432 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002433 if (c == '\n')
2434 newlinetypes |= NEWLINE_LF;
2435 else if (skipnextlf)
2436 newlinetypes |= NEWLINE_CR;
2437 *dst++ = c;
2438 skipnextlf = 0;
2439 }
2440 }
Tim Peters058b1412002-04-21 07:29:14 +00002441 if (shortread) {
2442 /* If this is EOF, update type flags. */
2443 if (skipnextlf && feof(stream))
2444 newlinetypes |= NEWLINE_CR;
2445 break;
2446 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002447 }
Tim Peters058b1412002-04-21 07:29:14 +00002448 f->f_newlinetypes = newlinetypes;
2449 f->f_skipnextlf = skipnextlf;
2450 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002451}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002452
2453#ifdef __cplusplus
2454}
2455#endif