blob: ab2616dee4b433fc4269d3eab9b27e8e3d0ae93f [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
Guido van Rossumff7e83d1999-08-27 20:39:37 +00007#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00009#endif /* DONT_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{
Tim Peters59c9a642001-09-13 05:38:56 +0000106 assert(f != NULL);
107 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000108 assert(f->f_fp == NULL);
109
110 Py_DECREF(f->f_name);
111 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000112 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000113
114 Py_INCREF (name);
115 f->f_name = name;
116
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000118
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000119 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000120 f->f_softspace = 0;
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
Tim Peters59c9a642001-09-13 05:38:56 +0000129 if (f->f_name == NULL || 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
139 universal newline support is expressly forbidden by PEP 278. */
140/* zero return is kewl - one is un-kewl */
141static int
142check_the_mode(char *mode)
143{
Neal Norwitz76dc0812006-01-08 06:13:13 +0000144 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000145
146 switch (len) {
147 case 0:
148 PyErr_SetString(PyExc_ValueError, "empty mode string");
149 return 1;
150
151 /* reject wU, aU */
152 case 2:
153 switch (mode[0]) {
154 case 'w':
155 case 'a':
156 if (mode[1] == 'U') {
157 PyErr_SetString(PyExc_ValueError,
158 "invalid mode string");
159 return 1;
160 }
161 break;
162 }
163 break;
164
165 /* reject w+U, a+U, wU+, aU+ */
166 case 3:
167 switch (mode[0]) {
168 case 'w':
169 case 'a':
170 if ((mode[1] == '+' && mode[2] == 'U') ||
171 (mode[1] == 'U' && mode[2] == '+')) {
172 PyErr_SetString(PyExc_ValueError,
173 "invalid mode string");
174 return 1;
175 }
176 break;
177 }
178 break;
179 }
180
181 return 0;
182}
183
Tim Peters59c9a642001-09-13 05:38:56 +0000184static PyObject *
185open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
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
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000198 if (check_the_mode(mode))
199 return NULL;
200
Tim Peters8fa45672001-09-13 21:01:29 +0000201 /* rexec.py can't stop a user from getting the file() constructor --
202 all they have to do is get *any* file object f, and then do
203 type(f). Here we prevent them from doing damage with it. */
204 if (PyEval_GetRestricted()) {
205 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000206 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000207 return NULL;
208 }
Tim Petersa27a1502001-11-09 20:59:14 +0000209 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000210
211 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
212 mode = "rb";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000213#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000214 if (PyUnicode_Check(f->f_name)) {
215 PyObject *wmode;
216 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
217 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000218 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000219 /* PyUnicode_AS_UNICODE OK without thread
220 lock as it is a simple dereference. */
221 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
222 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000223 Py_END_ALLOW_THREADS
224 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000225 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000226 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000227#endif
228 if (NULL == f->f_fp && NULL != name) {
229 Py_BEGIN_ALLOW_THREADS
230 f->f_fp = fopen(name, mode);
231 Py_END_ALLOW_THREADS
232 }
233
Guido van Rossuma08095a1991-02-13 23:25:27 +0000234 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000235#ifdef _MSC_VER
236 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
237 * across all Windows flavors. When it sets EINVAL varies
238 * across Windows flavors, the exact conditions aren't
239 * documented, and the answer lies in the OS's implementation
240 * of Win32's CreateFile function (whose source is secret).
241 * Seems the best we can do is map EINVAL to ENOENT.
242 */
243 if (errno == 0) /* bad mode string */
244 errno = EINVAL;
245 else if (errno == EINVAL) /* unknown, but not a mode string */
246 errno = ENOENT;
247#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000248 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000249 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000250 mode);
251 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000252 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000253 f = NULL;
254 }
Tim Peters2ea91112002-04-08 04:13:12 +0000255 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000256 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000257 return (PyObject *)f;
258}
259
260PyObject *
261PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
262{
Tim Peters44410012001-09-14 03:26:08 +0000263 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
264 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000265 if (f != NULL) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000266 PyObject *o_name = PyString_FromString(name);
267 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000268 Py_DECREF(f);
269 f = NULL;
270 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000271 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000272 }
273 return (PyObject *) f;
274}
275
276PyObject *
277PyFile_FromString(char *name, char *mode)
278{
279 extern int fclose(FILE *);
280 PyFileObject *f;
281
282 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
283 if (f != NULL) {
284 if (open_the_file(f, name, mode) == NULL) {
285 Py_DECREF(f);
286 f = NULL;
287 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000289 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000290}
291
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292void
Fred Drakefd99de62000-07-09 05:02:18 +0000293PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000294{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000295 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000296 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297 int type;
298 switch (bufsize) {
299 case 0:
300 type = _IONBF;
301 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000302#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303 case 1:
304 type = _IOLBF;
305 bufsize = BUFSIZ;
306 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000307#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308 default:
309 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000310#ifndef HAVE_SETVBUF
311 bufsize = BUFSIZ;
312#endif
313 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000315 fflush(file->f_fp);
316 if (type == _IONBF) {
317 PyMem_Free(file->f_setbuf);
318 file->f_setbuf = NULL;
319 } else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
321 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000322 }
323#ifdef HAVE_SETVBUF
324 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000325#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000326 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000327#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000328 }
329}
330
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000331/* Set the encoding used to output Unicode strings.
332 Returh 1 on success, 0 on failure. */
333
334int
335PyFile_SetEncoding(PyObject *f, const char *enc)
336{
337 PyFileObject *file = (PyFileObject*)f;
338 PyObject *str = PyString_FromString(enc);
339 if (!str)
340 return 0;
341 Py_DECREF(file->f_encoding);
342 file->f_encoding = str;
343 return 1;
344}
345
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000346static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000347err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000348{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000349 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000350 return NULL;
351}
352
Thomas Woutersc45251a2006-02-12 11:53:32 +0000353/* Refuse regular file I/O if there's data in the iteration-buffer.
354 * Mixing them would cause data to arrive out of order, as the read*
355 * methods don't use the iteration buffer. */
356static PyObject *
357err_iterbuffered(void)
358{
359 PyErr_SetString(PyExc_ValueError,
360 "Mixing iteration and read methods would lose data");
361 return NULL;
362}
363
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000364static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000365
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366/* Methods */
367
368static void
Fred Drakefd99de62000-07-09 05:02:18 +0000369file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000371 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000372 if (f->weakreflist != NULL)
373 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000374 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000376 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000378 if (sts == EOF)
379#ifdef HAVE_STRERROR
380 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
381#else
382 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
383#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000384 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000385 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000386 Py_XDECREF(f->f_name);
387 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000388 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000389 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000390 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391}
392
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000394file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000396 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000397#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000398 PyObject *ret = NULL;
399 PyObject *name;
400 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
401 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
402 f->f_fp == NULL ? "closed" : "open",
403 PyString_AsString(name),
404 PyString_AsString(f->f_mode),
405 f);
406 Py_XDECREF(name);
407 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000408#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000409 } else {
410 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000411 f->f_fp == NULL ? "closed" : "open",
412 PyString_AsString(f->f_name),
413 PyString_AsString(f->f_mode),
414 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000415 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416}
417
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000419file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000420{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000421 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000423 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000425 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000426 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000427 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000428 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429 f->f_fp = NULL;
430 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000431 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000432 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000433 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000435 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436 return PyInt_FromLong((long)sts);
437 Py_INCREF(Py_None);
438 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439}
440
Trent Mickf29f47b2000-08-11 19:02:59 +0000441
Guido van Rossumb8552162001-09-05 14:58:11 +0000442/* Our very own off_t-like type, 64-bit if possible */
443#if !defined(HAVE_LARGEFILE_SUPPORT)
444typedef off_t Py_off_t;
445#elif SIZEOF_OFF_T >= 8
446typedef off_t Py_off_t;
447#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000448typedef fpos_t Py_off_t;
449#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000450#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000451#endif
452
453
Trent Mickf29f47b2000-08-11 19:02:59 +0000454/* a portable fseek() function
455 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000456static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000457_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000458{
Guido van Rossumb8552162001-09-05 14:58:11 +0000459#if !defined(HAVE_LARGEFILE_SUPPORT)
460 return fseek(fp, offset, whence);
461#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000462 return fseeko(fp, offset, whence);
463#elif defined(HAVE_FSEEK64)
464 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000465#elif defined(__BEOS__)
466 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000467#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000468 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
469 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000470 fpos_t pos;
471 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000472 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000473#ifdef MS_WINDOWS
474 fflush(fp);
475 if (_lseeki64(fileno(fp), 0, 2) == -1)
476 return -1;
477#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000478 if (fseek(fp, 0, SEEK_END) != 0)
479 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000480#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000481 /* fall through */
482 case SEEK_CUR:
483 if (fgetpos(fp, &pos) != 0)
484 return -1;
485 offset += pos;
486 break;
487 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000488 }
489 return fsetpos(fp, &offset);
490#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000491#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000492#endif
493}
494
495
496/* a portable ftell() function
497 Return -1 on failure with errno set appropriately, current file
498 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000499static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000500_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000501{
Guido van Rossumb8552162001-09-05 14:58:11 +0000502#if !defined(HAVE_LARGEFILE_SUPPORT)
503 return ftell(fp);
504#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
505 return ftello(fp);
506#elif defined(HAVE_FTELL64)
507 return ftell64(fp);
508#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000509 fpos_t pos;
510 if (fgetpos(fp, &pos) != 0)
511 return -1;
512 return pos;
513#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000514#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000515#endif
516}
517
518
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000520file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000522 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000523 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000524 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000525 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000526
Guido van Rossumd7297e61992-07-06 14:19:26 +0000527 if (f->f_fp == NULL)
528 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000529 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000530 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000531 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000532 return NULL;
533#if !defined(HAVE_LARGEFILE_SUPPORT)
534 offset = PyInt_AsLong(offobj);
535#else
536 offset = PyLong_Check(offobj) ?
537 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
538#endif
539 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000540 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000543 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000544 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000546
Guido van Rossumff4949e1992-08-05 19:58:53 +0000547 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000549 clearerr(f->f_fp);
550 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000551 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000552 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553 Py_INCREF(Py_None);
554 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000555}
556
Trent Mickf29f47b2000-08-11 19:02:59 +0000557
Guido van Rossumd7047b31995-01-02 19:07:15 +0000558#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000560file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000561{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000562 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000563 PyObject *newsizeobj = NULL;
564 Py_off_t initialpos;
565 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000566
Guido van Rossumd7047b31995-01-02 19:07:15 +0000567 if (f->f_fp == NULL)
568 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000569 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000570 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000571
Tim Petersf1827cf2003-09-07 03:30:18 +0000572 /* Get current file position. If the file happens to be open for
573 * update and the last operation was an input operation, C doesn't
574 * define what the later fflush() will do, but we promise truncate()
575 * won't change the current position (and fflush() *does* change it
576 * then at least on Windows). The easiest thing is to capture
577 * current pos now and seek back to it at the end.
578 */
579 Py_BEGIN_ALLOW_THREADS
580 errno = 0;
581 initialpos = _portable_ftell(f->f_fp);
582 Py_END_ALLOW_THREADS
583 if (initialpos == -1)
584 goto onioerror;
585
Tim Petersfb05db22002-03-11 00:24:00 +0000586 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000587 * specified value.
588 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000589 if (newsizeobj != NULL) {
590#if !defined(HAVE_LARGEFILE_SUPPORT)
591 newsize = PyInt_AsLong(newsizeobj);
592#else
593 newsize = PyLong_Check(newsizeobj) ?
594 PyLong_AsLongLong(newsizeobj) :
595 PyInt_AsLong(newsizeobj);
596#endif
597 if (PyErr_Occurred())
598 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000599 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000600 else /* default to current position */
601 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000602
Tim Petersf1827cf2003-09-07 03:30:18 +0000603 /* Flush the stream. We're mixing stream-level I/O with lower-level
604 * I/O, and a flush may be necessary to synch both platform views
605 * of the current file state.
606 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000608 errno = 0;
609 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000611 if (ret != 0)
612 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000613
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000614#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000615 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000616 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000617 {
Tim Petersfb05db22002-03-11 00:24:00 +0000618 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000619
Tim Petersf1827cf2003-09-07 03:30:18 +0000620 /* Have to move current pos to desired endpoint on Windows. */
621 Py_BEGIN_ALLOW_THREADS
622 errno = 0;
623 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
624 Py_END_ALLOW_THREADS
625 if (ret)
626 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000627
Tim Peters8f01b682002-03-12 03:04:44 +0000628 /* Truncate. Note that this may grow the file! */
629 Py_BEGIN_ALLOW_THREADS
630 errno = 0;
631 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000632 ret = hFile == (HANDLE)-1;
633 if (ret == 0) {
634 ret = SetEndOfFile(hFile) == 0;
635 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000636 errno = EACCES;
637 }
638 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000639 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000640 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000641 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000642#else
643 Py_BEGIN_ALLOW_THREADS
644 errno = 0;
645 ret = ftruncate(fileno(f->f_fp), newsize);
646 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000647 if (ret != 0)
648 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000649#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000650
Tim Petersf1827cf2003-09-07 03:30:18 +0000651 /* Restore original file position. */
652 Py_BEGIN_ALLOW_THREADS
653 errno = 0;
654 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
655 Py_END_ALLOW_THREADS
656 if (ret)
657 goto onioerror;
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659 Py_INCREF(Py_None);
660 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000661
662onioerror:
663 PyErr_SetFromErrno(PyExc_IOError);
664 clearerr(f->f_fp);
665 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000666}
667#endif /* HAVE_FTRUNCATE */
668
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000670file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000671{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000672 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000673
Guido van Rossumd7297e61992-07-06 14:19:26 +0000674 if (f->f_fp == NULL)
675 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000677 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000678 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000680 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000682 clearerr(f->f_fp);
683 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000684 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000685 if (f->f_skipnextlf) {
686 int c;
687 c = GETC(f->f_fp);
688 if (c == '\n') {
689 pos++;
690 f->f_skipnextlf = 0;
691 } else if (c != EOF) ungetc(c, f->f_fp);
692 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000693#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000694 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000695#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000696 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000697#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000698}
699
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000700static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000701file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000702{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000703 if (f->f_fp == NULL)
704 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000706}
707
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000709file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000710{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000711 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000712
Guido van Rossumd7297e61992-07-06 14:19:26 +0000713 if (f->f_fp == NULL)
714 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000715 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000716 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000717 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000719 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000720 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000721 clearerr(f->f_fp);
722 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000723 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 Py_INCREF(Py_None);
725 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000726}
727
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000729file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000730{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000731 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000732 if (f->f_fp == NULL)
733 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000734 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000735 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000737 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000738}
739
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000740
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000741#if BUFSIZ < 8192
742#define SMALLCHUNK 8192
743#else
744#define SMALLCHUNK BUFSIZ
745#endif
746
Guido van Rossum3c259041999-01-14 19:00:14 +0000747#if SIZEOF_INT < 4
748#define BIGCHUNK (512 * 32)
749#else
750#define BIGCHUNK (512 * 1024)
751#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000752
753static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000754new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000755{
756#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000757 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000758 struct stat st;
759 if (fstat(fileno(f->f_fp), &st) == 0) {
760 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000761 /* The following is not a bug: we really need to call lseek()
762 *and* ftell(). The reason is that some stdio libraries
763 mistakenly flush their buffer when ftell() is called and
764 the lseek() call it makes fails, thereby throwing away
765 data that cannot be recovered in any way. To avoid this,
766 we first test lseek(), and only call ftell() if lseek()
767 works. We can't use the lseek() value either, because we
768 need to take the amount of buffered data into account.
769 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000770 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000771 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000772 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000773 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000774 if (pos < 0)
775 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000776 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000777 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000778 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000779 }
780#endif
781 if (currentsize > SMALLCHUNK) {
782 /* Keep doubling until we reach BIGCHUNK;
783 then keep adding BIGCHUNK. */
784 if (currentsize <= BIGCHUNK)
785 return currentsize + currentsize;
786 else
787 return currentsize + BIGCHUNK;
788 }
789 return currentsize + SMALLCHUNK;
790}
791
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000792#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
793#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
794#else
795#ifdef EWOULDBLOCK
796#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
797#else
798#ifdef EAGAIN
799#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
800#else
801#define BLOCKED_ERRNO(x) 0
802#endif
803#endif
804#endif
805
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000807file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000808{
Guido van Rossum789a1611997-05-10 22:33:55 +0000809 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000810 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000812
Guido van Rossumd7297e61992-07-06 14:19:26 +0000813 if (f->f_fp == NULL)
814 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000815 /* refuse to mix with f.next() */
816 if (f->f_buf != NULL &&
817 (f->f_bufend - f->f_bufptr) > 0 &&
818 f->f_buf[0] != '\0')
819 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000820 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000821 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000822 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000823 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000824 else
825 buffersize = bytesrequested;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000827 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000828 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000829 return NULL;
830 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000831 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000832 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000834 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000835 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000836 Py_BEGIN_ALLOW_THREADS
837 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000838 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000839 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000840 Py_END_ALLOW_THREADS
841 if (chunksize == 0) {
842 if (!ferror(f->f_fp))
843 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000844 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000845 /* When in non-blocking mode, data shouldn't
846 * be discarded if a blocking signal was
847 * received. That will also happen if
848 * chunksize != 0, but bytesread < buffersize. */
849 if (bytesread > 0 && BLOCKED_ERRNO(errno))
850 break;
851 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000852 Py_DECREF(v);
853 return NULL;
854 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000855 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000856 if (bytesread < buffersize) {
857 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000858 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000859 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000860 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000861 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000862 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000863 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000864 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000865 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000866 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000867 }
868 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000869 if (bytesread != buffersize)
870 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000871 return v;
872}
873
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000874static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000875file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000876{
877 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000878 Py_ssize_t ntodo;
879 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000880
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000881 if (f->f_fp == NULL)
882 return err_closed();
Guido van Rossumd624f182006-04-24 13:47:05 +0000883 if (!f->f_binary) {
884 PyErr_SetString(PyExc_TypeError,
885 "readinto() requires binary mode");
886 return NULL;
887 }
Thomas Woutersc45251a2006-02-12 11:53:32 +0000888 /* refuse to mix with f.next() */
889 if (f->f_buf != NULL &&
890 (f->f_bufend - f->f_bufptr) > 0 &&
891 f->f_buf[0] != '\0')
892 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000893 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000894 return NULL;
895 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000896 while (ntodo > 0) {
897 Py_BEGIN_ALLOW_THREADS
898 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000899 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000900 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000901 Py_END_ALLOW_THREADS
902 if (nnow == 0) {
903 if (!ferror(f->f_fp))
904 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000905 PyErr_SetFromErrno(PyExc_IOError);
906 clearerr(f->f_fp);
907 return NULL;
908 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000909 ndone += nnow;
910 ntodo -= nnow;
911 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000912 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000913}
914
Tim Peters86821b22001-01-07 21:19:34 +0000915/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000916Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000917
918Under MSVC 6:
919
Tim Peters1c733232001-01-08 04:02:07 +0000920+ MS threadsafe getc is very slow (multiple layers of function calls before+
921 after each character, to lock+unlock the stream).
922+ The stream-locking functions are MS-internal -- can't access them from user
923 code.
924+ There's nothing Tim could find in the MS C or platform SDK libraries that
925 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000926+ MS fgets locks/unlocks only once per line; it's the only hook we have.
927
928So we use fgets for speed(!), despite that it's painful.
929
930MS realloc is also slow.
931
Tim Petersf29b64d2001-01-15 06:33:19 +0000932Reports from other platforms on this method vs getc_unlocked (which MS doesn't
933have):
934 Linux a wash
935 Solaris a wash
936 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000937
Tim Petersf29b64d2001-01-15 06:33:19 +0000938CAUTION: The C std isn't clear about this: in those cases where fgets
939writes something into the buffer, can it write into any position beyond the
940required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
941known on which it does; and it would be a strange way to code fgets. Still,
942getline_via_fgets may not work correctly if it does. The std test
943test_bufio.py should fail if platform fgets() routinely writes beyond the
944trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000945**************************************************************************/
946
Tim Petersf29b64d2001-01-15 06:33:19 +0000947/* Use this routine if told to, or by default on non-get_unlocked()
948 * platforms unless told not to. Yikes! Let's spell that out:
949 * On a platform with getc_unlocked():
950 * By default, use getc_unlocked().
951 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
952 * On a platform without getc_unlocked():
953 * By default, use fgets().
954 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
955 */
956#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
957#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000958#endif
959
Tim Petersf29b64d2001-01-15 06:33:19 +0000960#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
961#undef USE_FGETS_IN_GETLINE
962#endif
963
964#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000965static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000966getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000967{
Tim Peters15b83852001-01-08 00:53:12 +0000968/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000969 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
970 * to fill this much of the buffer with a known value in order to figure out
971 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
972 * than "most" lines, we waste time filling unused buffer slots. 100 is
973 * surely adequate for most peoples' email archives, chewing over source code,
974 * etc -- "regular old text files".
975 * MAXBUFSIZE is the maximum line length that lets us get away with the less
976 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
977 * cautions about boosting that. 300 was chosen because the worst real-life
978 * text-crunching job reported on Python-Dev was a mail-log crawler where over
979 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000980 */
Tim Peters142297a2001-01-15 10:36:56 +0000981#define INITBUFSIZE 100
982#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000983 char* p; /* temp */
984 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000985 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000986 char* pvfree; /* address of next free slot */
987 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000988 size_t nfree; /* # of free buffer slots; pvend-pvfree */
989 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000990 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000991
Tim Peters15b83852001-01-08 00:53:12 +0000992 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000993 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000994 */
Tim Peters142297a2001-01-15 10:36:56 +0000995 total_v_size = INITBUFSIZE; /* start small and pray */
996 pvfree = buf;
997 for (;;) {
998 Py_BEGIN_ALLOW_THREADS
999 pvend = buf + total_v_size;
1000 nfree = pvend - pvfree;
1001 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001002 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1003 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +00001004 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001005
Tim Peters142297a2001-01-15 10:36:56 +00001006 if (p == NULL) {
1007 clearerr(fp);
1008 if (PyErr_CheckSignals())
1009 return NULL;
1010 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001011 return v;
1012 }
Tim Peters142297a2001-01-15 10:36:56 +00001013 /* fgets read *something* */
1014 p = memchr(pvfree, '\n', nfree);
1015 if (p != NULL) {
1016 /* Did the \n come from fgets or from us?
1017 * Since fgets stops at the first \n, and then writes
1018 * \0, if it's from fgets a \0 must be next. But if
1019 * that's so, it could not have come from us, since
1020 * the \n's we filled the buffer with have only more
1021 * \n's to the right.
1022 */
1023 if (p+1 < pvend && *(p+1) == '\0') {
1024 /* It's from fgets: we win! In particular,
1025 * we haven't done any mallocs yet, and can
1026 * build the final result on the first try.
1027 */
1028 ++p; /* include \n from fgets */
1029 }
1030 else {
1031 /* Must be from us: fgets didn't fill the
1032 * buffer and didn't find a newline, so it
1033 * must be the last and newline-free line of
1034 * the file.
1035 */
1036 assert(p > pvfree && *(p-1) == '\0');
1037 --p; /* don't include \0 from fgets */
1038 }
1039 v = PyString_FromStringAndSize(buf, p - buf);
1040 return v;
1041 }
1042 /* yuck: fgets overwrote all the newlines, i.e. the entire
1043 * buffer. So this line isn't over yet, or maybe it is but
1044 * we're exactly at EOF. If we haven't already, try using the
1045 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001046 */
Tim Peters142297a2001-01-15 10:36:56 +00001047 assert(*(pvend-1) == '\0');
1048 if (pvfree == buf) {
1049 pvfree = pvend - 1; /* overwrite trailing null */
1050 total_v_size = MAXBUFSIZE;
1051 }
1052 else
1053 break;
Tim Peters86821b22001-01-07 21:19:34 +00001054 }
Tim Peters142297a2001-01-15 10:36:56 +00001055
1056 /* The stack buffer isn't big enough; malloc a string object and read
1057 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001058 */
Tim Petersddea2082002-03-23 10:03:50 +00001059 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001060 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001061 if (v == NULL)
1062 return v;
1063 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001064 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1065 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001066
1067 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001068 * after setting p one beyond the end of the line. The code here is
1069 * very much like the code above, except reads into v's buffer; see
1070 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001071 */
1072 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001073 Py_BEGIN_ALLOW_THREADS
1074 pvend = BUF(v) + total_v_size;
1075 nfree = pvend - pvfree;
1076 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001077 assert(nfree < INT_MAX);
1078 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001079 Py_END_ALLOW_THREADS
1080
1081 if (p == NULL) {
1082 clearerr(fp);
1083 if (PyErr_CheckSignals()) {
1084 Py_DECREF(v);
1085 return NULL;
1086 }
1087 p = pvfree;
1088 break;
1089 }
Tim Peters86821b22001-01-07 21:19:34 +00001090 p = memchr(pvfree, '\n', nfree);
1091 if (p != NULL) {
1092 if (p+1 < pvend && *(p+1) == '\0') {
1093 /* \n came from fgets */
1094 ++p;
1095 break;
1096 }
1097 /* \n came from us; last line of file, no newline */
1098 assert(p > pvfree && *(p-1) == '\0');
1099 --p;
1100 break;
1101 }
1102 /* expand buffer and try again */
1103 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001104 increment = total_v_size >> 2; /* mild exponential growth */
1105 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001106 if (total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001107 PyErr_SetString(PyExc_OverflowError,
1108 "line is longer than a Python string can hold");
1109 Py_DECREF(v);
1110 return NULL;
1111 }
1112 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1113 return NULL;
1114 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001115 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001116 }
1117 if (BUF(v) + total_v_size != p)
1118 _PyString_Resize(&v, p - BUF(v));
1119 return v;
1120#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001121#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001122}
Tim Petersf29b64d2001-01-15 06:33:19 +00001123#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001124
Guido van Rossum0bd24411991-04-04 15:21:57 +00001125/* Internal routine to get a line.
1126 Size argument interpretation:
1127 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001128 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001129*/
1130
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001131static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001132get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001133{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001134 FILE *fp = f->f_fp;
1135 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001136 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001137 size_t total_v_size; /* total # of slots in buffer */
1138 size_t used_v_size; /* # used slots in buffer */
1139 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001140 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001141 int newlinetypes = f->f_newlinetypes;
1142 int skipnextlf = f->f_skipnextlf;
1143 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001144
Jack Jansen7b8c7542002-04-14 20:12:41 +00001145#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001146 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001147 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001148#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001149 total_v_size = n > 0 ? n : 100;
1150 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001151 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001152 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001153 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001154 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001155
Guido van Rossumce5ba841991-03-06 13:06:18 +00001156 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001157 Py_BEGIN_ALLOW_THREADS
1158 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001159 if (univ_newline) {
1160 c = 'x'; /* Shut up gcc warning */
1161 while ( buf != end && (c = GETC(fp)) != EOF ) {
1162 if (skipnextlf ) {
1163 skipnextlf = 0;
1164 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001165 /* Seeing a \n here with
1166 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001167 * saw a \r before.
1168 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001169 newlinetypes |= NEWLINE_CRLF;
1170 c = GETC(fp);
1171 if (c == EOF) break;
1172 } else {
1173 newlinetypes |= NEWLINE_CR;
1174 }
1175 }
1176 if (c == '\r') {
1177 skipnextlf = 1;
1178 c = '\n';
1179 } else if ( c == '\n')
1180 newlinetypes |= NEWLINE_LF;
1181 *buf++ = c;
1182 if (c == '\n') break;
1183 }
1184 if ( c == EOF && skipnextlf )
1185 newlinetypes |= NEWLINE_CR;
1186 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001187 while ((c = GETC(fp)) != EOF &&
1188 (*buf++ = c) != '\n' &&
1189 buf != end)
1190 ;
1191 FUNLOCKFILE(fp);
1192 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001193 f->f_newlinetypes = newlinetypes;
1194 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001195 if (c == '\n')
1196 break;
1197 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001198 if (ferror(fp)) {
1199 PyErr_SetFromErrno(PyExc_IOError);
1200 clearerr(fp);
1201 Py_DECREF(v);
1202 return NULL;
1203 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001204 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001205 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001206 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001207 return NULL;
1208 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001209 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001210 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001211 /* Must be because buf == end */
1212 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001213 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001214 used_v_size = total_v_size;
1215 increment = total_v_size >> 2; /* mild exponential growth */
1216 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001218 PyErr_SetString(PyExc_OverflowError,
1219 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001220 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001221 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001222 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001223 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001224 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001225 buf = BUF(v) + used_v_size;
1226 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001227 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001228
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001229 used_v_size = buf - BUF(v);
1230 if (used_v_size != total_v_size)
1231 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001232 return v;
1233}
1234
Guido van Rossum0bd24411991-04-04 15:21:57 +00001235/* External C interface */
1236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001237PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001238PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001239{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001240 PyObject *result;
1241
Guido van Rossum3165fe61992-09-25 21:59:05 +00001242 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001243 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001244 return NULL;
1245 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001246
1247 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001248 PyFileObject *fo = (PyFileObject *)f;
1249 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001250 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001251 /* refuse to mix with f.next() */
1252 if (fo->f_buf != NULL &&
1253 (fo->f_bufend - fo->f_bufptr) > 0 &&
1254 fo->f_buf[0] != '\0')
1255 return err_iterbuffered();
1256 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001257 }
1258 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001259 PyObject *reader;
1260 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001261
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001262 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001263 if (reader == NULL)
1264 return NULL;
1265 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001266 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001267 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001268 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001269 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001270 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001271 return NULL;
1272 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001273 result = PyEval_CallObject(reader, args);
1274 Py_DECREF(reader);
1275 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001276 if (result != NULL && !PyString_Check(result) &&
1277 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001278 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001279 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001280 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001281 "object.readline() returned non-string");
1282 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001283 }
1284
1285 if (n < 0 && result != NULL && PyString_Check(result)) {
1286 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001288 if (len == 0) {
1289 Py_DECREF(result);
1290 result = NULL;
1291 PyErr_SetString(PyExc_EOFError,
1292 "EOF when reading a line");
1293 }
1294 else if (s[len-1] == '\n') {
1295 if (result->ob_refcnt == 1)
1296 _PyString_Resize(&result, len-1);
1297 else {
1298 PyObject *v;
1299 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001300 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001301 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001302 }
1303 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001304 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001305#ifdef Py_USING_UNICODE
1306 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1307 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001308 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001309 if (len == 0) {
1310 Py_DECREF(result);
1311 result = NULL;
1312 PyErr_SetString(PyExc_EOFError,
1313 "EOF when reading a line");
1314 }
1315 else if (s[len-1] == '\n') {
1316 if (result->ob_refcnt == 1)
1317 PyUnicode_Resize(&result, len-1);
1318 else {
1319 PyObject *v;
1320 v = PyUnicode_FromUnicode(s, len-1);
1321 Py_DECREF(result);
1322 result = v;
1323 }
1324 }
1325 }
1326#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001327 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001328}
1329
1330/* Python method */
1331
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001332static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001333file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001334{
Guido van Rossum789a1611997-05-10 22:33:55 +00001335 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001336
Guido van Rossumd7297e61992-07-06 14:19:26 +00001337 if (f->f_fp == NULL)
1338 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001339 /* refuse to mix with f.next() */
1340 if (f->f_buf != NULL &&
1341 (f->f_bufend - f->f_bufptr) > 0 &&
1342 f->f_buf[0] != '\0')
1343 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001344 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001345 return NULL;
1346 if (n == 0)
1347 return PyString_FromString("");
1348 if (n < 0)
1349 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001350 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001351}
1352
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001353static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001354file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001355{
Guido van Rossum789a1611997-05-10 22:33:55 +00001356 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357 PyObject *list;
1358 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001359 char small_buffer[SMALLCHUNK];
1360 char *buffer = small_buffer;
1361 size_t buffersize = SMALLCHUNK;
1362 PyObject *big_buffer = NULL;
1363 size_t nfilled = 0;
1364 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001365 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001366 char *p, *q, *end;
1367 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001368 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001369
Guido van Rossumd7297e61992-07-06 14:19:26 +00001370 if (f->f_fp == NULL)
1371 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001372 /* refuse to mix with f.next() */
1373 if (f->f_buf != NULL &&
1374 (f->f_bufend - f->f_bufptr) > 0 &&
1375 f->f_buf[0] != '\0')
1376 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001377 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001378 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001379 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001380 return NULL;
1381 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001382 if (shortread)
1383 nread = 0;
1384 else {
1385 Py_BEGIN_ALLOW_THREADS
1386 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001387 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001388 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001389 Py_END_ALLOW_THREADS
1390 shortread = (nread < buffersize-nfilled);
1391 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001392 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001393 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001394 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001395 break;
1396 PyErr_SetFromErrno(PyExc_IOError);
1397 clearerr(f->f_fp);
1398 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001399 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001400 list = NULL;
1401 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001402 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001403 totalread += nread;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001404 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001405 if (p == NULL) {
1406 /* Need a larger buffer to fit this line */
1407 nfilled += nread;
1408 buffersize *= 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001409 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001410 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001411 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001412 goto error;
1413 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001414 if (big_buffer == NULL) {
1415 /* Create the big buffer */
1416 big_buffer = PyString_FromStringAndSize(
1417 NULL, buffersize);
1418 if (big_buffer == NULL)
1419 goto error;
1420 buffer = PyString_AS_STRING(big_buffer);
1421 memcpy(buffer, small_buffer, nfilled);
1422 }
1423 else {
1424 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001425 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1426 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001427 buffer = PyString_AS_STRING(big_buffer);
1428 }
1429 continue;
1430 }
1431 end = buffer+nfilled+nread;
1432 q = buffer;
1433 do {
1434 /* Process complete lines */
1435 p++;
1436 line = PyString_FromStringAndSize(q, p-q);
1437 if (line == NULL)
1438 goto error;
1439 err = PyList_Append(list, line);
1440 Py_DECREF(line);
1441 if (err != 0)
1442 goto error;
1443 q = p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001444 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001445 } while (p != NULL);
1446 /* Move the remaining incomplete line to the start */
1447 nfilled = end-q;
1448 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001449 if (sizehint > 0)
1450 if (totalread >= (size_t)sizehint)
1451 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001452 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001453 if (nfilled != 0) {
1454 /* Partial last line */
1455 line = PyString_FromStringAndSize(buffer, nfilled);
1456 if (line == NULL)
1457 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001458 if (sizehint > 0) {
1459 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001460 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001461 if (rest == NULL) {
1462 Py_DECREF(line);
1463 goto error;
1464 }
1465 PyString_Concat(&line, rest);
1466 Py_DECREF(rest);
1467 if (line == NULL)
1468 goto error;
1469 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001470 err = PyList_Append(list, line);
1471 Py_DECREF(line);
1472 if (err != 0)
1473 goto error;
1474 }
1475 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001476 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001477 return list;
1478}
1479
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001480static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001481file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001482{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001483 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001484 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001485 if (f->f_fp == NULL)
1486 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001487 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001488 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001489 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001491 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001492 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001493 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001494 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001495 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001496 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001497 return NULL;
1498 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001499 Py_INCREF(Py_None);
1500 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001501}
1502
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001503static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001504file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001505{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001506#define CHUNKSIZE 1000
1507 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001508 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001509 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001510 int index, islist;
1511 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001512
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001513 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001514 if (f->f_fp == NULL)
1515 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001516
1517 result = NULL;
1518 list = NULL;
1519 islist = PyList_Check(seq);
1520 if (islist)
1521 it = NULL;
1522 else {
1523 it = PyObject_GetIter(seq);
1524 if (it == NULL) {
1525 PyErr_SetString(PyExc_TypeError,
1526 "writelines() requires an iterable argument");
1527 return NULL;
1528 }
1529 /* From here on, fail by going to error, to reclaim "it". */
1530 list = PyList_New(CHUNKSIZE);
1531 if (list == NULL)
1532 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001533 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001534
1535 /* Strategy: slurp CHUNKSIZE lines into a private list,
1536 checking that they are all strings, then write that list
1537 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001538 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539 if (islist) {
1540 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001541 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001542 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001543 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001544 j = PyList_GET_SIZE(list);
1545 }
1546 else {
1547 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001548 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001549 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001550 if (PyErr_Occurred())
1551 goto error;
1552 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001553 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001554 PyList_SetItem(list, j, line);
1555 }
1556 }
1557 if (j == 0)
1558 break;
1559
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001560 /* Check that all entries are indeed strings. If not,
1561 apply the same rules as for file.write() and
1562 convert the results to strings. This is slow, but
1563 seems to be the only way since all conversion APIs
1564 could potentially execute Python code. */
1565 for (i = 0; i < j; i++) {
1566 PyObject *v = PyList_GET_ITEM(list, i);
1567 if (!PyString_Check(v)) {
1568 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001569 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001570 PyObject_AsReadBuffer(v,
1571 (const void**)&buffer,
1572 &len)) ||
1573 PyObject_AsCharBuffer(v,
1574 &buffer,
1575 &len))) {
1576 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001577 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001578 goto error;
1579 }
1580 line = PyString_FromStringAndSize(buffer,
1581 len);
1582 if (line == NULL)
1583 goto error;
1584 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001585 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001586 }
1587 }
1588
1589 /* Since we are releasing the global lock, the
1590 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001591 Py_BEGIN_ALLOW_THREADS
1592 f->f_softspace = 0;
1593 errno = 0;
1594 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001595 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001596 len = PyString_GET_SIZE(line);
1597 nwritten = fwrite(PyString_AS_STRING(line),
1598 1, len, f->f_fp);
1599 if (nwritten != len) {
1600 Py_BLOCK_THREADS
1601 PyErr_SetFromErrno(PyExc_IOError);
1602 clearerr(f->f_fp);
1603 goto error;
1604 }
1605 }
1606 Py_END_ALLOW_THREADS
1607
1608 if (j < CHUNKSIZE)
1609 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001610 }
1611
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001612 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001613 result = Py_None;
1614 error:
1615 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001616 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001617 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001618#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001619}
1620
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001621static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001622file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001623{
1624 if (f->f_fp == NULL)
1625 return err_closed();
1626 Py_INCREF(f);
1627 return (PyObject *)f;
1628}
1629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001630PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001631"readline([size]) -> next line from the file, as a string.\n"
1632"\n"
1633"Retain newline. A non-negative size argument limits the maximum\n"
1634"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001636
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001637PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001638"read([size]) -> read at most size bytes, returned as a string.\n"
1639"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001640"If the size argument is negative or omitted, read until EOF is reached.\n"
1641"Notice that when in non-blocking mode, less data than what was requested\n"
1642"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001644PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001645"write(str) -> None. Write string str to file.\n"
1646"\n"
1647"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001648"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001650PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001651"fileno() -> integer \"file descriptor\".\n"
1652"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001653"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001654
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001655PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001656"seek(offset[, whence]) -> None. Move to new file position.\n"
1657"\n"
1658"Argument offset is a byte count. Optional argument whence defaults to\n"
1659"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1660"(move relative to current position, positive or negative), and 2 (move\n"
1661"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001662"seeking beyond the end of a file). If the file is opened in text mode,\n"
1663"only offsets returned by tell() are legal. Use of other offsets causes\n"
1664"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001665"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001666"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001667
Guido van Rossumd7047b31995-01-02 19:07:15 +00001668#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001669PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001670"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1671"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001672"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001673#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001674
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001675PyDoc_STRVAR(tell_doc,
1676"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001678PyDoc_STRVAR(readinto_doc,
1679"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001681PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001682"readlines([size]) -> list of strings, each a line from the file.\n"
1683"\n"
1684"Call readline() repeatedly and return a list of the lines so read.\n"
1685"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001686"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001687
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001688PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001689"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001690"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001691"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001692"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001694PyDoc_STRVAR(flush_doc,
1695"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001697PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001698"close() -> None or (perhaps) an integer. Close the file.\n"
1699"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001700"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001701"further I/O operations. close() may be called more than once without\n"
1702"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001703"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001705PyDoc_STRVAR(isatty_doc,
1706"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001707
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001708PyDoc_STRVAR(context_doc,
1709 "__context__() -> self.");
1710
1711PyDoc_STRVAR(enter_doc,
1712 "__enter__() -> self.");
1713
Tim Petersefc3a3a2001-09-20 07:55:22 +00001714static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001715 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1716 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1717 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1718 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1719 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001720#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001721 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001722#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001723 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1724 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1725 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001726 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1727 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1728 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1729 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001730 {"__context__", (PyCFunction)file_self, METH_NOARGS, context_doc},
1731 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Guido van Rossumf6694362006-03-10 02:28:35 +00001732 {"__exit__", (PyCFunction)file_close, METH_VARARGS, close_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001733 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001734};
1735
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001736#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001737
Guido van Rossum6f799372001-09-20 20:46:19 +00001738static PyMemberDef file_memberlist[] = {
1739 {"softspace", T_INT, OFF(f_softspace), 0,
1740 "flag indicating that a space needs to be printed; used by print"},
1741 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001742 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001743 {"name", T_OBJECT, OFF(f_name), RO,
1744 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001745 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1746 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001747 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001748 {NULL} /* Sentinel */
1749};
1750
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001751static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001753{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001754 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001755}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001756static PyObject *
1757get_newlines(PyFileObject *f, void *closure)
1758{
1759 switch (f->f_newlinetypes) {
1760 case NEWLINE_UNKNOWN:
1761 Py_INCREF(Py_None);
1762 return Py_None;
1763 case NEWLINE_CR:
1764 return PyString_FromString("\r");
1765 case NEWLINE_LF:
1766 return PyString_FromString("\n");
1767 case NEWLINE_CR|NEWLINE_LF:
1768 return Py_BuildValue("(ss)", "\r", "\n");
1769 case NEWLINE_CRLF:
1770 return PyString_FromString("\r\n");
1771 case NEWLINE_CR|NEWLINE_CRLF:
1772 return Py_BuildValue("(ss)", "\r", "\r\n");
1773 case NEWLINE_LF|NEWLINE_CRLF:
1774 return Py_BuildValue("(ss)", "\n", "\r\n");
1775 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1776 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1777 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001778 PyErr_Format(PyExc_SystemError,
1779 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001780 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001781 return NULL;
1782 }
1783}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001784
Guido van Rossum32d34c82001-09-20 21:45:26 +00001785static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001786 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001787 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001788 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789 {0},
1790};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001791
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001792static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001793drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001794{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001795 if (f->f_buf != NULL) {
1796 PyMem_Free(f->f_buf);
1797 f->f_buf = NULL;
1798 }
Guido van Rossum65967252001-04-21 13:20:18 +00001799}
1800
Tim Petersf1827cf2003-09-07 03:30:18 +00001801/* Make sure that file has a readahead buffer with at least one byte
1802 (unless at EOF) and no more than bufsize. Returns negative value on
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001803 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001804static int
1805readahead(PyFileObject *f, int bufsize)
1806{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001807 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001808
1809 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001810 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001811 return 0;
1812 else
1813 drop_readahead(f);
1814 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001815 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
1816 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001817 return -1;
1818 }
1819 Py_BEGIN_ALLOW_THREADS
1820 errno = 0;
1821 chunksize = Py_UniversalNewlineFread(
1822 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1823 Py_END_ALLOW_THREADS
1824 if (chunksize == 0) {
1825 if (ferror(f->f_fp)) {
1826 PyErr_SetFromErrno(PyExc_IOError);
1827 clearerr(f->f_fp);
1828 drop_readahead(f);
1829 return -1;
1830 }
1831 }
1832 f->f_bufptr = f->f_buf;
1833 f->f_bufend = f->f_buf + chunksize;
1834 return 0;
1835}
1836
1837/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001838 uninitialized bytes followed by the remainder of the line. Don't be
1839 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001840 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1841
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001842static PyStringObject *
1843readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1844{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001845 PyStringObject* s;
1846 char *bufptr;
1847 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001848 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001849
1850 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001851 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001852 return NULL;
1853
1854 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001855 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001856 return (PyStringObject *)
1857 PyString_FromStringAndSize(NULL, skip);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001858 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001859 if (bufptr != NULL) {
1860 bufptr++; /* Count the '\n' */
1861 len = bufptr - f->f_bufptr;
1862 s = (PyStringObject *)
1863 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001864 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001865 return NULL;
1866 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1867 f->f_bufptr = bufptr;
1868 if (bufptr == f->f_bufend)
1869 drop_readahead(f);
1870 } else {
1871 bufptr = f->f_bufptr;
1872 buf = f->f_buf;
1873 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001874 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001875 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001876 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001877 if (s == NULL) {
1878 PyMem_Free(buf);
1879 return NULL;
1880 }
1881 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1882 PyMem_Free(buf);
1883 }
1884 return s;
1885}
1886
1887/* A larger buffer size may actually decrease performance. */
1888#define READAHEAD_BUFSIZE 8192
1889
1890static PyObject *
1891file_iternext(PyFileObject *f)
1892{
1893 PyStringObject* l;
1894
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001895 if (f->f_fp == NULL)
1896 return err_closed();
1897
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001898 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1899 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1900 Py_XDECREF(l);
1901 return NULL;
1902 }
1903 return (PyObject *)l;
1904}
1905
1906
Tim Peters59c9a642001-09-13 05:38:56 +00001907static PyObject *
1908file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1909{
Tim Peters44410012001-09-14 03:26:08 +00001910 PyObject *self;
1911 static PyObject *not_yet_string;
1912
1913 assert(type != NULL && type->tp_alloc != NULL);
1914
1915 if (not_yet_string == NULL) {
1916 not_yet_string = PyString_FromString("<uninitialized file>");
1917 if (not_yet_string == NULL)
1918 return NULL;
1919 }
1920
1921 self = type->tp_alloc(type, 0);
1922 if (self != NULL) {
1923 /* Always fill in the name and mode, so that nobody else
1924 needs to special-case NULLs there. */
1925 Py_INCREF(not_yet_string);
1926 ((PyFileObject *)self)->f_name = not_yet_string;
1927 Py_INCREF(not_yet_string);
1928 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001929 Py_INCREF(Py_None);
1930 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001931 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001932 }
1933 return self;
1934}
1935
1936static int
1937file_init(PyObject *self, PyObject *args, PyObject *kwds)
1938{
1939 PyFileObject *foself = (PyFileObject *)self;
1940 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001941 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001942 char *name = NULL;
1943 char *mode = "r";
1944 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001945 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001946
1947 assert(PyFile_Check(self));
1948 if (foself->f_fp != NULL) {
1949 /* Have to close the existing file first. */
1950 PyObject *closeresult = file_close(foself);
1951 if (closeresult == NULL)
1952 return -1;
1953 Py_DECREF(closeresult);
1954 }
Tim Peters59c9a642001-09-13 05:38:56 +00001955
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001956#ifdef Py_WIN_WIDE_FILENAMES
1957 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1958 PyObject *po;
1959 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1960 kwlist, &po, &mode, &bufsize)) {
1961 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001962 if (fill_file_fields(foself, NULL, po, mode,
1963 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001964 goto Error;
1965 } else {
1966 /* Drop the argument parsing error as narrow
1967 strings are also valid. */
1968 PyErr_Clear();
1969 }
1970 }
1971#endif
1972
1973 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001974 PyObject *o_name;
1975
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001976 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1977 Py_FileSystemDefaultEncoding,
1978 &name,
1979 &mode, &bufsize))
1980 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001981
1982 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001983 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1984 kwlist, &o_name, &mode,
1985 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001986 return -1;
1987
1988 if (fill_file_fields(foself, NULL, o_name, mode,
1989 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001990 goto Error;
1991 }
Tim Peters44410012001-09-14 03:26:08 +00001992 if (open_the_file(foself, name, mode) == NULL)
1993 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001994 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001995 PyFile_SetBufSize(self, bufsize);
1996 goto Done;
1997
1998Error:
1999 ret = -1;
2000 /* fall through */
2001Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002002 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002003 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002004}
2005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002006PyDoc_VAR(file_doc) =
2007PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002008"file(name[, mode[, buffering]]) -> file object\n"
2009"\n"
2010"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2011"writing or appending. The file will be created if it doesn't exist\n"
2012"when opened for writing or appending; it will be truncated when\n"
2013"opened for writing. Add a 'b' to the mode for binary files.\n"
2014"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2015"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002016"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002017)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002018PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002019"Add a 'U' to mode to open the file for input with universal newline\n"
2020"support. Any line ending in the input file will be seen as a '\\n'\n"
2021"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2022"the value for this attribute is one of None (no newline read yet),\n"
2023"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2024"\n"
2025"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002026)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002028"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002029"Note: open() is an alias for file()."
2030);
Tim Peters59c9a642001-09-13 05:38:56 +00002031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002032PyTypeObject PyFile_Type = {
2033 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002034 0,
2035 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002036 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002037 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002038 (destructor)file_dealloc, /* tp_dealloc */
2039 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 0, /* tp_getattr */
2041 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002042 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002044 0, /* tp_as_number */
2045 0, /* tp_as_sequence */
2046 0, /* tp_as_mapping */
2047 0, /* tp_hash */
2048 0, /* tp_call */
2049 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002051 /* softspace is writable: we must supply tp_setattro */
2052 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002053 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002054 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002055 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 0, /* tp_traverse */
2057 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002058 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002059 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002060 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002061 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062 file_methods, /* tp_methods */
2063 file_memberlist, /* tp_members */
2064 file_getsetlist, /* tp_getset */
2065 0, /* tp_base */
2066 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002067 0, /* tp_descr_get */
2068 0, /* tp_descr_set */
2069 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002070 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002071 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002072 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002073 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002074};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002075
2076/* Interface for the 'soft space' between print items. */
2077
2078int
Fred Drakefd99de62000-07-09 05:02:18 +00002079PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002080{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002081 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002082 if (f == NULL) {
2083 /* Do nothing */
2084 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002085 else if (PyFile_Check(f)) {
2086 oldflag = ((PyFileObject *)f)->f_softspace;
2087 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002088 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002089 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002090 PyObject *v;
2091 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002092 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002094 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002095 if (PyInt_Check(v))
2096 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002097 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002099 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002101 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002103 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002104 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2105 PyErr_Clear();
2106 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002107 }
2108 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002109 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002110}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002111
2112/* Interfaces to write objects/strings to file-like objects */
2113
2114int
Fred Drakefd99de62000-07-09 05:02:18 +00002115PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002116{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002118 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002119 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002120 return -1;
2121 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 else if (PyFile_Check(f)) {
2123 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002124#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002125 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2126 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002127#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002128 if (fp == NULL) {
2129 err_closed();
2130 return -1;
2131 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002132#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002133 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002134 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002135 char *cenc = PyString_AS_STRING(enc);
2136 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2137 if (value == NULL)
2138 return -1;
2139 } else {
2140 value = v;
2141 Py_INCREF(value);
2142 }
2143 result = PyObject_Print(value, fp, flags);
2144 Py_DECREF(value);
2145 return result;
2146#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002147 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002148#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002149 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002151 if (writer == NULL)
2152 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002153 if (flags & Py_PRINT_RAW) {
2154 if (PyUnicode_Check(v)) {
2155 value = v;
2156 Py_INCREF(value);
2157 } else
2158 value = PyObject_Str(v);
2159 }
2160 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002162 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002163 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002164 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002165 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002166 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002167 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002168 Py_DECREF(value);
2169 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002170 return -1;
2171 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172 result = PyEval_CallObject(writer, args);
2173 Py_DECREF(args);
2174 Py_DECREF(value);
2175 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002176 if (result == NULL)
2177 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002178 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002179 return 0;
2180}
2181
Guido van Rossum27a60b11997-05-22 22:25:11 +00002182int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002183PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002184{
2185 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002186 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002187 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002188 PyErr_SetString(PyExc_SystemError,
2189 "null file for PyFile_WriteString");
2190 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002191 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192 else if (PyFile_Check(f)) {
2193 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002194 if (fp == NULL) {
2195 err_closed();
2196 return -1;
2197 }
2198 fputs(s, fp);
2199 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002200 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201 else if (!PyErr_Occurred()) {
2202 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002203 int err;
2204 if (v == NULL)
2205 return -1;
2206 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2207 Py_DECREF(v);
2208 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002209 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002210 else
2211 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002212}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002213
2214/* Try to get a file-descriptor from a Python object. If the object
2215 is an integer or long integer, its value is returned. If not, the
2216 object's fileno() method is called if it exists; the method must return
2217 an integer or long integer, which is returned as the file descriptor value.
2218 -1 is returned on failure.
2219*/
2220
2221int PyObject_AsFileDescriptor(PyObject *o)
2222{
2223 int fd;
2224 PyObject *meth;
2225
2226 if (PyInt_Check(o)) {
2227 fd = PyInt_AsLong(o);
2228 }
2229 else if (PyLong_Check(o)) {
2230 fd = PyLong_AsLong(o);
2231 }
2232 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2233 {
2234 PyObject *fno = PyEval_CallObject(meth, NULL);
2235 Py_DECREF(meth);
2236 if (fno == NULL)
2237 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002238
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002239 if (PyInt_Check(fno)) {
2240 fd = PyInt_AsLong(fno);
2241 Py_DECREF(fno);
2242 }
2243 else if (PyLong_Check(fno)) {
2244 fd = PyLong_AsLong(fno);
2245 Py_DECREF(fno);
2246 }
2247 else {
2248 PyErr_SetString(PyExc_TypeError,
2249 "fileno() returned a non-integer");
2250 Py_DECREF(fno);
2251 return -1;
2252 }
2253 }
2254 else {
2255 PyErr_SetString(PyExc_TypeError,
2256 "argument must be an int, or have a fileno() method.");
2257 return -1;
2258 }
2259
2260 if (fd < 0) {
2261 PyErr_Format(PyExc_ValueError,
2262 "file descriptor cannot be a negative integer (%i)",
2263 fd);
2264 return -1;
2265 }
2266 return fd;
2267}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002268
Jack Jansen7b8c7542002-04-14 20:12:41 +00002269/* From here on we need access to the real fgets and fread */
2270#undef fgets
2271#undef fread
2272
2273/*
2274** Py_UniversalNewlineFgets is an fgets variation that understands
2275** all of \r, \n and \r\n conventions.
2276** The stream should be opened in binary mode.
2277** If fobj is NULL the routine always does newline conversion, and
2278** it may peek one char ahead to gobble the second char in \r\n.
2279** If fobj is non-NULL it must be a PyFileObject. In this case there
2280** is no readahead but in stead a flag is used to skip a following
2281** \n on the next read. Also, if the file is open in binary mode
2282** the whole conversion is skipped. Finally, the routine keeps track of
2283** the different types of newlines seen.
2284** Note that we need no error handling: fgets() treats error and eof
2285** identically.
2286*/
2287char *
2288Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2289{
2290 char *p = buf;
2291 int c;
2292 int newlinetypes = 0;
2293 int skipnextlf = 0;
2294 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002295
Jack Jansen7b8c7542002-04-14 20:12:41 +00002296 if (fobj) {
2297 if (!PyFile_Check(fobj)) {
2298 errno = ENXIO; /* What can you do... */
2299 return NULL;
2300 }
2301 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2302 if ( !univ_newline )
2303 return fgets(buf, n, stream);
2304 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2305 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2306 }
2307 FLOCKFILE(stream);
2308 c = 'x'; /* Shut up gcc warning */
2309 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2310 if (skipnextlf ) {
2311 skipnextlf = 0;
2312 if (c == '\n') {
2313 /* Seeing a \n here with skipnextlf true
2314 ** means we saw a \r before.
2315 */
2316 newlinetypes |= NEWLINE_CRLF;
2317 c = GETC(stream);
2318 if (c == EOF) break;
2319 } else {
2320 /*
2321 ** Note that c == EOF also brings us here,
2322 ** so we're okay if the last char in the file
2323 ** is a CR.
2324 */
2325 newlinetypes |= NEWLINE_CR;
2326 }
2327 }
2328 if (c == '\r') {
2329 /* A \r is translated into a \n, and we skip
2330 ** an adjacent \n, if any. We don't set the
2331 ** newlinetypes flag until we've seen the next char.
2332 */
2333 skipnextlf = 1;
2334 c = '\n';
2335 } else if ( c == '\n') {
2336 newlinetypes |= NEWLINE_LF;
2337 }
2338 *p++ = c;
2339 if (c == '\n') break;
2340 }
2341 if ( c == EOF && skipnextlf )
2342 newlinetypes |= NEWLINE_CR;
2343 FUNLOCKFILE(stream);
2344 *p = '\0';
2345 if (fobj) {
2346 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2347 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2348 } else if ( skipnextlf ) {
2349 /* If we have no file object we cannot save the
2350 ** skipnextlf flag. We have to readahead, which
2351 ** will cause a pause if we're reading from an
2352 ** interactive stream, but that is very unlikely
2353 ** unless we're doing something silly like
2354 ** execfile("/dev/tty").
2355 */
2356 c = GETC(stream);
2357 if ( c != '\n' )
2358 ungetc(c, stream);
2359 }
2360 if (p == buf)
2361 return NULL;
2362 return buf;
2363}
2364
2365/*
2366** Py_UniversalNewlineFread is an fread variation that understands
2367** all of \r, \n and \r\n conventions.
2368** The stream should be opened in binary mode.
2369** fobj must be a PyFileObject. In this case there
2370** is no readahead but in stead a flag is used to skip a following
2371** \n on the next read. Also, if the file is open in binary mode
2372** the whole conversion is skipped. Finally, the routine keeps track of
2373** the different types of newlines seen.
2374*/
2375size_t
Tim Peters058b1412002-04-21 07:29:14 +00002376Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002377 FILE *stream, PyObject *fobj)
2378{
Tim Peters058b1412002-04-21 07:29:14 +00002379 char *dst = buf;
2380 PyFileObject *f = (PyFileObject *)fobj;
2381 int newlinetypes, skipnextlf;
2382
2383 assert(buf != NULL);
2384 assert(stream != NULL);
2385
Jack Jansen7b8c7542002-04-14 20:12:41 +00002386 if (!fobj || !PyFile_Check(fobj)) {
2387 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002388 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002389 }
Tim Peters058b1412002-04-21 07:29:14 +00002390 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002391 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002392 newlinetypes = f->f_newlinetypes;
2393 skipnextlf = f->f_skipnextlf;
2394 /* Invariant: n is the number of bytes remaining to be filled
2395 * in the buffer.
2396 */
2397 while (n) {
2398 size_t nread;
2399 int shortread;
2400 char *src = dst;
2401
2402 nread = fread(dst, 1, n, stream);
2403 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002404 if (nread == 0)
2405 break;
2406
Tim Peterse1682a82002-04-21 18:15:20 +00002407 n -= nread; /* assuming 1 byte out for each in; will adjust */
2408 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002409 while (nread--) {
2410 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002411 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002412 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002413 *dst++ = '\n';
2414 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002415 }
2416 else if (skipnextlf && c == '\n') {
2417 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002418 skipnextlf = 0;
2419 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002420 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002421 }
2422 else {
2423 /* Normal char to be stored in buffer. Also
2424 * update the newlinetypes flag if either this
2425 * is an LF or the previous char was a CR.
2426 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002427 if (c == '\n')
2428 newlinetypes |= NEWLINE_LF;
2429 else if (skipnextlf)
2430 newlinetypes |= NEWLINE_CR;
2431 *dst++ = c;
2432 skipnextlf = 0;
2433 }
2434 }
Tim Peters058b1412002-04-21 07:29:14 +00002435 if (shortread) {
2436 /* If this is EOF, update type flags. */
2437 if (skipnextlf && feof(stream))
2438 newlinetypes |= NEWLINE_CR;
2439 break;
2440 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002441 }
Tim Peters058b1412002-04-21 07:29:14 +00002442 f->f_newlinetypes = newlinetypes;
2443 f->f_skipnextlf = skipnextlf;
2444 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002445}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002446
2447#ifdef __cplusplus
2448}
2449#endif
2450