blob: 20e71a30be0d454b74fe1a0238b06f731bd22681 [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
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000052PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000054 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000056 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000057 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058}
59
Guido van Rossumc0b618a1997-05-02 03:12:38 +000060PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000061PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000062{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000063 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000064 return NULL;
65 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000067}
68
Neil Schemenauered19b882002-03-23 02:06:50 +000069/* On Unix, fopen will succeed for directories.
70 In Python, there should be no file objects referring to
71 directories, so we need a check. */
72
73static PyFileObject*
74dircheck(PyFileObject* f)
75{
76#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
77 struct stat buf;
78 if (f->f_fp == NULL)
79 return f;
80 if (fstat(fileno(f->f_fp), &buf) == 0 &&
81 S_ISDIR(buf.st_mode)) {
82#ifdef HAVE_STRERROR
83 char *msg = strerror(EISDIR);
84#else
85 char *msg = "Is a directory";
86#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000087 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000088 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000089 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000090 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000091 return NULL;
92 }
93#endif
94 return f;
95}
96
Tim Peters59c9a642001-09-13 05:38:56 +000097
98static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +000099fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
100 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Tim Peters59c9a642001-09-13 05:38:56 +0000102 assert(f != NULL);
103 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000104 assert(f->f_fp == NULL);
105
106 Py_DECREF(f->f_name);
107 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000108 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000109
110 Py_INCREF (name);
111 f->f_name = name;
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000114
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000115 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000116 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000117 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000118 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000119 f->f_univ_newline = (strchr(mode, 'U') != NULL);
120 f->f_newlinetypes = NEWLINE_UNKNOWN;
121 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000122 Py_INCREF(Py_None);
123 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000124
Tim Peters59c9a642001-09-13 05:38:56 +0000125 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000128 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130}
131
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000132/* check for known incorrect mode strings - problem is, platforms are
133 free to accept any mode characters they like and are supposed to
134 ignore stuff they don't understand... write or append mode with
135 universal newline support is expressly forbidden by PEP 278. */
136/* zero return is kewl - one is un-kewl */
137static int
138check_the_mode(char *mode)
139{
Neal Norwitz76dc0812006-01-08 06:13:13 +0000140 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000141
142 switch (len) {
143 case 0:
144 PyErr_SetString(PyExc_ValueError, "empty mode string");
145 return 1;
146
147 /* reject wU, aU */
148 case 2:
149 switch (mode[0]) {
150 case 'w':
151 case 'a':
152 if (mode[1] == 'U') {
153 PyErr_SetString(PyExc_ValueError,
154 "invalid mode string");
155 return 1;
156 }
157 break;
158 }
159 break;
160
161 /* reject w+U, a+U, wU+, aU+ */
162 case 3:
163 switch (mode[0]) {
164 case 'w':
165 case 'a':
166 if ((mode[1] == '+' && mode[2] == 'U') ||
167 (mode[1] == 'U' && mode[2] == '+')) {
168 PyErr_SetString(PyExc_ValueError,
169 "invalid mode string");
170 return 1;
171 }
172 break;
173 }
174 break;
175 }
176
177 return 0;
178}
179
Tim Peters59c9a642001-09-13 05:38:56 +0000180static PyObject *
181open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000182{
Tim Peters59c9a642001-09-13 05:38:56 +0000183 assert(f != NULL);
184 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000185#ifdef MS_WINDOWS
186 /* windows ignores the passed name in order to support Unicode */
187 assert(f->f_name != NULL);
188#else
Tim Peters59c9a642001-09-13 05:38:56 +0000189 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000190#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000191 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000192 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000193
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000194 if (check_the_mode(mode))
195 return NULL;
196
Tim Peters8fa45672001-09-13 21:01:29 +0000197 /* rexec.py can't stop a user from getting the file() constructor --
198 all they have to do is get *any* file object f, and then do
199 type(f). Here we prevent them from doing damage with it. */
200 if (PyEval_GetRestricted()) {
201 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000202 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000203 return NULL;
204 }
Tim Petersa27a1502001-11-09 20:59:14 +0000205 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000206
207 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
208 mode = "rb";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000209#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000210 if (PyUnicode_Check(f->f_name)) {
211 PyObject *wmode;
212 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
213 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000214 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000215 /* PyUnicode_AS_UNICODE OK without thread
216 lock as it is a simple dereference. */
217 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
218 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000219 Py_END_ALLOW_THREADS
220 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000221 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000222 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000223#endif
224 if (NULL == f->f_fp && NULL != name) {
225 Py_BEGIN_ALLOW_THREADS
226 f->f_fp = fopen(name, mode);
227 Py_END_ALLOW_THREADS
228 }
229
Guido van Rossuma08095a1991-02-13 23:25:27 +0000230 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000231#ifdef _MSC_VER
232 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
233 * across all Windows flavors. When it sets EINVAL varies
234 * across Windows flavors, the exact conditions aren't
235 * documented, and the answer lies in the OS's implementation
236 * of Win32's CreateFile function (whose source is secret).
237 * Seems the best we can do is map EINVAL to ENOENT.
238 */
239 if (errno == 0) /* bad mode string */
240 errno = EINVAL;
241 else if (errno == EINVAL) /* unknown, but not a mode string */
242 errno = ENOENT;
243#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000244 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000245 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000246 mode);
247 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000248 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000249 f = NULL;
250 }
Tim Peters2ea91112002-04-08 04:13:12 +0000251 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000252 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000253 return (PyObject *)f;
254}
255
256PyObject *
257PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
258{
Tim Peters44410012001-09-14 03:26:08 +0000259 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
260 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000261 if (f != NULL) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000262 PyObject *o_name = PyString_FromString(name);
263 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000264 Py_DECREF(f);
265 f = NULL;
266 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000267 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000268 }
269 return (PyObject *) f;
270}
271
272PyObject *
273PyFile_FromString(char *name, char *mode)
274{
275 extern int fclose(FILE *);
276 PyFileObject *f;
277
278 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
279 if (f != NULL) {
280 if (open_the_file(f, name, mode) == NULL) {
281 Py_DECREF(f);
282 f = NULL;
283 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000285 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286}
287
Guido van Rossumb6775db1994-08-01 11:34:53 +0000288void
Fred Drakefd99de62000-07-09 05:02:18 +0000289PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000290{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000291 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000293 int type;
294 switch (bufsize) {
295 case 0:
296 type = _IONBF;
297 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000298#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000299 case 1:
300 type = _IOLBF;
301 bufsize = BUFSIZ;
302 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000303#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000304 default:
305 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000306#ifndef HAVE_SETVBUF
307 bufsize = BUFSIZ;
308#endif
309 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000311 fflush(file->f_fp);
312 if (type == _IONBF) {
313 PyMem_Free(file->f_setbuf);
314 file->f_setbuf = NULL;
315 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000316 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
317 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000318 }
319#ifdef HAVE_SETVBUF
320 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000321#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000322 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000323#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000324 }
325}
326
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000327/* Set the encoding used to output Unicode strings.
328 Returh 1 on success, 0 on failure. */
329
330int
331PyFile_SetEncoding(PyObject *f, const char *enc)
332{
333 PyFileObject *file = (PyFileObject*)f;
334 PyObject *str = PyString_FromString(enc);
335 if (!str)
336 return 0;
337 Py_DECREF(file->f_encoding);
338 file->f_encoding = str;
339 return 1;
340}
341
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000343err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000344{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000346 return NULL;
347}
348
Thomas Woutersc45251a2006-02-12 11:53:32 +0000349/* Refuse regular file I/O if there's data in the iteration-buffer.
350 * Mixing them would cause data to arrive out of order, as the read*
351 * methods don't use the iteration buffer. */
352static PyObject *
353err_iterbuffered(void)
354{
355 PyErr_SetString(PyExc_ValueError,
356 "Mixing iteration and read methods would lose data");
357 return NULL;
358}
359
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000360static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000361
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362/* Methods */
363
364static void
Fred Drakefd99de62000-07-09 05:02:18 +0000365file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000367 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000368 if (f->weakreflist != NULL)
369 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000370 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000372 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000374 if (sts == EOF)
375#ifdef HAVE_STRERROR
376 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
377#else
378 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
379#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000380 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000381 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000382 Py_XDECREF(f->f_name);
383 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000384 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000385 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000386 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387}
388
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000389static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000390file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000392 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000393#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000394 PyObject *ret = NULL;
395 PyObject *name;
396 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
397 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
398 f->f_fp == NULL ? "closed" : "open",
399 PyString_AsString(name),
400 PyString_AsString(f->f_mode),
401 f);
402 Py_XDECREF(name);
403 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000404#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000405 } else {
406 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000407 f->f_fp == NULL ? "closed" : "open",
408 PyString_AsString(f->f_name),
409 PyString_AsString(f->f_mode),
410 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000411 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412}
413
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000414static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000415file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000417 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000418 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000419 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000421 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000422 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000423 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000424 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000425 f->f_fp = NULL;
426 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000427 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000428 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000429 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000431 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000432 return PyInt_FromLong((long)sts);
433 Py_INCREF(Py_None);
434 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435}
436
Trent Mickf29f47b2000-08-11 19:02:59 +0000437
Guido van Rossumb8552162001-09-05 14:58:11 +0000438/* Our very own off_t-like type, 64-bit if possible */
439#if !defined(HAVE_LARGEFILE_SUPPORT)
440typedef off_t Py_off_t;
441#elif SIZEOF_OFF_T >= 8
442typedef off_t Py_off_t;
443#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000444typedef fpos_t Py_off_t;
445#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000446#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000447#endif
448
449
Trent Mickf29f47b2000-08-11 19:02:59 +0000450/* a portable fseek() function
451 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000452static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000453_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000454{
Guido van Rossumb8552162001-09-05 14:58:11 +0000455#if !defined(HAVE_LARGEFILE_SUPPORT)
456 return fseek(fp, offset, whence);
457#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000458 return fseeko(fp, offset, whence);
459#elif defined(HAVE_FSEEK64)
460 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000461#elif defined(__BEOS__)
462 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000463#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000464 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
465 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000466 fpos_t pos;
467 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000468 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000469#ifdef MS_WINDOWS
470 fflush(fp);
471 if (_lseeki64(fileno(fp), 0, 2) == -1)
472 return -1;
473#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000474 if (fseek(fp, 0, SEEK_END) != 0)
475 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000476#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000477 /* fall through */
478 case SEEK_CUR:
479 if (fgetpos(fp, &pos) != 0)
480 return -1;
481 offset += pos;
482 break;
483 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000484 }
485 return fsetpos(fp, &offset);
486#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000487#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000488#endif
489}
490
491
492/* a portable ftell() function
493 Return -1 on failure with errno set appropriately, current file
494 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000495static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000496_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000497{
Guido van Rossumb8552162001-09-05 14:58:11 +0000498#if !defined(HAVE_LARGEFILE_SUPPORT)
499 return ftell(fp);
500#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
501 return ftello(fp);
502#elif defined(HAVE_FTELL64)
503 return ftell64(fp);
504#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000505 fpos_t pos;
506 if (fgetpos(fp, &pos) != 0)
507 return -1;
508 return pos;
509#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000510#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000511#endif
512}
513
514
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000515static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000516file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000517{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000518 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000519 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000520 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000521 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000522
Guido van Rossumd7297e61992-07-06 14:19:26 +0000523 if (f->f_fp == NULL)
524 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000525 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000526 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000527 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000528 return NULL;
529#if !defined(HAVE_LARGEFILE_SUPPORT)
530 offset = PyInt_AsLong(offobj);
531#else
532 offset = PyLong_Check(offobj) ?
533 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
534#endif
535 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000536 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000539 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000540 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000542
Guido van Rossumff4949e1992-08-05 19:58:53 +0000543 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000545 clearerr(f->f_fp);
546 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000547 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000548 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549 Py_INCREF(Py_None);
550 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000551}
552
Trent Mickf29f47b2000-08-11 19:02:59 +0000553
Guido van Rossumd7047b31995-01-02 19:07:15 +0000554#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000556file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000557{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000558 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000559 PyObject *newsizeobj = NULL;
560 Py_off_t initialpos;
561 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000562
Guido van Rossumd7047b31995-01-02 19:07:15 +0000563 if (f->f_fp == NULL)
564 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000565 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000566 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000567
Tim Petersf1827cf2003-09-07 03:30:18 +0000568 /* Get current file position. If the file happens to be open for
569 * update and the last operation was an input operation, C doesn't
570 * define what the later fflush() will do, but we promise truncate()
571 * won't change the current position (and fflush() *does* change it
572 * then at least on Windows). The easiest thing is to capture
573 * current pos now and seek back to it at the end.
574 */
575 Py_BEGIN_ALLOW_THREADS
576 errno = 0;
577 initialpos = _portable_ftell(f->f_fp);
578 Py_END_ALLOW_THREADS
579 if (initialpos == -1)
580 goto onioerror;
581
Tim Petersfb05db22002-03-11 00:24:00 +0000582 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000583 * specified value.
584 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000585 if (newsizeobj != NULL) {
586#if !defined(HAVE_LARGEFILE_SUPPORT)
587 newsize = PyInt_AsLong(newsizeobj);
588#else
589 newsize = PyLong_Check(newsizeobj) ?
590 PyLong_AsLongLong(newsizeobj) :
591 PyInt_AsLong(newsizeobj);
592#endif
593 if (PyErr_Occurred())
594 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000595 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000596 else /* default to current position */
597 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000598
Tim Petersf1827cf2003-09-07 03:30:18 +0000599 /* Flush the stream. We're mixing stream-level I/O with lower-level
600 * I/O, and a flush may be necessary to synch both platform views
601 * of the current file state.
602 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000603 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000604 errno = 0;
605 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000607 if (ret != 0)
608 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000609
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000610#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000611 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000612 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000613 {
Tim Petersfb05db22002-03-11 00:24:00 +0000614 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000615
Tim Petersf1827cf2003-09-07 03:30:18 +0000616 /* Have to move current pos to desired endpoint on Windows. */
617 Py_BEGIN_ALLOW_THREADS
618 errno = 0;
619 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
620 Py_END_ALLOW_THREADS
621 if (ret)
622 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000623
Tim Peters8f01b682002-03-12 03:04:44 +0000624 /* Truncate. Note that this may grow the file! */
625 Py_BEGIN_ALLOW_THREADS
626 errno = 0;
627 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000628 ret = hFile == (HANDLE)-1;
629 if (ret == 0) {
630 ret = SetEndOfFile(hFile) == 0;
631 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000632 errno = EACCES;
633 }
634 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000635 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000636 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000637 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000638#else
639 Py_BEGIN_ALLOW_THREADS
640 errno = 0;
641 ret = ftruncate(fileno(f->f_fp), newsize);
642 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000643 if (ret != 0)
644 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000645#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000646
Tim Petersf1827cf2003-09-07 03:30:18 +0000647 /* Restore original file position. */
648 Py_BEGIN_ALLOW_THREADS
649 errno = 0;
650 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
651 Py_END_ALLOW_THREADS
652 if (ret)
653 goto onioerror;
654
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000655 Py_INCREF(Py_None);
656 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000657
658onioerror:
659 PyErr_SetFromErrno(PyExc_IOError);
660 clearerr(f->f_fp);
661 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000662}
663#endif /* HAVE_FTRUNCATE */
664
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000666file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000667{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000668 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000669
Guido van Rossumd7297e61992-07-06 14:19:26 +0000670 if (f->f_fp == NULL)
671 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000672 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000673 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000674 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000676 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000678 clearerr(f->f_fp);
679 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000680 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000681 if (f->f_skipnextlf) {
682 int c;
683 c = GETC(f->f_fp);
684 if (c == '\n') {
685 pos++;
686 f->f_skipnextlf = 0;
687 } else if (c != EOF) ungetc(c, f->f_fp);
688 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000689#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000690 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000691#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000692 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000693#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000694}
695
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000696static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000697file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000698{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000699 if (f->f_fp == NULL)
700 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000701 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000702}
703
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000704static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000705file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000706{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000707 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000708
Guido van Rossumd7297e61992-07-06 14:19:26 +0000709 if (f->f_fp == NULL)
710 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000711 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000712 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000713 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000715 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000717 clearerr(f->f_fp);
718 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000719 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000720 Py_INCREF(Py_None);
721 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000722}
723
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000725file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000726{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000727 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000728 if (f->f_fp == NULL)
729 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000730 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000731 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000733 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000734}
735
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000736
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000737#if BUFSIZ < 8192
738#define SMALLCHUNK 8192
739#else
740#define SMALLCHUNK BUFSIZ
741#endif
742
Guido van Rossum3c259041999-01-14 19:00:14 +0000743#if SIZEOF_INT < 4
744#define BIGCHUNK (512 * 32)
745#else
746#define BIGCHUNK (512 * 1024)
747#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000748
749static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000750new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000751{
752#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000753 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000754 struct stat st;
755 if (fstat(fileno(f->f_fp), &st) == 0) {
756 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000757 /* The following is not a bug: we really need to call lseek()
758 *and* ftell(). The reason is that some stdio libraries
759 mistakenly flush their buffer when ftell() is called and
760 the lseek() call it makes fails, thereby throwing away
761 data that cannot be recovered in any way. To avoid this,
762 we first test lseek(), and only call ftell() if lseek()
763 works. We can't use the lseek() value either, because we
764 need to take the amount of buffered data into account.
765 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000766 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000767 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000768 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000769 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000770 if (pos < 0)
771 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000772 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000773 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000774 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000775 }
776#endif
777 if (currentsize > SMALLCHUNK) {
778 /* Keep doubling until we reach BIGCHUNK;
779 then keep adding BIGCHUNK. */
780 if (currentsize <= BIGCHUNK)
781 return currentsize + currentsize;
782 else
783 return currentsize + BIGCHUNK;
784 }
785 return currentsize + SMALLCHUNK;
786}
787
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000788#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
789#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
790#else
791#ifdef EWOULDBLOCK
792#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
793#else
794#ifdef EAGAIN
795#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
796#else
797#define BLOCKED_ERRNO(x) 0
798#endif
799#endif
800#endif
801
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000802static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000803file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000804{
Guido van Rossum789a1611997-05-10 22:33:55 +0000805 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000806 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000807 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000808
Guido van Rossumd7297e61992-07-06 14:19:26 +0000809 if (f->f_fp == NULL)
810 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000811 /* refuse to mix with f.next() */
812 if (f->f_buf != NULL &&
813 (f->f_bufend - f->f_bufptr) > 0 &&
814 f->f_buf[0] != '\0')
815 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000816 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000817 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000818 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000819 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000820 else
821 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000822 if (buffersize > INT_MAX) {
823 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000824 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000825 return NULL;
826 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000827 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000828 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000829 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000830 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000831 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000832 Py_BEGIN_ALLOW_THREADS
833 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000834 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000835 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000836 Py_END_ALLOW_THREADS
837 if (chunksize == 0) {
838 if (!ferror(f->f_fp))
839 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000840 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000841 /* When in non-blocking mode, data shouldn't
842 * be discarded if a blocking signal was
843 * received. That will also happen if
844 * chunksize != 0, but bytesread < buffersize. */
845 if (bytesread > 0 && BLOCKED_ERRNO(errno))
846 break;
847 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000848 Py_DECREF(v);
849 return NULL;
850 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000851 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000852 if (bytesread < buffersize) {
853 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000854 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000855 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000856 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000857 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000858 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000859 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000860 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000861 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000862 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000863 }
864 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000865 if (bytesread != buffersize)
866 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000867 return v;
868}
869
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000870static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000871file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000872{
873 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000874 Py_ssize_t ntodo;
875 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000876
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000877 if (f->f_fp == NULL)
878 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000879 /* refuse to mix with f.next() */
880 if (f->f_buf != NULL &&
881 (f->f_bufend - f->f_bufptr) > 0 &&
882 f->f_buf[0] != '\0')
883 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000884 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000885 return NULL;
886 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000887 while (ntodo > 0) {
888 Py_BEGIN_ALLOW_THREADS
889 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000890 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000891 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000892 Py_END_ALLOW_THREADS
893 if (nnow == 0) {
894 if (!ferror(f->f_fp))
895 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000896 PyErr_SetFromErrno(PyExc_IOError);
897 clearerr(f->f_fp);
898 return NULL;
899 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000900 ndone += nnow;
901 ntodo -= nnow;
902 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000903 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000904}
905
Tim Peters86821b22001-01-07 21:19:34 +0000906/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000907Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000908
909Under MSVC 6:
910
Tim Peters1c733232001-01-08 04:02:07 +0000911+ MS threadsafe getc is very slow (multiple layers of function calls before+
912 after each character, to lock+unlock the stream).
913+ The stream-locking functions are MS-internal -- can't access them from user
914 code.
915+ There's nothing Tim could find in the MS C or platform SDK libraries that
916 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000917+ MS fgets locks/unlocks only once per line; it's the only hook we have.
918
919So we use fgets for speed(!), despite that it's painful.
920
921MS realloc is also slow.
922
Tim Petersf29b64d2001-01-15 06:33:19 +0000923Reports from other platforms on this method vs getc_unlocked (which MS doesn't
924have):
925 Linux a wash
926 Solaris a wash
927 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000928
Tim Petersf29b64d2001-01-15 06:33:19 +0000929CAUTION: The C std isn't clear about this: in those cases where fgets
930writes something into the buffer, can it write into any position beyond the
931required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
932known on which it does; and it would be a strange way to code fgets. Still,
933getline_via_fgets may not work correctly if it does. The std test
934test_bufio.py should fail if platform fgets() routinely writes beyond the
935trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000936**************************************************************************/
937
Tim Petersf29b64d2001-01-15 06:33:19 +0000938/* Use this routine if told to, or by default on non-get_unlocked()
939 * platforms unless told not to. Yikes! Let's spell that out:
940 * On a platform with getc_unlocked():
941 * By default, use getc_unlocked().
942 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
943 * On a platform without getc_unlocked():
944 * By default, use fgets().
945 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
946 */
947#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
948#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000949#endif
950
Tim Petersf29b64d2001-01-15 06:33:19 +0000951#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
952#undef USE_FGETS_IN_GETLINE
953#endif
954
955#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000956static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000957getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000958{
Tim Peters15b83852001-01-08 00:53:12 +0000959/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000960 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
961 * to fill this much of the buffer with a known value in order to figure out
962 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
963 * than "most" lines, we waste time filling unused buffer slots. 100 is
964 * surely adequate for most peoples' email archives, chewing over source code,
965 * etc -- "regular old text files".
966 * MAXBUFSIZE is the maximum line length that lets us get away with the less
967 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
968 * cautions about boosting that. 300 was chosen because the worst real-life
969 * text-crunching job reported on Python-Dev was a mail-log crawler where over
970 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000971 */
Tim Peters142297a2001-01-15 10:36:56 +0000972#define INITBUFSIZE 100
973#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000974 char* p; /* temp */
975 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000976 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000977 char* pvfree; /* address of next free slot */
978 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000979 size_t nfree; /* # of free buffer slots; pvend-pvfree */
980 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000981 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000982
Tim Peters15b83852001-01-08 00:53:12 +0000983 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000984 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000985 */
Tim Peters142297a2001-01-15 10:36:56 +0000986 total_v_size = INITBUFSIZE; /* start small and pray */
987 pvfree = buf;
988 for (;;) {
989 Py_BEGIN_ALLOW_THREADS
990 pvend = buf + total_v_size;
991 nfree = pvend - pvfree;
992 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000993 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
994 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +0000995 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000996
Tim Peters142297a2001-01-15 10:36:56 +0000997 if (p == NULL) {
998 clearerr(fp);
999 if (PyErr_CheckSignals())
1000 return NULL;
1001 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001002 return v;
1003 }
Tim Peters142297a2001-01-15 10:36:56 +00001004 /* fgets read *something* */
1005 p = memchr(pvfree, '\n', nfree);
1006 if (p != NULL) {
1007 /* Did the \n come from fgets or from us?
1008 * Since fgets stops at the first \n, and then writes
1009 * \0, if it's from fgets a \0 must be next. But if
1010 * that's so, it could not have come from us, since
1011 * the \n's we filled the buffer with have only more
1012 * \n's to the right.
1013 */
1014 if (p+1 < pvend && *(p+1) == '\0') {
1015 /* It's from fgets: we win! In particular,
1016 * we haven't done any mallocs yet, and can
1017 * build the final result on the first try.
1018 */
1019 ++p; /* include \n from fgets */
1020 }
1021 else {
1022 /* Must be from us: fgets didn't fill the
1023 * buffer and didn't find a newline, so it
1024 * must be the last and newline-free line of
1025 * the file.
1026 */
1027 assert(p > pvfree && *(p-1) == '\0');
1028 --p; /* don't include \0 from fgets */
1029 }
1030 v = PyString_FromStringAndSize(buf, p - buf);
1031 return v;
1032 }
1033 /* yuck: fgets overwrote all the newlines, i.e. the entire
1034 * buffer. So this line isn't over yet, or maybe it is but
1035 * we're exactly at EOF. If we haven't already, try using the
1036 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001037 */
Tim Peters142297a2001-01-15 10:36:56 +00001038 assert(*(pvend-1) == '\0');
1039 if (pvfree == buf) {
1040 pvfree = pvend - 1; /* overwrite trailing null */
1041 total_v_size = MAXBUFSIZE;
1042 }
1043 else
1044 break;
Tim Peters86821b22001-01-07 21:19:34 +00001045 }
Tim Peters142297a2001-01-15 10:36:56 +00001046
1047 /* The stack buffer isn't big enough; malloc a string object and read
1048 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001049 */
Tim Petersddea2082002-03-23 10:03:50 +00001050 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001051 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001052 if (v == NULL)
1053 return v;
1054 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001055 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1056 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001057
1058 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001059 * after setting p one beyond the end of the line. The code here is
1060 * very much like the code above, except reads into v's buffer; see
1061 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001062 */
1063 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001064 Py_BEGIN_ALLOW_THREADS
1065 pvend = BUF(v) + total_v_size;
1066 nfree = pvend - pvfree;
1067 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001068 assert(nfree < INT_MAX);
1069 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001070 Py_END_ALLOW_THREADS
1071
1072 if (p == NULL) {
1073 clearerr(fp);
1074 if (PyErr_CheckSignals()) {
1075 Py_DECREF(v);
1076 return NULL;
1077 }
1078 p = pvfree;
1079 break;
1080 }
Tim Peters86821b22001-01-07 21:19:34 +00001081 p = memchr(pvfree, '\n', nfree);
1082 if (p != NULL) {
1083 if (p+1 < pvend && *(p+1) == '\0') {
1084 /* \n came from fgets */
1085 ++p;
1086 break;
1087 }
1088 /* \n came from us; last line of file, no newline */
1089 assert(p > pvfree && *(p-1) == '\0');
1090 --p;
1091 break;
1092 }
1093 /* expand buffer and try again */
1094 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001095 increment = total_v_size >> 2; /* mild exponential growth */
1096 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001097 if (total_v_size > INT_MAX) {
1098 PyErr_SetString(PyExc_OverflowError,
1099 "line is longer than a Python string can hold");
1100 Py_DECREF(v);
1101 return NULL;
1102 }
1103 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1104 return NULL;
1105 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001106 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001107 }
1108 if (BUF(v) + total_v_size != p)
1109 _PyString_Resize(&v, p - BUF(v));
1110 return v;
1111#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001112#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001113}
Tim Petersf29b64d2001-01-15 06:33:19 +00001114#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001115
Guido van Rossum0bd24411991-04-04 15:21:57 +00001116/* Internal routine to get a line.
1117 Size argument interpretation:
1118 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001119 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001120*/
1121
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001122static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001123get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001124{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001125 FILE *fp = f->f_fp;
1126 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001127 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001128 size_t total_v_size; /* total # of slots in buffer */
1129 size_t used_v_size; /* # used slots in buffer */
1130 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001131 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001132 int newlinetypes = f->f_newlinetypes;
1133 int skipnextlf = f->f_skipnextlf;
1134 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001135
Jack Jansen7b8c7542002-04-14 20:12:41 +00001136#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001137 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001138 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001139#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001140 total_v_size = n > 0 ? n : 100;
1141 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001142 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001143 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001144 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001145 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001146
Guido van Rossumce5ba841991-03-06 13:06:18 +00001147 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001148 Py_BEGIN_ALLOW_THREADS
1149 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001150 if (univ_newline) {
1151 c = 'x'; /* Shut up gcc warning */
1152 while ( buf != end && (c = GETC(fp)) != EOF ) {
1153 if (skipnextlf ) {
1154 skipnextlf = 0;
1155 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001156 /* Seeing a \n here with
1157 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001158 * saw a \r before.
1159 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001160 newlinetypes |= NEWLINE_CRLF;
1161 c = GETC(fp);
1162 if (c == EOF) break;
1163 } else {
1164 newlinetypes |= NEWLINE_CR;
1165 }
1166 }
1167 if (c == '\r') {
1168 skipnextlf = 1;
1169 c = '\n';
1170 } else if ( c == '\n')
1171 newlinetypes |= NEWLINE_LF;
1172 *buf++ = c;
1173 if (c == '\n') break;
1174 }
1175 if ( c == EOF && skipnextlf )
1176 newlinetypes |= NEWLINE_CR;
1177 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001178 while ((c = GETC(fp)) != EOF &&
1179 (*buf++ = c) != '\n' &&
1180 buf != end)
1181 ;
1182 FUNLOCKFILE(fp);
1183 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001184 f->f_newlinetypes = newlinetypes;
1185 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001186 if (c == '\n')
1187 break;
1188 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001189 if (ferror(fp)) {
1190 PyErr_SetFromErrno(PyExc_IOError);
1191 clearerr(fp);
1192 Py_DECREF(v);
1193 return NULL;
1194 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001195 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001196 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001197 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001198 return NULL;
1199 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001200 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001201 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001202 /* Must be because buf == end */
1203 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001204 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001205 used_v_size = total_v_size;
1206 increment = total_v_size >> 2; /* mild exponential growth */
1207 total_v_size += increment;
1208 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001209 PyErr_SetString(PyExc_OverflowError,
1210 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001211 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001212 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001213 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001214 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001215 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001216 buf = BUF(v) + used_v_size;
1217 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001218 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001219
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001220 used_v_size = buf - BUF(v);
1221 if (used_v_size != total_v_size)
1222 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001223 return v;
1224}
1225
Guido van Rossum0bd24411991-04-04 15:21:57 +00001226/* External C interface */
1227
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001228PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001229PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001230{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001231 PyObject *result;
1232
Guido van Rossum3165fe61992-09-25 21:59:05 +00001233 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001234 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001235 return NULL;
1236 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001237
1238 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001239 PyFileObject *fo = (PyFileObject *)f;
1240 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001241 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001242 /* refuse to mix with f.next() */
1243 if (fo->f_buf != NULL &&
1244 (fo->f_bufend - fo->f_bufptr) > 0 &&
1245 fo->f_buf[0] != '\0')
1246 return err_iterbuffered();
1247 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001248 }
1249 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001250 PyObject *reader;
1251 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001252
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001253 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001254 if (reader == NULL)
1255 return NULL;
1256 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001257 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001258 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001259 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001260 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001261 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001262 return NULL;
1263 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001264 result = PyEval_CallObject(reader, args);
1265 Py_DECREF(reader);
1266 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001267 if (result != NULL && !PyString_Check(result) &&
1268 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001269 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001270 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001271 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001272 "object.readline() returned non-string");
1273 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001274 }
1275
1276 if (n < 0 && result != NULL && PyString_Check(result)) {
1277 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001278 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001279 if (len == 0) {
1280 Py_DECREF(result);
1281 result = NULL;
1282 PyErr_SetString(PyExc_EOFError,
1283 "EOF when reading a line");
1284 }
1285 else if (s[len-1] == '\n') {
1286 if (result->ob_refcnt == 1)
1287 _PyString_Resize(&result, len-1);
1288 else {
1289 PyObject *v;
1290 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001291 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001292 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001293 }
1294 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001295 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001296#ifdef Py_USING_UNICODE
1297 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1298 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001299 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001300 if (len == 0) {
1301 Py_DECREF(result);
1302 result = NULL;
1303 PyErr_SetString(PyExc_EOFError,
1304 "EOF when reading a line");
1305 }
1306 else if (s[len-1] == '\n') {
1307 if (result->ob_refcnt == 1)
1308 PyUnicode_Resize(&result, len-1);
1309 else {
1310 PyObject *v;
1311 v = PyUnicode_FromUnicode(s, len-1);
1312 Py_DECREF(result);
1313 result = v;
1314 }
1315 }
1316 }
1317#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001318 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001319}
1320
1321/* Python method */
1322
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001323static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001324file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001325{
Guido van Rossum789a1611997-05-10 22:33:55 +00001326 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001327
Guido van Rossumd7297e61992-07-06 14:19:26 +00001328 if (f->f_fp == NULL)
1329 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001330 /* refuse to mix with f.next() */
1331 if (f->f_buf != NULL &&
1332 (f->f_bufend - f->f_bufptr) > 0 &&
1333 f->f_buf[0] != '\0')
1334 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001335 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001336 return NULL;
1337 if (n == 0)
1338 return PyString_FromString("");
1339 if (n < 0)
1340 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001341 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001342}
1343
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001344static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001345file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001346{
Guido van Rossum789a1611997-05-10 22:33:55 +00001347 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001348 PyObject *list;
1349 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001350 char small_buffer[SMALLCHUNK];
1351 char *buffer = small_buffer;
1352 size_t buffersize = SMALLCHUNK;
1353 PyObject *big_buffer = NULL;
1354 size_t nfilled = 0;
1355 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001356 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001357 char *p, *q, *end;
1358 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001359 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001360
Guido van Rossumd7297e61992-07-06 14:19:26 +00001361 if (f->f_fp == NULL)
1362 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001363 /* refuse to mix with f.next() */
1364 if (f->f_buf != NULL &&
1365 (f->f_bufend - f->f_bufptr) > 0 &&
1366 f->f_buf[0] != '\0')
1367 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001368 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001369 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001370 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001371 return NULL;
1372 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001373 if (shortread)
1374 nread = 0;
1375 else {
1376 Py_BEGIN_ALLOW_THREADS
1377 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001378 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001379 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001380 Py_END_ALLOW_THREADS
1381 shortread = (nread < buffersize-nfilled);
1382 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001383 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001384 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001385 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001386 break;
1387 PyErr_SetFromErrno(PyExc_IOError);
1388 clearerr(f->f_fp);
1389 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001390 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001391 list = NULL;
1392 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001393 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001394 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001395 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001396 if (p == NULL) {
1397 /* Need a larger buffer to fit this line */
1398 nfilled += nread;
1399 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001400 if (buffersize > INT_MAX) {
1401 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001402 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001403 goto error;
1404 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001405 if (big_buffer == NULL) {
1406 /* Create the big buffer */
1407 big_buffer = PyString_FromStringAndSize(
1408 NULL, buffersize);
1409 if (big_buffer == NULL)
1410 goto error;
1411 buffer = PyString_AS_STRING(big_buffer);
1412 memcpy(buffer, small_buffer, nfilled);
1413 }
1414 else {
1415 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001416 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1417 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001418 buffer = PyString_AS_STRING(big_buffer);
1419 }
1420 continue;
1421 }
1422 end = buffer+nfilled+nread;
1423 q = buffer;
1424 do {
1425 /* Process complete lines */
1426 p++;
1427 line = PyString_FromStringAndSize(q, p-q);
1428 if (line == NULL)
1429 goto error;
1430 err = PyList_Append(list, line);
1431 Py_DECREF(line);
1432 if (err != 0)
1433 goto error;
1434 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001435 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001436 } while (p != NULL);
1437 /* Move the remaining incomplete line to the start */
1438 nfilled = end-q;
1439 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001440 if (sizehint > 0)
1441 if (totalread >= (size_t)sizehint)
1442 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001443 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001444 if (nfilled != 0) {
1445 /* Partial last line */
1446 line = PyString_FromStringAndSize(buffer, nfilled);
1447 if (line == NULL)
1448 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001449 if (sizehint > 0) {
1450 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001451 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001452 if (rest == NULL) {
1453 Py_DECREF(line);
1454 goto error;
1455 }
1456 PyString_Concat(&line, rest);
1457 Py_DECREF(rest);
1458 if (line == NULL)
1459 goto error;
1460 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001461 err = PyList_Append(list, line);
1462 Py_DECREF(line);
1463 if (err != 0)
1464 goto error;
1465 }
1466 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001467 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001468 return list;
1469}
1470
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001471static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001472file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001473{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001474 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001475 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001476 if (f->f_fp == NULL)
1477 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001478 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001479 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001480 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001481 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001482 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001483 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001485 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001486 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001487 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001488 return NULL;
1489 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490 Py_INCREF(Py_None);
1491 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001492}
1493
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001494static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001495file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001496{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001497#define CHUNKSIZE 1000
1498 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001499 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001500 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001501 int index, islist;
1502 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001503
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001504 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001505 if (f->f_fp == NULL)
1506 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001507
1508 result = NULL;
1509 list = NULL;
1510 islist = PyList_Check(seq);
1511 if (islist)
1512 it = NULL;
1513 else {
1514 it = PyObject_GetIter(seq);
1515 if (it == NULL) {
1516 PyErr_SetString(PyExc_TypeError,
1517 "writelines() requires an iterable argument");
1518 return NULL;
1519 }
1520 /* From here on, fail by going to error, to reclaim "it". */
1521 list = PyList_New(CHUNKSIZE);
1522 if (list == NULL)
1523 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001524 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001525
1526 /* Strategy: slurp CHUNKSIZE lines into a private list,
1527 checking that they are all strings, then write that list
1528 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001529 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001530 if (islist) {
1531 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001532 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001533 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001534 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001535 j = PyList_GET_SIZE(list);
1536 }
1537 else {
1538 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001539 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001540 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001541 if (PyErr_Occurred())
1542 goto error;
1543 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001544 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001545 PyList_SetItem(list, j, line);
1546 }
1547 }
1548 if (j == 0)
1549 break;
1550
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001551 /* Check that all entries are indeed strings. If not,
1552 apply the same rules as for file.write() and
1553 convert the results to strings. This is slow, but
1554 seems to be the only way since all conversion APIs
1555 could potentially execute Python code. */
1556 for (i = 0; i < j; i++) {
1557 PyObject *v = PyList_GET_ITEM(list, i);
1558 if (!PyString_Check(v)) {
1559 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001560 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001561 PyObject_AsReadBuffer(v,
1562 (const void**)&buffer,
1563 &len)) ||
1564 PyObject_AsCharBuffer(v,
1565 &buffer,
1566 &len))) {
1567 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001568 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001569 goto error;
1570 }
1571 line = PyString_FromStringAndSize(buffer,
1572 len);
1573 if (line == NULL)
1574 goto error;
1575 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001576 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001577 }
1578 }
1579
1580 /* Since we are releasing the global lock, the
1581 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001582 Py_BEGIN_ALLOW_THREADS
1583 f->f_softspace = 0;
1584 errno = 0;
1585 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001586 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001587 len = PyString_GET_SIZE(line);
1588 nwritten = fwrite(PyString_AS_STRING(line),
1589 1, len, f->f_fp);
1590 if (nwritten != len) {
1591 Py_BLOCK_THREADS
1592 PyErr_SetFromErrno(PyExc_IOError);
1593 clearerr(f->f_fp);
1594 goto error;
1595 }
1596 }
1597 Py_END_ALLOW_THREADS
1598
1599 if (j < CHUNKSIZE)
1600 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001601 }
1602
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001603 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001604 result = Py_None;
1605 error:
1606 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001607 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001608 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001609#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001610}
1611
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001612static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001613file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001614{
1615 if (f->f_fp == NULL)
1616 return err_closed();
1617 Py_INCREF(f);
1618 return (PyObject *)f;
1619}
1620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001622"readline([size]) -> next line from the file, as a string.\n"
1623"\n"
1624"Retain newline. A non-negative size argument limits the maximum\n"
1625"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001626"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001628PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001629"read([size]) -> read at most size bytes, returned as a string.\n"
1630"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001631"If the size argument is negative or omitted, read until EOF is reached.\n"
1632"Notice that when in non-blocking mode, less data than what was requested\n"
1633"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001636"write(str) -> None. Write string str to file.\n"
1637"\n"
1638"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001639"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001641PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001642"fileno() -> integer \"file descriptor\".\n"
1643"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001644"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001646PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001647"seek(offset[, whence]) -> None. Move to new file position.\n"
1648"\n"
1649"Argument offset is a byte count. Optional argument whence defaults to\n"
1650"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1651"(move relative to current position, positive or negative), and 2 (move\n"
1652"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001653"seeking beyond the end of a file). If the file is opened in text mode,\n"
1654"only offsets returned by tell() are legal. Use of other offsets causes\n"
1655"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001656"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001657"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001658
Guido van Rossumd7047b31995-01-02 19:07:15 +00001659#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001660PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001661"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1662"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001663"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001664#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001666PyDoc_STRVAR(tell_doc,
1667"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001668
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001669PyDoc_STRVAR(readinto_doc,
1670"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001672PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001673"readlines([size]) -> list of strings, each a line from the file.\n"
1674"\n"
1675"Call readline() repeatedly and return a list of the lines so read.\n"
1676"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001677"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001679PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001680"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001681"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001682"For backward compatibility. File objects now include the performance\n"
1683"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001684
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001685PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001686"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001687"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001688"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001689"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001691PyDoc_STRVAR(flush_doc,
1692"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001694PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001695"close() -> None or (perhaps) an integer. Close the file.\n"
1696"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001697"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001698"further I/O operations. close() may be called more than once without\n"
1699"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001700"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001702PyDoc_STRVAR(isatty_doc,
1703"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001704
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001705PyDoc_STRVAR(context_doc,
1706 "__context__() -> self.");
1707
1708PyDoc_STRVAR(enter_doc,
1709 "__enter__() -> self.");
1710
Tim Petersefc3a3a2001-09-20 07:55:22 +00001711static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001712 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1713 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1714 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1715 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1716 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001717#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001718 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001719#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001720 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1721 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1722 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001723 {"xreadlines",(PyCFunction)file_self, METH_NOARGS, xreadlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001724 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1725 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1726 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1727 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001728 {"__context__", (PyCFunction)file_self, METH_NOARGS, context_doc},
1729 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Guido van Rossumf6694362006-03-10 02:28:35 +00001730 {"__exit__", (PyCFunction)file_close, METH_VARARGS, close_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001731 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001732};
1733
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001734#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001735
Guido van Rossum6f799372001-09-20 20:46:19 +00001736static PyMemberDef file_memberlist[] = {
1737 {"softspace", T_INT, OFF(f_softspace), 0,
1738 "flag indicating that a space needs to be printed; used by print"},
1739 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001740 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001741 {"name", T_OBJECT, OFF(f_name), RO,
1742 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001743 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1744 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001745 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001746 {NULL} /* Sentinel */
1747};
1748
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001749static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001750get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001751{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001752 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001753}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001754static PyObject *
1755get_newlines(PyFileObject *f, void *closure)
1756{
1757 switch (f->f_newlinetypes) {
1758 case NEWLINE_UNKNOWN:
1759 Py_INCREF(Py_None);
1760 return Py_None;
1761 case NEWLINE_CR:
1762 return PyString_FromString("\r");
1763 case NEWLINE_LF:
1764 return PyString_FromString("\n");
1765 case NEWLINE_CR|NEWLINE_LF:
1766 return Py_BuildValue("(ss)", "\r", "\n");
1767 case NEWLINE_CRLF:
1768 return PyString_FromString("\r\n");
1769 case NEWLINE_CR|NEWLINE_CRLF:
1770 return Py_BuildValue("(ss)", "\r", "\r\n");
1771 case NEWLINE_LF|NEWLINE_CRLF:
1772 return Py_BuildValue("(ss)", "\n", "\r\n");
1773 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1774 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1775 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001776 PyErr_Format(PyExc_SystemError,
1777 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001778 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001779 return NULL;
1780 }
1781}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001782
Guido van Rossum32d34c82001-09-20 21:45:26 +00001783static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001784 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001785 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001786 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 {0},
1788};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001789
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001790static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001791drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001792{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001793 if (f->f_buf != NULL) {
1794 PyMem_Free(f->f_buf);
1795 f->f_buf = NULL;
1796 }
Guido van Rossum65967252001-04-21 13:20:18 +00001797}
1798
Tim Petersf1827cf2003-09-07 03:30:18 +00001799/* Make sure that file has a readahead buffer with at least one byte
1800 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00001801 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001802static int
1803readahead(PyFileObject *f, int bufsize)
1804{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001805 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001806
1807 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001808 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001809 return 0;
1810 else
1811 drop_readahead(f);
1812 }
Anthony Baxter377be112006-04-11 06:54:30 +00001813 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00001814 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001815 return -1;
1816 }
1817 Py_BEGIN_ALLOW_THREADS
1818 errno = 0;
1819 chunksize = Py_UniversalNewlineFread(
1820 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1821 Py_END_ALLOW_THREADS
1822 if (chunksize == 0) {
1823 if (ferror(f->f_fp)) {
1824 PyErr_SetFromErrno(PyExc_IOError);
1825 clearerr(f->f_fp);
1826 drop_readahead(f);
1827 return -1;
1828 }
1829 }
1830 f->f_bufptr = f->f_buf;
1831 f->f_bufend = f->f_buf + chunksize;
1832 return 0;
1833}
1834
1835/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001836 uninitialized bytes followed by the remainder of the line. Don't be
1837 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001838 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1839
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001840static PyStringObject *
1841readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1842{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001843 PyStringObject* s;
1844 char *bufptr;
1845 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001846 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001847
1848 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001849 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001850 return NULL;
1851
1852 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001853 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001854 return (PyStringObject *)
1855 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00001856 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001857 if (bufptr != NULL) {
1858 bufptr++; /* Count the '\n' */
1859 len = bufptr - f->f_bufptr;
1860 s = (PyStringObject *)
1861 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001862 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001863 return NULL;
1864 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1865 f->f_bufptr = bufptr;
1866 if (bufptr == f->f_bufend)
1867 drop_readahead(f);
1868 } else {
1869 bufptr = f->f_bufptr;
1870 buf = f->f_buf;
1871 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001872 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001873 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001874 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001875 if (s == NULL) {
1876 PyMem_Free(buf);
1877 return NULL;
1878 }
1879 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1880 PyMem_Free(buf);
1881 }
1882 return s;
1883}
1884
1885/* A larger buffer size may actually decrease performance. */
1886#define READAHEAD_BUFSIZE 8192
1887
1888static PyObject *
1889file_iternext(PyFileObject *f)
1890{
1891 PyStringObject* l;
1892
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001893 if (f->f_fp == NULL)
1894 return err_closed();
1895
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001896 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1897 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1898 Py_XDECREF(l);
1899 return NULL;
1900 }
1901 return (PyObject *)l;
1902}
1903
1904
Tim Peters59c9a642001-09-13 05:38:56 +00001905static PyObject *
1906file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1907{
Tim Peters44410012001-09-14 03:26:08 +00001908 PyObject *self;
1909 static PyObject *not_yet_string;
1910
1911 assert(type != NULL && type->tp_alloc != NULL);
1912
1913 if (not_yet_string == NULL) {
1914 not_yet_string = PyString_FromString("<uninitialized file>");
1915 if (not_yet_string == NULL)
1916 return NULL;
1917 }
1918
1919 self = type->tp_alloc(type, 0);
1920 if (self != NULL) {
1921 /* Always fill in the name and mode, so that nobody else
1922 needs to special-case NULLs there. */
1923 Py_INCREF(not_yet_string);
1924 ((PyFileObject *)self)->f_name = not_yet_string;
1925 Py_INCREF(not_yet_string);
1926 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001927 Py_INCREF(Py_None);
1928 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001929 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001930 }
1931 return self;
1932}
1933
1934static int
1935file_init(PyObject *self, PyObject *args, PyObject *kwds)
1936{
1937 PyFileObject *foself = (PyFileObject *)self;
1938 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001939 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001940 char *name = NULL;
1941 char *mode = "r";
1942 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001943 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001944
1945 assert(PyFile_Check(self));
1946 if (foself->f_fp != NULL) {
1947 /* Have to close the existing file first. */
1948 PyObject *closeresult = file_close(foself);
1949 if (closeresult == NULL)
1950 return -1;
1951 Py_DECREF(closeresult);
1952 }
Tim Peters59c9a642001-09-13 05:38:56 +00001953
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001954#ifdef Py_WIN_WIDE_FILENAMES
1955 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1956 PyObject *po;
1957 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1958 kwlist, &po, &mode, &bufsize)) {
1959 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001960 if (fill_file_fields(foself, NULL, po, mode,
1961 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001962 goto Error;
1963 } else {
1964 /* Drop the argument parsing error as narrow
1965 strings are also valid. */
1966 PyErr_Clear();
1967 }
1968 }
1969#endif
1970
1971 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001972 PyObject *o_name;
1973
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001974 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1975 Py_FileSystemDefaultEncoding,
1976 &name,
1977 &mode, &bufsize))
1978 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001979
1980 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001981 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1982 kwlist, &o_name, &mode,
1983 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001984 return -1;
1985
1986 if (fill_file_fields(foself, NULL, o_name, mode,
1987 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001988 goto Error;
1989 }
Tim Peters44410012001-09-14 03:26:08 +00001990 if (open_the_file(foself, name, mode) == NULL)
1991 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001992 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001993 PyFile_SetBufSize(self, bufsize);
1994 goto Done;
1995
1996Error:
1997 ret = -1;
1998 /* fall through */
1999Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002000 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002001 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002002}
2003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002004PyDoc_VAR(file_doc) =
2005PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002006"file(name[, mode[, buffering]]) -> file object\n"
2007"\n"
2008"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2009"writing or appending. The file will be created if it doesn't exist\n"
2010"when opened for writing or appending; it will be truncated when\n"
2011"opened for writing. Add a 'b' to the mode for binary files.\n"
2012"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2013"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002014"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002015)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002016PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002017"Add a 'U' to mode to open the file for input with universal newline\n"
2018"support. Any line ending in the input file will be seen as a '\\n'\n"
2019"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2020"the value for this attribute is one of None (no newline read yet),\n"
2021"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2022"\n"
2023"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002025PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002026"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027"Note: open() is an alias for file()."
2028);
Tim Peters59c9a642001-09-13 05:38:56 +00002029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030PyTypeObject PyFile_Type = {
2031 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002032 0,
2033 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002035 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002036 (destructor)file_dealloc, /* tp_dealloc */
2037 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 0, /* tp_getattr */
2039 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002040 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002042 0, /* tp_as_number */
2043 0, /* tp_as_sequence */
2044 0, /* tp_as_mapping */
2045 0, /* tp_hash */
2046 0, /* tp_call */
2047 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002049 /* softspace is writable: we must supply tp_setattro */
2050 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002051 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002052 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002053 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002054 0, /* tp_traverse */
2055 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002056 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002057 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002058 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002059 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002060 file_methods, /* tp_methods */
2061 file_memberlist, /* tp_members */
2062 file_getsetlist, /* tp_getset */
2063 0, /* tp_base */
2064 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002065 0, /* tp_descr_get */
2066 0, /* tp_descr_set */
2067 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002068 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002069 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002070 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002071 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002072};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002073
2074/* Interface for the 'soft space' between print items. */
2075
2076int
Fred Drakefd99de62000-07-09 05:02:18 +00002077PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002078{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002079 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002080 if (f == NULL) {
2081 /* Do nothing */
2082 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002083 else if (PyFile_Check(f)) {
2084 oldflag = ((PyFileObject *)f)->f_softspace;
2085 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002086 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002087 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002088 PyObject *v;
2089 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002090 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002091 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002092 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093 if (PyInt_Check(v))
2094 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002095 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002097 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002099 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002101 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2103 PyErr_Clear();
2104 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002105 }
2106 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002107 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002108}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002109
2110/* Interfaces to write objects/strings to file-like objects */
2111
2112int
Fred Drakefd99de62000-07-09 05:02:18 +00002113PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002114{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002116 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002118 return -1;
2119 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002120 else if (PyFile_Check(f)) {
2121 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002122#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002123 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2124 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002125#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002126 if (fp == NULL) {
2127 err_closed();
2128 return -1;
2129 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002130#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002131 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002132 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002133 char *cenc = PyString_AS_STRING(enc);
2134 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2135 if (value == NULL)
2136 return -1;
2137 } else {
2138 value = v;
2139 Py_INCREF(value);
2140 }
2141 result = PyObject_Print(value, fp, flags);
2142 Py_DECREF(value);
2143 return result;
2144#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002145 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002146#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002147 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002148 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002149 if (writer == NULL)
2150 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002151 if (flags & Py_PRINT_RAW) {
2152 if (PyUnicode_Check(v)) {
2153 value = v;
2154 Py_INCREF(value);
2155 } else
2156 value = PyObject_Str(v);
2157 }
2158 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002159 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002160 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002162 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002163 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002164 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002165 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166 Py_DECREF(value);
2167 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002168 return -1;
2169 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002170 result = PyEval_CallObject(writer, args);
2171 Py_DECREF(args);
2172 Py_DECREF(value);
2173 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002174 if (result == NULL)
2175 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002176 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002177 return 0;
2178}
2179
Guido van Rossum27a60b11997-05-22 22:25:11 +00002180int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002181PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002182{
2183 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002184 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002185 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002186 PyErr_SetString(PyExc_SystemError,
2187 "null file for PyFile_WriteString");
2188 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002190 else if (PyFile_Check(f)) {
2191 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002192 if (fp == NULL) {
2193 err_closed();
2194 return -1;
2195 }
2196 fputs(s, fp);
2197 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002198 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 else if (!PyErr_Occurred()) {
2200 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002201 int err;
2202 if (v == NULL)
2203 return -1;
2204 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2205 Py_DECREF(v);
2206 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002207 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002208 else
2209 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002210}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002211
2212/* Try to get a file-descriptor from a Python object. If the object
2213 is an integer or long integer, its value is returned. If not, the
2214 object's fileno() method is called if it exists; the method must return
2215 an integer or long integer, which is returned as the file descriptor value.
2216 -1 is returned on failure.
2217*/
2218
2219int PyObject_AsFileDescriptor(PyObject *o)
2220{
2221 int fd;
2222 PyObject *meth;
2223
2224 if (PyInt_Check(o)) {
2225 fd = PyInt_AsLong(o);
2226 }
2227 else if (PyLong_Check(o)) {
2228 fd = PyLong_AsLong(o);
2229 }
2230 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2231 {
2232 PyObject *fno = PyEval_CallObject(meth, NULL);
2233 Py_DECREF(meth);
2234 if (fno == NULL)
2235 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002236
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002237 if (PyInt_Check(fno)) {
2238 fd = PyInt_AsLong(fno);
2239 Py_DECREF(fno);
2240 }
2241 else if (PyLong_Check(fno)) {
2242 fd = PyLong_AsLong(fno);
2243 Py_DECREF(fno);
2244 }
2245 else {
2246 PyErr_SetString(PyExc_TypeError,
2247 "fileno() returned a non-integer");
2248 Py_DECREF(fno);
2249 return -1;
2250 }
2251 }
2252 else {
2253 PyErr_SetString(PyExc_TypeError,
2254 "argument must be an int, or have a fileno() method.");
2255 return -1;
2256 }
2257
2258 if (fd < 0) {
2259 PyErr_Format(PyExc_ValueError,
2260 "file descriptor cannot be a negative integer (%i)",
2261 fd);
2262 return -1;
2263 }
2264 return fd;
2265}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002266
Jack Jansen7b8c7542002-04-14 20:12:41 +00002267/* From here on we need access to the real fgets and fread */
2268#undef fgets
2269#undef fread
2270
2271/*
2272** Py_UniversalNewlineFgets is an fgets variation that understands
2273** all of \r, \n and \r\n conventions.
2274** The stream should be opened in binary mode.
2275** If fobj is NULL the routine always does newline conversion, and
2276** it may peek one char ahead to gobble the second char in \r\n.
2277** If fobj is non-NULL it must be a PyFileObject. In this case there
2278** is no readahead but in stead a flag is used to skip a following
2279** \n on the next read. Also, if the file is open in binary mode
2280** the whole conversion is skipped. Finally, the routine keeps track of
2281** the different types of newlines seen.
2282** Note that we need no error handling: fgets() treats error and eof
2283** identically.
2284*/
2285char *
2286Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2287{
2288 char *p = buf;
2289 int c;
2290 int newlinetypes = 0;
2291 int skipnextlf = 0;
2292 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002293
Jack Jansen7b8c7542002-04-14 20:12:41 +00002294 if (fobj) {
2295 if (!PyFile_Check(fobj)) {
2296 errno = ENXIO; /* What can you do... */
2297 return NULL;
2298 }
2299 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2300 if ( !univ_newline )
2301 return fgets(buf, n, stream);
2302 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2303 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2304 }
2305 FLOCKFILE(stream);
2306 c = 'x'; /* Shut up gcc warning */
2307 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2308 if (skipnextlf ) {
2309 skipnextlf = 0;
2310 if (c == '\n') {
2311 /* Seeing a \n here with skipnextlf true
2312 ** means we saw a \r before.
2313 */
2314 newlinetypes |= NEWLINE_CRLF;
2315 c = GETC(stream);
2316 if (c == EOF) break;
2317 } else {
2318 /*
2319 ** Note that c == EOF also brings us here,
2320 ** so we're okay if the last char in the file
2321 ** is a CR.
2322 */
2323 newlinetypes |= NEWLINE_CR;
2324 }
2325 }
2326 if (c == '\r') {
2327 /* A \r is translated into a \n, and we skip
2328 ** an adjacent \n, if any. We don't set the
2329 ** newlinetypes flag until we've seen the next char.
2330 */
2331 skipnextlf = 1;
2332 c = '\n';
2333 } else if ( c == '\n') {
2334 newlinetypes |= NEWLINE_LF;
2335 }
2336 *p++ = c;
2337 if (c == '\n') break;
2338 }
2339 if ( c == EOF && skipnextlf )
2340 newlinetypes |= NEWLINE_CR;
2341 FUNLOCKFILE(stream);
2342 *p = '\0';
2343 if (fobj) {
2344 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2345 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2346 } else if ( skipnextlf ) {
2347 /* If we have no file object we cannot save the
2348 ** skipnextlf flag. We have to readahead, which
2349 ** will cause a pause if we're reading from an
2350 ** interactive stream, but that is very unlikely
2351 ** unless we're doing something silly like
2352 ** execfile("/dev/tty").
2353 */
2354 c = GETC(stream);
2355 if ( c != '\n' )
2356 ungetc(c, stream);
2357 }
2358 if (p == buf)
2359 return NULL;
2360 return buf;
2361}
2362
2363/*
2364** Py_UniversalNewlineFread is an fread variation that understands
2365** all of \r, \n and \r\n conventions.
2366** The stream should be opened in binary mode.
2367** fobj must be a PyFileObject. In this case there
2368** is no readahead but in stead a flag is used to skip a following
2369** \n on the next read. Also, if the file is open in binary mode
2370** the whole conversion is skipped. Finally, the routine keeps track of
2371** the different types of newlines seen.
2372*/
2373size_t
Tim Peters058b1412002-04-21 07:29:14 +00002374Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002375 FILE *stream, PyObject *fobj)
2376{
Tim Peters058b1412002-04-21 07:29:14 +00002377 char *dst = buf;
2378 PyFileObject *f = (PyFileObject *)fobj;
2379 int newlinetypes, skipnextlf;
2380
2381 assert(buf != NULL);
2382 assert(stream != NULL);
2383
Jack Jansen7b8c7542002-04-14 20:12:41 +00002384 if (!fobj || !PyFile_Check(fobj)) {
2385 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002386 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002387 }
Tim Peters058b1412002-04-21 07:29:14 +00002388 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002389 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002390 newlinetypes = f->f_newlinetypes;
2391 skipnextlf = f->f_skipnextlf;
2392 /* Invariant: n is the number of bytes remaining to be filled
2393 * in the buffer.
2394 */
2395 while (n) {
2396 size_t nread;
2397 int shortread;
2398 char *src = dst;
2399
2400 nread = fread(dst, 1, n, stream);
2401 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002402 if (nread == 0)
2403 break;
2404
Tim Peterse1682a82002-04-21 18:15:20 +00002405 n -= nread; /* assuming 1 byte out for each in; will adjust */
2406 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002407 while (nread--) {
2408 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002409 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002410 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002411 *dst++ = '\n';
2412 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002413 }
2414 else if (skipnextlf && c == '\n') {
2415 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002416 skipnextlf = 0;
2417 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002418 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002419 }
2420 else {
2421 /* Normal char to be stored in buffer. Also
2422 * update the newlinetypes flag if either this
2423 * is an LF or the previous char was a CR.
2424 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002425 if (c == '\n')
2426 newlinetypes |= NEWLINE_LF;
2427 else if (skipnextlf)
2428 newlinetypes |= NEWLINE_CR;
2429 *dst++ = c;
2430 skipnextlf = 0;
2431 }
2432 }
Tim Peters058b1412002-04-21 07:29:14 +00002433 if (shortread) {
2434 /* If this is EOF, update type flags. */
2435 if (skipnextlf && feof(stream))
2436 newlinetypes |= NEWLINE_CR;
2437 break;
2438 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002439 }
Tim Peters058b1412002-04-21 07:29:14 +00002440 f->f_newlinetypes = newlinetypes;
2441 f->f_skipnextlf = skipnextlf;
2442 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002443}