blob: f96ee7b6111f94fdef2845c5e8de57a4a69d2f74 [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 {
316 file->f_setbuf = PyMem_Realloc(file->f_setbuf, bufsize);
317 }
318#ifdef HAVE_SETVBUF
319 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000320#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000321 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000322#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000323 }
324}
325
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000326/* Set the encoding used to output Unicode strings.
327 Returh 1 on success, 0 on failure. */
328
329int
330PyFile_SetEncoding(PyObject *f, const char *enc)
331{
332 PyFileObject *file = (PyFileObject*)f;
333 PyObject *str = PyString_FromString(enc);
334 if (!str)
335 return 0;
336 Py_DECREF(file->f_encoding);
337 file->f_encoding = str;
338 return 1;
339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000342err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000343{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000345 return NULL;
346}
347
Thomas Woutersc45251a2006-02-12 11:53:32 +0000348/* Refuse regular file I/O if there's data in the iteration-buffer.
349 * Mixing them would cause data to arrive out of order, as the read*
350 * methods don't use the iteration buffer. */
351static PyObject *
352err_iterbuffered(void)
353{
354 PyErr_SetString(PyExc_ValueError,
355 "Mixing iteration and read methods would lose data");
356 return NULL;
357}
358
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000359static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000360
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000361/* Methods */
362
363static void
Fred Drakefd99de62000-07-09 05:02:18 +0000364file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000366 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000367 if (f->weakreflist != NULL)
368 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000369 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000371 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000372 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000373 if (sts == EOF)
374#ifdef HAVE_STRERROR
375 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
376#else
377 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
378#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000379 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000380 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000381 Py_XDECREF(f->f_name);
382 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000383 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000384 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000385 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000386}
387
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000389file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000391 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000392#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000393 PyObject *ret = NULL;
394 PyObject *name;
395 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
396 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
397 f->f_fp == NULL ? "closed" : "open",
398 PyString_AsString(name),
399 PyString_AsString(f->f_mode),
400 f);
401 Py_XDECREF(name);
402 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000403#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000404 } else {
405 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000406 f->f_fp == NULL ? "closed" : "open",
407 PyString_AsString(f->f_name),
408 PyString_AsString(f->f_mode),
409 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000410 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411}
412
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000414file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000416 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000418 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000420 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000421 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000423 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000424 f->f_fp = NULL;
425 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000426 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000427 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000428 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000430 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000431 return PyInt_FromLong((long)sts);
432 Py_INCREF(Py_None);
433 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434}
435
Trent Mickf29f47b2000-08-11 19:02:59 +0000436
Guido van Rossumb8552162001-09-05 14:58:11 +0000437/* Our very own off_t-like type, 64-bit if possible */
438#if !defined(HAVE_LARGEFILE_SUPPORT)
439typedef off_t Py_off_t;
440#elif SIZEOF_OFF_T >= 8
441typedef off_t Py_off_t;
442#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000443typedef fpos_t Py_off_t;
444#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000445#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000446#endif
447
448
Trent Mickf29f47b2000-08-11 19:02:59 +0000449/* a portable fseek() function
450 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000451static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000452_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000453{
Guido van Rossumb8552162001-09-05 14:58:11 +0000454#if !defined(HAVE_LARGEFILE_SUPPORT)
455 return fseek(fp, offset, whence);
456#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000457 return fseeko(fp, offset, whence);
458#elif defined(HAVE_FSEEK64)
459 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000460#elif defined(__BEOS__)
461 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000462#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000463 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
464 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000465 fpos_t pos;
466 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000467 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000468#ifdef MS_WINDOWS
469 fflush(fp);
470 if (_lseeki64(fileno(fp), 0, 2) == -1)
471 return -1;
472#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000473 if (fseek(fp, 0, SEEK_END) != 0)
474 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000475#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000476 /* fall through */
477 case SEEK_CUR:
478 if (fgetpos(fp, &pos) != 0)
479 return -1;
480 offset += pos;
481 break;
482 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000483 }
484 return fsetpos(fp, &offset);
485#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000486#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000487#endif
488}
489
490
491/* a portable ftell() function
492 Return -1 on failure with errno set appropriately, current file
493 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000494static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000495_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000496{
Guido van Rossumb8552162001-09-05 14:58:11 +0000497#if !defined(HAVE_LARGEFILE_SUPPORT)
498 return ftell(fp);
499#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
500 return ftello(fp);
501#elif defined(HAVE_FTELL64)
502 return ftell64(fp);
503#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000504 fpos_t pos;
505 if (fgetpos(fp, &pos) != 0)
506 return -1;
507 return pos;
508#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000509#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000510#endif
511}
512
513
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000515file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000516{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000517 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000518 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000519 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000520 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000521
Guido van Rossumd7297e61992-07-06 14:19:26 +0000522 if (f->f_fp == NULL)
523 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000524 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000525 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000526 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000527 return NULL;
528#if !defined(HAVE_LARGEFILE_SUPPORT)
529 offset = PyInt_AsLong(offobj);
530#else
531 offset = PyLong_Check(offobj) ?
532 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
533#endif
534 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000535 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000536
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000538 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000539 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000541
Guido van Rossumff4949e1992-08-05 19:58:53 +0000542 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000544 clearerr(f->f_fp);
545 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000546 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000547 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 Py_INCREF(Py_None);
549 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000550}
551
Trent Mickf29f47b2000-08-11 19:02:59 +0000552
Guido van Rossumd7047b31995-01-02 19:07:15 +0000553#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000555file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000556{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000557 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000558 PyObject *newsizeobj = NULL;
559 Py_off_t initialpos;
560 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000561
Guido van Rossumd7047b31995-01-02 19:07:15 +0000562 if (f->f_fp == NULL)
563 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000564 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000565 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000566
Tim Petersf1827cf2003-09-07 03:30:18 +0000567 /* Get current file position. If the file happens to be open for
568 * update and the last operation was an input operation, C doesn't
569 * define what the later fflush() will do, but we promise truncate()
570 * won't change the current position (and fflush() *does* change it
571 * then at least on Windows). The easiest thing is to capture
572 * current pos now and seek back to it at the end.
573 */
574 Py_BEGIN_ALLOW_THREADS
575 errno = 0;
576 initialpos = _portable_ftell(f->f_fp);
577 Py_END_ALLOW_THREADS
578 if (initialpos == -1)
579 goto onioerror;
580
Tim Petersfb05db22002-03-11 00:24:00 +0000581 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000582 * specified value.
583 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000584 if (newsizeobj != NULL) {
585#if !defined(HAVE_LARGEFILE_SUPPORT)
586 newsize = PyInt_AsLong(newsizeobj);
587#else
588 newsize = PyLong_Check(newsizeobj) ?
589 PyLong_AsLongLong(newsizeobj) :
590 PyInt_AsLong(newsizeobj);
591#endif
592 if (PyErr_Occurred())
593 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000594 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000595 else /* default to current position */
596 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000597
Tim Petersf1827cf2003-09-07 03:30:18 +0000598 /* Flush the stream. We're mixing stream-level I/O with lower-level
599 * I/O, and a flush may be necessary to synch both platform views
600 * of the current file state.
601 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000602 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000603 errno = 0;
604 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000605 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000606 if (ret != 0)
607 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000608
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000609#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000610 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000611 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000612 {
Tim Petersfb05db22002-03-11 00:24:00 +0000613 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000614
Tim Petersf1827cf2003-09-07 03:30:18 +0000615 /* Have to move current pos to desired endpoint on Windows. */
616 Py_BEGIN_ALLOW_THREADS
617 errno = 0;
618 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
619 Py_END_ALLOW_THREADS
620 if (ret)
621 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000622
Tim Peters8f01b682002-03-12 03:04:44 +0000623 /* Truncate. Note that this may grow the file! */
624 Py_BEGIN_ALLOW_THREADS
625 errno = 0;
626 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000627 ret = hFile == (HANDLE)-1;
628 if (ret == 0) {
629 ret = SetEndOfFile(hFile) == 0;
630 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000631 errno = EACCES;
632 }
633 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000634 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000635 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000636 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000637#else
638 Py_BEGIN_ALLOW_THREADS
639 errno = 0;
640 ret = ftruncate(fileno(f->f_fp), newsize);
641 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000642 if (ret != 0)
643 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000644#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000645
Tim Petersf1827cf2003-09-07 03:30:18 +0000646 /* Restore original file position. */
647 Py_BEGIN_ALLOW_THREADS
648 errno = 0;
649 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
650 Py_END_ALLOW_THREADS
651 if (ret)
652 goto onioerror;
653
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000654 Py_INCREF(Py_None);
655 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000656
657onioerror:
658 PyErr_SetFromErrno(PyExc_IOError);
659 clearerr(f->f_fp);
660 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000661}
662#endif /* HAVE_FTRUNCATE */
663
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000664static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000665file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000666{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000667 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000668
Guido van Rossumd7297e61992-07-06 14:19:26 +0000669 if (f->f_fp == NULL)
670 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000672 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000673 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000675 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000677 clearerr(f->f_fp);
678 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000679 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000680 if (f->f_skipnextlf) {
681 int c;
682 c = GETC(f->f_fp);
683 if (c == '\n') {
684 pos++;
685 f->f_skipnextlf = 0;
686 } else if (c != EOF) ungetc(c, f->f_fp);
687 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000688#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000689 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000690#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000691 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000692#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000693}
694
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000695static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000696file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000697{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000698 if (f->f_fp == NULL)
699 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000700 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000701}
702
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000703static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000704file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000705{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000706 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000707
Guido van Rossumd7297e61992-07-06 14:19:26 +0000708 if (f->f_fp == NULL)
709 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000710 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000711 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000712 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000713 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000714 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000715 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000716 clearerr(f->f_fp);
717 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000718 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000719 Py_INCREF(Py_None);
720 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000721}
722
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000723static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000724file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000725{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000726 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000727 if (f->f_fp == NULL)
728 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000730 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000732 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000733}
734
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000735
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000736#if BUFSIZ < 8192
737#define SMALLCHUNK 8192
738#else
739#define SMALLCHUNK BUFSIZ
740#endif
741
Guido van Rossum3c259041999-01-14 19:00:14 +0000742#if SIZEOF_INT < 4
743#define BIGCHUNK (512 * 32)
744#else
745#define BIGCHUNK (512 * 1024)
746#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000747
748static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000749new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000750{
751#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000752 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000753 struct stat st;
754 if (fstat(fileno(f->f_fp), &st) == 0) {
755 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000756 /* The following is not a bug: we really need to call lseek()
757 *and* ftell(). The reason is that some stdio libraries
758 mistakenly flush their buffer when ftell() is called and
759 the lseek() call it makes fails, thereby throwing away
760 data that cannot be recovered in any way. To avoid this,
761 we first test lseek(), and only call ftell() if lseek()
762 works. We can't use the lseek() value either, because we
763 need to take the amount of buffered data into account.
764 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000765 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000766 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000767 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000768 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000769 if (pos < 0)
770 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000771 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000772 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000773 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000774 }
775#endif
776 if (currentsize > SMALLCHUNK) {
777 /* Keep doubling until we reach BIGCHUNK;
778 then keep adding BIGCHUNK. */
779 if (currentsize <= BIGCHUNK)
780 return currentsize + currentsize;
781 else
782 return currentsize + BIGCHUNK;
783 }
784 return currentsize + SMALLCHUNK;
785}
786
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000787#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
788#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
789#else
790#ifdef EWOULDBLOCK
791#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
792#else
793#ifdef EAGAIN
794#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
795#else
796#define BLOCKED_ERRNO(x) 0
797#endif
798#endif
799#endif
800
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000801static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000802file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000803{
Guido van Rossum789a1611997-05-10 22:33:55 +0000804 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000805 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000807
Guido van Rossumd7297e61992-07-06 14:19:26 +0000808 if (f->f_fp == NULL)
809 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000810 /* refuse to mix with f.next() */
811 if (f->f_buf != NULL &&
812 (f->f_bufend - f->f_bufptr) > 0 &&
813 f->f_buf[0] != '\0')
814 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000815 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000816 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000817 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000818 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000819 else
820 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000821 if (buffersize > INT_MAX) {
822 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000823 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000824 return NULL;
825 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000826 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000827 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000828 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000829 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000830 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000831 Py_BEGIN_ALLOW_THREADS
832 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000833 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000834 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000835 Py_END_ALLOW_THREADS
836 if (chunksize == 0) {
837 if (!ferror(f->f_fp))
838 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000839 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000840 /* When in non-blocking mode, data shouldn't
841 * be discarded if a blocking signal was
842 * received. That will also happen if
843 * chunksize != 0, but bytesread < buffersize. */
844 if (bytesread > 0 && BLOCKED_ERRNO(errno))
845 break;
846 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000847 Py_DECREF(v);
848 return NULL;
849 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000850 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000851 if (bytesread < buffersize) {
852 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000853 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000854 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000855 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000856 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000857 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000858 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000859 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000860 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000861 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000862 }
863 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000864 if (bytesread != buffersize)
865 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000866 return v;
867}
868
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000869static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000870file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000871{
872 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000873 Py_ssize_t ntodo;
874 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000875
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000876 if (f->f_fp == NULL)
877 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000878 /* refuse to mix with f.next() */
879 if (f->f_buf != NULL &&
880 (f->f_bufend - f->f_bufptr) > 0 &&
881 f->f_buf[0] != '\0')
882 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000883 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000884 return NULL;
885 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000886 while (ntodo > 0) {
887 Py_BEGIN_ALLOW_THREADS
888 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000889 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000890 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000891 Py_END_ALLOW_THREADS
892 if (nnow == 0) {
893 if (!ferror(f->f_fp))
894 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000895 PyErr_SetFromErrno(PyExc_IOError);
896 clearerr(f->f_fp);
897 return NULL;
898 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000899 ndone += nnow;
900 ntodo -= nnow;
901 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000902 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000903}
904
Tim Peters86821b22001-01-07 21:19:34 +0000905/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000906Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000907
908Under MSVC 6:
909
Tim Peters1c733232001-01-08 04:02:07 +0000910+ MS threadsafe getc is very slow (multiple layers of function calls before+
911 after each character, to lock+unlock the stream).
912+ The stream-locking functions are MS-internal -- can't access them from user
913 code.
914+ There's nothing Tim could find in the MS C or platform SDK libraries that
915 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000916+ MS fgets locks/unlocks only once per line; it's the only hook we have.
917
918So we use fgets for speed(!), despite that it's painful.
919
920MS realloc is also slow.
921
Tim Petersf29b64d2001-01-15 06:33:19 +0000922Reports from other platforms on this method vs getc_unlocked (which MS doesn't
923have):
924 Linux a wash
925 Solaris a wash
926 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000927
Tim Petersf29b64d2001-01-15 06:33:19 +0000928CAUTION: The C std isn't clear about this: in those cases where fgets
929writes something into the buffer, can it write into any position beyond the
930required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
931known on which it does; and it would be a strange way to code fgets. Still,
932getline_via_fgets may not work correctly if it does. The std test
933test_bufio.py should fail if platform fgets() routinely writes beyond the
934trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000935**************************************************************************/
936
Tim Petersf29b64d2001-01-15 06:33:19 +0000937/* Use this routine if told to, or by default on non-get_unlocked()
938 * platforms unless told not to. Yikes! Let's spell that out:
939 * On a platform with getc_unlocked():
940 * By default, use getc_unlocked().
941 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
942 * On a platform without getc_unlocked():
943 * By default, use fgets().
944 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
945 */
946#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
947#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000948#endif
949
Tim Petersf29b64d2001-01-15 06:33:19 +0000950#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
951#undef USE_FGETS_IN_GETLINE
952#endif
953
954#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000955static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000956getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000957{
Tim Peters15b83852001-01-08 00:53:12 +0000958/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000959 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
960 * to fill this much of the buffer with a known value in order to figure out
961 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
962 * than "most" lines, we waste time filling unused buffer slots. 100 is
963 * surely adequate for most peoples' email archives, chewing over source code,
964 * etc -- "regular old text files".
965 * MAXBUFSIZE is the maximum line length that lets us get away with the less
966 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
967 * cautions about boosting that. 300 was chosen because the worst real-life
968 * text-crunching job reported on Python-Dev was a mail-log crawler where over
969 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000970 */
Tim Peters142297a2001-01-15 10:36:56 +0000971#define INITBUFSIZE 100
972#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000973 char* p; /* temp */
974 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000975 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000976 char* pvfree; /* address of next free slot */
977 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000978 size_t nfree; /* # of free buffer slots; pvend-pvfree */
979 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000980 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000981
Tim Peters15b83852001-01-08 00:53:12 +0000982 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000983 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000984 */
Tim Peters142297a2001-01-15 10:36:56 +0000985 total_v_size = INITBUFSIZE; /* start small and pray */
986 pvfree = buf;
987 for (;;) {
988 Py_BEGIN_ALLOW_THREADS
989 pvend = buf + total_v_size;
990 nfree = pvend - pvfree;
991 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000992 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
993 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +0000994 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000995
Tim Peters142297a2001-01-15 10:36:56 +0000996 if (p == NULL) {
997 clearerr(fp);
998 if (PyErr_CheckSignals())
999 return NULL;
1000 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001001 return v;
1002 }
Tim Peters142297a2001-01-15 10:36:56 +00001003 /* fgets read *something* */
1004 p = memchr(pvfree, '\n', nfree);
1005 if (p != NULL) {
1006 /* Did the \n come from fgets or from us?
1007 * Since fgets stops at the first \n, and then writes
1008 * \0, if it's from fgets a \0 must be next. But if
1009 * that's so, it could not have come from us, since
1010 * the \n's we filled the buffer with have only more
1011 * \n's to the right.
1012 */
1013 if (p+1 < pvend && *(p+1) == '\0') {
1014 /* It's from fgets: we win! In particular,
1015 * we haven't done any mallocs yet, and can
1016 * build the final result on the first try.
1017 */
1018 ++p; /* include \n from fgets */
1019 }
1020 else {
1021 /* Must be from us: fgets didn't fill the
1022 * buffer and didn't find a newline, so it
1023 * must be the last and newline-free line of
1024 * the file.
1025 */
1026 assert(p > pvfree && *(p-1) == '\0');
1027 --p; /* don't include \0 from fgets */
1028 }
1029 v = PyString_FromStringAndSize(buf, p - buf);
1030 return v;
1031 }
1032 /* yuck: fgets overwrote all the newlines, i.e. the entire
1033 * buffer. So this line isn't over yet, or maybe it is but
1034 * we're exactly at EOF. If we haven't already, try using the
1035 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001036 */
Tim Peters142297a2001-01-15 10:36:56 +00001037 assert(*(pvend-1) == '\0');
1038 if (pvfree == buf) {
1039 pvfree = pvend - 1; /* overwrite trailing null */
1040 total_v_size = MAXBUFSIZE;
1041 }
1042 else
1043 break;
Tim Peters86821b22001-01-07 21:19:34 +00001044 }
Tim Peters142297a2001-01-15 10:36:56 +00001045
1046 /* The stack buffer isn't big enough; malloc a string object and read
1047 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001048 */
Tim Petersddea2082002-03-23 10:03:50 +00001049 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001050 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001051 if (v == NULL)
1052 return v;
1053 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001054 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1055 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001056
1057 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001058 * after setting p one beyond the end of the line. The code here is
1059 * very much like the code above, except reads into v's buffer; see
1060 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001061 */
1062 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001063 Py_BEGIN_ALLOW_THREADS
1064 pvend = BUF(v) + total_v_size;
1065 nfree = pvend - pvfree;
1066 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001067 assert(nfree < INT_MAX);
1068 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001069 Py_END_ALLOW_THREADS
1070
1071 if (p == NULL) {
1072 clearerr(fp);
1073 if (PyErr_CheckSignals()) {
1074 Py_DECREF(v);
1075 return NULL;
1076 }
1077 p = pvfree;
1078 break;
1079 }
Tim Peters86821b22001-01-07 21:19:34 +00001080 p = memchr(pvfree, '\n', nfree);
1081 if (p != NULL) {
1082 if (p+1 < pvend && *(p+1) == '\0') {
1083 /* \n came from fgets */
1084 ++p;
1085 break;
1086 }
1087 /* \n came from us; last line of file, no newline */
1088 assert(p > pvfree && *(p-1) == '\0');
1089 --p;
1090 break;
1091 }
1092 /* expand buffer and try again */
1093 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001094 increment = total_v_size >> 2; /* mild exponential growth */
1095 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001096 if (total_v_size > INT_MAX) {
1097 PyErr_SetString(PyExc_OverflowError,
1098 "line is longer than a Python string can hold");
1099 Py_DECREF(v);
1100 return NULL;
1101 }
1102 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1103 return NULL;
1104 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001105 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001106 }
1107 if (BUF(v) + total_v_size != p)
1108 _PyString_Resize(&v, p - BUF(v));
1109 return v;
1110#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001111#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001112}
Tim Petersf29b64d2001-01-15 06:33:19 +00001113#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001114
Guido van Rossum0bd24411991-04-04 15:21:57 +00001115/* Internal routine to get a line.
1116 Size argument interpretation:
1117 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001118 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001119*/
1120
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001121static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001122get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001123{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001124 FILE *fp = f->f_fp;
1125 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001126 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001127 size_t total_v_size; /* total # of slots in buffer */
1128 size_t used_v_size; /* # used slots in buffer */
1129 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001130 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001131 int newlinetypes = f->f_newlinetypes;
1132 int skipnextlf = f->f_skipnextlf;
1133 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001134
Jack Jansen7b8c7542002-04-14 20:12:41 +00001135#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001136 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001137 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001138#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001139 total_v_size = n > 0 ? n : 100;
1140 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001141 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001142 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001143 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001144 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001145
Guido van Rossumce5ba841991-03-06 13:06:18 +00001146 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001147 Py_BEGIN_ALLOW_THREADS
1148 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001149 if (univ_newline) {
1150 c = 'x'; /* Shut up gcc warning */
1151 while ( buf != end && (c = GETC(fp)) != EOF ) {
1152 if (skipnextlf ) {
1153 skipnextlf = 0;
1154 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001155 /* Seeing a \n here with
1156 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001157 * saw a \r before.
1158 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001159 newlinetypes |= NEWLINE_CRLF;
1160 c = GETC(fp);
1161 if (c == EOF) break;
1162 } else {
1163 newlinetypes |= NEWLINE_CR;
1164 }
1165 }
1166 if (c == '\r') {
1167 skipnextlf = 1;
1168 c = '\n';
1169 } else if ( c == '\n')
1170 newlinetypes |= NEWLINE_LF;
1171 *buf++ = c;
1172 if (c == '\n') break;
1173 }
1174 if ( c == EOF && skipnextlf )
1175 newlinetypes |= NEWLINE_CR;
1176 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001177 while ((c = GETC(fp)) != EOF &&
1178 (*buf++ = c) != '\n' &&
1179 buf != end)
1180 ;
1181 FUNLOCKFILE(fp);
1182 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001183 f->f_newlinetypes = newlinetypes;
1184 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001185 if (c == '\n')
1186 break;
1187 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001188 if (ferror(fp)) {
1189 PyErr_SetFromErrno(PyExc_IOError);
1190 clearerr(fp);
1191 Py_DECREF(v);
1192 return NULL;
1193 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001194 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001195 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001196 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001197 return NULL;
1198 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001199 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001200 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001201 /* Must be because buf == end */
1202 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001203 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001204 used_v_size = total_v_size;
1205 increment = total_v_size >> 2; /* mild exponential growth */
1206 total_v_size += increment;
1207 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001208 PyErr_SetString(PyExc_OverflowError,
1209 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001210 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001211 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001212 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001213 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001214 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001215 buf = BUF(v) + used_v_size;
1216 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001217 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001218
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001219 used_v_size = buf - BUF(v);
1220 if (used_v_size != total_v_size)
1221 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001222 return v;
1223}
1224
Guido van Rossum0bd24411991-04-04 15:21:57 +00001225/* External C interface */
1226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001227PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001228PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001229{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001230 PyObject *result;
1231
Guido van Rossum3165fe61992-09-25 21:59:05 +00001232 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001233 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001234 return NULL;
1235 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001236
1237 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001238 PyFileObject *fo = (PyFileObject *)f;
1239 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001240 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001241 /* refuse to mix with f.next() */
1242 if (fo->f_buf != NULL &&
1243 (fo->f_bufend - fo->f_bufptr) > 0 &&
1244 fo->f_buf[0] != '\0')
1245 return err_iterbuffered();
1246 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001247 }
1248 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001249 PyObject *reader;
1250 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001252 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001253 if (reader == NULL)
1254 return NULL;
1255 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001256 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001257 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001258 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001259 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001260 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001261 return NULL;
1262 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001263 result = PyEval_CallObject(reader, args);
1264 Py_DECREF(reader);
1265 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001266 if (result != NULL && !PyString_Check(result) &&
1267 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001268 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001269 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001270 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001271 "object.readline() returned non-string");
1272 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001273 }
1274
1275 if (n < 0 && result != NULL && PyString_Check(result)) {
1276 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001277 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001278 if (len == 0) {
1279 Py_DECREF(result);
1280 result = NULL;
1281 PyErr_SetString(PyExc_EOFError,
1282 "EOF when reading a line");
1283 }
1284 else if (s[len-1] == '\n') {
1285 if (result->ob_refcnt == 1)
1286 _PyString_Resize(&result, len-1);
1287 else {
1288 PyObject *v;
1289 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001290 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001291 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001292 }
1293 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001294 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001295#ifdef Py_USING_UNICODE
1296 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1297 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001298 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001299 if (len == 0) {
1300 Py_DECREF(result);
1301 result = NULL;
1302 PyErr_SetString(PyExc_EOFError,
1303 "EOF when reading a line");
1304 }
1305 else if (s[len-1] == '\n') {
1306 if (result->ob_refcnt == 1)
1307 PyUnicode_Resize(&result, len-1);
1308 else {
1309 PyObject *v;
1310 v = PyUnicode_FromUnicode(s, len-1);
1311 Py_DECREF(result);
1312 result = v;
1313 }
1314 }
1315 }
1316#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001317 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001318}
1319
1320/* Python method */
1321
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001322static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001323file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001324{
Guido van Rossum789a1611997-05-10 22:33:55 +00001325 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001326
Guido van Rossumd7297e61992-07-06 14:19:26 +00001327 if (f->f_fp == NULL)
1328 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001329 /* refuse to mix with f.next() */
1330 if (f->f_buf != NULL &&
1331 (f->f_bufend - f->f_bufptr) > 0 &&
1332 f->f_buf[0] != '\0')
1333 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001334 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001335 return NULL;
1336 if (n == 0)
1337 return PyString_FromString("");
1338 if (n < 0)
1339 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001340 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001341}
1342
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001343static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001344file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001345{
Guido van Rossum789a1611997-05-10 22:33:55 +00001346 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001347 PyObject *list;
1348 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001349 char small_buffer[SMALLCHUNK];
1350 char *buffer = small_buffer;
1351 size_t buffersize = SMALLCHUNK;
1352 PyObject *big_buffer = NULL;
1353 size_t nfilled = 0;
1354 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001355 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001356 char *p, *q, *end;
1357 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001358 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001359
Guido van Rossumd7297e61992-07-06 14:19:26 +00001360 if (f->f_fp == NULL)
1361 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001362 /* refuse to mix with f.next() */
1363 if (f->f_buf != NULL &&
1364 (f->f_bufend - f->f_bufptr) > 0 &&
1365 f->f_buf[0] != '\0')
1366 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001367 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001368 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001369 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001370 return NULL;
1371 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001372 if (shortread)
1373 nread = 0;
1374 else {
1375 Py_BEGIN_ALLOW_THREADS
1376 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001377 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001378 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001379 Py_END_ALLOW_THREADS
1380 shortread = (nread < buffersize-nfilled);
1381 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001382 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001383 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001384 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001385 break;
1386 PyErr_SetFromErrno(PyExc_IOError);
1387 clearerr(f->f_fp);
1388 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001389 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001390 list = NULL;
1391 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001392 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001393 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001394 p = memchr(buffer+nfilled, '\n', nread);
1395 if (p == NULL) {
1396 /* Need a larger buffer to fit this line */
1397 nfilled += nread;
1398 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001399 if (buffersize > INT_MAX) {
1400 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001401 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001402 goto error;
1403 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001404 if (big_buffer == NULL) {
1405 /* Create the big buffer */
1406 big_buffer = PyString_FromStringAndSize(
1407 NULL, buffersize);
1408 if (big_buffer == NULL)
1409 goto error;
1410 buffer = PyString_AS_STRING(big_buffer);
1411 memcpy(buffer, small_buffer, nfilled);
1412 }
1413 else {
1414 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001415 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1416 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001417 buffer = PyString_AS_STRING(big_buffer);
1418 }
1419 continue;
1420 }
1421 end = buffer+nfilled+nread;
1422 q = buffer;
1423 do {
1424 /* Process complete lines */
1425 p++;
1426 line = PyString_FromStringAndSize(q, p-q);
1427 if (line == NULL)
1428 goto error;
1429 err = PyList_Append(list, line);
1430 Py_DECREF(line);
1431 if (err != 0)
1432 goto error;
1433 q = p;
1434 p = memchr(q, '\n', end-q);
1435 } while (p != NULL);
1436 /* Move the remaining incomplete line to the start */
1437 nfilled = end-q;
1438 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001439 if (sizehint > 0)
1440 if (totalread >= (size_t)sizehint)
1441 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001442 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001443 if (nfilled != 0) {
1444 /* Partial last line */
1445 line = PyString_FromStringAndSize(buffer, nfilled);
1446 if (line == NULL)
1447 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001448 if (sizehint > 0) {
1449 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001450 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001451 if (rest == NULL) {
1452 Py_DECREF(line);
1453 goto error;
1454 }
1455 PyString_Concat(&line, rest);
1456 Py_DECREF(rest);
1457 if (line == NULL)
1458 goto error;
1459 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001460 err = PyList_Append(list, line);
1461 Py_DECREF(line);
1462 if (err != 0)
1463 goto error;
1464 }
1465 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001466 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001467 return list;
1468}
1469
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001470static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001471file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001472{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001473 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001474 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001475 if (f->f_fp == NULL)
1476 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001477 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001478 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001479 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001480 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001481 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001482 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001483 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001484 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001485 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001486 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001487 return NULL;
1488 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 Py_INCREF(Py_None);
1490 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001491}
1492
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001493static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001494file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001495{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001496#define CHUNKSIZE 1000
1497 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001498 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001499 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001500 int index, islist;
1501 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001502
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001503 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001504 if (f->f_fp == NULL)
1505 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001506
1507 result = NULL;
1508 list = NULL;
1509 islist = PyList_Check(seq);
1510 if (islist)
1511 it = NULL;
1512 else {
1513 it = PyObject_GetIter(seq);
1514 if (it == NULL) {
1515 PyErr_SetString(PyExc_TypeError,
1516 "writelines() requires an iterable argument");
1517 return NULL;
1518 }
1519 /* From here on, fail by going to error, to reclaim "it". */
1520 list = PyList_New(CHUNKSIZE);
1521 if (list == NULL)
1522 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001523 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001524
1525 /* Strategy: slurp CHUNKSIZE lines into a private list,
1526 checking that they are all strings, then write that list
1527 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001528 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001529 if (islist) {
1530 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001531 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001532 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001533 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001534 j = PyList_GET_SIZE(list);
1535 }
1536 else {
1537 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001538 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001540 if (PyErr_Occurred())
1541 goto error;
1542 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001543 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001544 PyList_SetItem(list, j, line);
1545 }
1546 }
1547 if (j == 0)
1548 break;
1549
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001550 /* Check that all entries are indeed strings. If not,
1551 apply the same rules as for file.write() and
1552 convert the results to strings. This is slow, but
1553 seems to be the only way since all conversion APIs
1554 could potentially execute Python code. */
1555 for (i = 0; i < j; i++) {
1556 PyObject *v = PyList_GET_ITEM(list, i);
1557 if (!PyString_Check(v)) {
1558 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001559 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001560 PyObject_AsReadBuffer(v,
1561 (const void**)&buffer,
1562 &len)) ||
1563 PyObject_AsCharBuffer(v,
1564 &buffer,
1565 &len))) {
1566 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001567 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001568 goto error;
1569 }
1570 line = PyString_FromStringAndSize(buffer,
1571 len);
1572 if (line == NULL)
1573 goto error;
1574 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001575 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001576 }
1577 }
1578
1579 /* Since we are releasing the global lock, the
1580 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001581 Py_BEGIN_ALLOW_THREADS
1582 f->f_softspace = 0;
1583 errno = 0;
1584 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001585 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001586 len = PyString_GET_SIZE(line);
1587 nwritten = fwrite(PyString_AS_STRING(line),
1588 1, len, f->f_fp);
1589 if (nwritten != len) {
1590 Py_BLOCK_THREADS
1591 PyErr_SetFromErrno(PyExc_IOError);
1592 clearerr(f->f_fp);
1593 goto error;
1594 }
1595 }
1596 Py_END_ALLOW_THREADS
1597
1598 if (j < CHUNKSIZE)
1599 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001600 }
1601
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001602 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001603 result = Py_None;
1604 error:
1605 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001606 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001607 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001608#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001609}
1610
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001611static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001612file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001613{
1614 if (f->f_fp == NULL)
1615 return err_closed();
1616 Py_INCREF(f);
1617 return (PyObject *)f;
1618}
1619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001620PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001621"readline([size]) -> next line from the file, as a string.\n"
1622"\n"
1623"Retain newline. A non-negative size argument limits the maximum\n"
1624"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001625"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001627PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001628"read([size]) -> read at most size bytes, returned as a string.\n"
1629"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001630"If the size argument is negative or omitted, read until EOF is reached.\n"
1631"Notice that when in non-blocking mode, less data than what was requested\n"
1632"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001634PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001635"write(str) -> None. Write string str to file.\n"
1636"\n"
1637"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001638"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001640PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001641"fileno() -> integer \"file descriptor\".\n"
1642"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001643"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001646"seek(offset[, whence]) -> None. Move to new file position.\n"
1647"\n"
1648"Argument offset is a byte count. Optional argument whence defaults to\n"
1649"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1650"(move relative to current position, positive or negative), and 2 (move\n"
1651"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001652"seeking beyond the end of a file). If the file is opened in text mode,\n"
1653"only offsets returned by tell() are legal. Use of other offsets causes\n"
1654"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001655"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001656"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001657
Guido van Rossumd7047b31995-01-02 19:07:15 +00001658#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001659PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001660"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1661"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001662"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001663#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001665PyDoc_STRVAR(tell_doc,
1666"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001668PyDoc_STRVAR(readinto_doc,
1669"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001671PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001672"readlines([size]) -> list of strings, each a line from the file.\n"
1673"\n"
1674"Call readline() repeatedly and return a list of the lines so read.\n"
1675"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001676"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001678PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001679"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001680"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001681"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001682"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001683
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001684PyDoc_STRVAR(flush_doc,
1685"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001687PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001688"close() -> None or (perhaps) an integer. Close the file.\n"
1689"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001690"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001691"further I/O operations. close() may be called more than once without\n"
1692"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001693"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001695PyDoc_STRVAR(isatty_doc,
1696"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001697
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001698PyDoc_STRVAR(context_doc,
1699 "__context__() -> self.");
1700
1701PyDoc_STRVAR(enter_doc,
1702 "__enter__() -> self.");
1703
Tim Petersefc3a3a2001-09-20 07:55:22 +00001704static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001705 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1706 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1707 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1708 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1709 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001710#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001711 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001712#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001713 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1714 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1715 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001716 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1717 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1718 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1719 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001720 {"__context__", (PyCFunction)file_self, METH_NOARGS, context_doc},
1721 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Guido van Rossumf6694362006-03-10 02:28:35 +00001722 {"__exit__", (PyCFunction)file_close, METH_VARARGS, close_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001723 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001724};
1725
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001726#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001727
Guido van Rossum6f799372001-09-20 20:46:19 +00001728static PyMemberDef file_memberlist[] = {
1729 {"softspace", T_INT, OFF(f_softspace), 0,
1730 "flag indicating that a space needs to be printed; used by print"},
1731 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001732 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001733 {"name", T_OBJECT, OFF(f_name), RO,
1734 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001735 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1736 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001737 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001738 {NULL} /* Sentinel */
1739};
1740
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001741static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001742get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001743{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001744 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001745}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001746static PyObject *
1747get_newlines(PyFileObject *f, void *closure)
1748{
1749 switch (f->f_newlinetypes) {
1750 case NEWLINE_UNKNOWN:
1751 Py_INCREF(Py_None);
1752 return Py_None;
1753 case NEWLINE_CR:
1754 return PyString_FromString("\r");
1755 case NEWLINE_LF:
1756 return PyString_FromString("\n");
1757 case NEWLINE_CR|NEWLINE_LF:
1758 return Py_BuildValue("(ss)", "\r", "\n");
1759 case NEWLINE_CRLF:
1760 return PyString_FromString("\r\n");
1761 case NEWLINE_CR|NEWLINE_CRLF:
1762 return Py_BuildValue("(ss)", "\r", "\r\n");
1763 case NEWLINE_LF|NEWLINE_CRLF:
1764 return Py_BuildValue("(ss)", "\n", "\r\n");
1765 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1766 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1767 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001768 PyErr_Format(PyExc_SystemError,
1769 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001770 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001771 return NULL;
1772 }
1773}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001774
Guido van Rossum32d34c82001-09-20 21:45:26 +00001775static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001776 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001777 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001778 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779 {0},
1780};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001781
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001782static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001783drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001784{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001785 if (f->f_buf != NULL) {
1786 PyMem_Free(f->f_buf);
1787 f->f_buf = NULL;
1788 }
Guido van Rossum65967252001-04-21 13:20:18 +00001789}
1790
Tim Petersf1827cf2003-09-07 03:30:18 +00001791/* Make sure that file has a readahead buffer with at least one byte
1792 (unless at EOF) and no more than bufsize. Returns negative value on
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001793 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001794static int
1795readahead(PyFileObject *f, int bufsize)
1796{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001797 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001798
1799 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001800 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001801 return 0;
1802 else
1803 drop_readahead(f);
1804 }
1805 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1806 return -1;
1807 }
1808 Py_BEGIN_ALLOW_THREADS
1809 errno = 0;
1810 chunksize = Py_UniversalNewlineFread(
1811 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1812 Py_END_ALLOW_THREADS
1813 if (chunksize == 0) {
1814 if (ferror(f->f_fp)) {
1815 PyErr_SetFromErrno(PyExc_IOError);
1816 clearerr(f->f_fp);
1817 drop_readahead(f);
1818 return -1;
1819 }
1820 }
1821 f->f_bufptr = f->f_buf;
1822 f->f_bufend = f->f_buf + chunksize;
1823 return 0;
1824}
1825
1826/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001827 uninitialized bytes followed by the remainder of the line. Don't be
1828 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001829 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1830
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001831static PyStringObject *
1832readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1833{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001834 PyStringObject* s;
1835 char *bufptr;
1836 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001837 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001838
1839 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001840 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001841 return NULL;
1842
1843 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001844 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001845 return (PyStringObject *)
1846 PyString_FromStringAndSize(NULL, skip);
1847 bufptr = memchr(f->f_bufptr, '\n', len);
1848 if (bufptr != NULL) {
1849 bufptr++; /* Count the '\n' */
1850 len = bufptr - f->f_bufptr;
1851 s = (PyStringObject *)
1852 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001853 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001854 return NULL;
1855 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1856 f->f_bufptr = bufptr;
1857 if (bufptr == f->f_bufend)
1858 drop_readahead(f);
1859 } else {
1860 bufptr = f->f_bufptr;
1861 buf = f->f_buf;
1862 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001863 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001864 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001865 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001866 if (s == NULL) {
1867 PyMem_Free(buf);
1868 return NULL;
1869 }
1870 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1871 PyMem_Free(buf);
1872 }
1873 return s;
1874}
1875
1876/* A larger buffer size may actually decrease performance. */
1877#define READAHEAD_BUFSIZE 8192
1878
1879static PyObject *
1880file_iternext(PyFileObject *f)
1881{
1882 PyStringObject* l;
1883
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001884 if (f->f_fp == NULL)
1885 return err_closed();
1886
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001887 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1888 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1889 Py_XDECREF(l);
1890 return NULL;
1891 }
1892 return (PyObject *)l;
1893}
1894
1895
Tim Peters59c9a642001-09-13 05:38:56 +00001896static PyObject *
1897file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1898{
Tim Peters44410012001-09-14 03:26:08 +00001899 PyObject *self;
1900 static PyObject *not_yet_string;
1901
1902 assert(type != NULL && type->tp_alloc != NULL);
1903
1904 if (not_yet_string == NULL) {
1905 not_yet_string = PyString_FromString("<uninitialized file>");
1906 if (not_yet_string == NULL)
1907 return NULL;
1908 }
1909
1910 self = type->tp_alloc(type, 0);
1911 if (self != NULL) {
1912 /* Always fill in the name and mode, so that nobody else
1913 needs to special-case NULLs there. */
1914 Py_INCREF(not_yet_string);
1915 ((PyFileObject *)self)->f_name = not_yet_string;
1916 Py_INCREF(not_yet_string);
1917 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001918 Py_INCREF(Py_None);
1919 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001920 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001921 }
1922 return self;
1923}
1924
1925static int
1926file_init(PyObject *self, PyObject *args, PyObject *kwds)
1927{
1928 PyFileObject *foself = (PyFileObject *)self;
1929 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001930 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001931 char *name = NULL;
1932 char *mode = "r";
1933 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001934 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001935
1936 assert(PyFile_Check(self));
1937 if (foself->f_fp != NULL) {
1938 /* Have to close the existing file first. */
1939 PyObject *closeresult = file_close(foself);
1940 if (closeresult == NULL)
1941 return -1;
1942 Py_DECREF(closeresult);
1943 }
Tim Peters59c9a642001-09-13 05:38:56 +00001944
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001945#ifdef Py_WIN_WIDE_FILENAMES
1946 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1947 PyObject *po;
1948 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1949 kwlist, &po, &mode, &bufsize)) {
1950 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001951 if (fill_file_fields(foself, NULL, po, mode,
1952 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001953 goto Error;
1954 } else {
1955 /* Drop the argument parsing error as narrow
1956 strings are also valid. */
1957 PyErr_Clear();
1958 }
1959 }
1960#endif
1961
1962 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001963 PyObject *o_name;
1964
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001965 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1966 Py_FileSystemDefaultEncoding,
1967 &name,
1968 &mode, &bufsize))
1969 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001970
1971 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001972 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1973 kwlist, &o_name, &mode,
1974 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001975 return -1;
1976
1977 if (fill_file_fields(foself, NULL, o_name, mode,
1978 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001979 goto Error;
1980 }
Tim Peters44410012001-09-14 03:26:08 +00001981 if (open_the_file(foself, name, mode) == NULL)
1982 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001983 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001984 PyFile_SetBufSize(self, bufsize);
1985 goto Done;
1986
1987Error:
1988 ret = -1;
1989 /* fall through */
1990Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001991 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001992 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001993}
1994
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001995PyDoc_VAR(file_doc) =
1996PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001997"file(name[, mode[, buffering]]) -> file object\n"
1998"\n"
1999"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2000"writing or appending. The file will be created if it doesn't exist\n"
2001"when opened for writing or appending; it will be truncated when\n"
2002"opened for writing. Add a 'b' to the mode for binary files.\n"
2003"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2004"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002005"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002006)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002007PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002008"Add a 'U' to mode to open the file for input with universal newline\n"
2009"support. Any line ending in the input file will be seen as a '\\n'\n"
2010"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2011"the value for this attribute is one of None (no newline read yet),\n"
2012"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2013"\n"
2014"'U' cannot be combined with 'w' or '+' mode.\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"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002018"Note: open() is an alias for file()."
2019);
Tim Peters59c9a642001-09-13 05:38:56 +00002020
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002021PyTypeObject PyFile_Type = {
2022 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002023 0,
2024 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002025 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002026 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002027 (destructor)file_dealloc, /* tp_dealloc */
2028 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 0, /* tp_getattr */
2030 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002031 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002033 0, /* tp_as_number */
2034 0, /* tp_as_sequence */
2035 0, /* tp_as_mapping */
2036 0, /* tp_hash */
2037 0, /* tp_call */
2038 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002040 /* softspace is writable: we must supply tp_setattro */
2041 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002042 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002043 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002044 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 0, /* tp_traverse */
2046 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002047 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002048 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002049 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002050 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051 file_methods, /* tp_methods */
2052 file_memberlist, /* tp_members */
2053 file_getsetlist, /* tp_getset */
2054 0, /* tp_base */
2055 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002056 0, /* tp_descr_get */
2057 0, /* tp_descr_set */
2058 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00002059 (initproc)file_init, /* tp_init */
2060 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002061 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002062 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002063};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002064
2065/* Interface for the 'soft space' between print items. */
2066
2067int
Fred Drakefd99de62000-07-09 05:02:18 +00002068PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002069{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002070 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002071 if (f == NULL) {
2072 /* Do nothing */
2073 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074 else if (PyFile_Check(f)) {
2075 oldflag = ((PyFileObject *)f)->f_softspace;
2076 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002077 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002078 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002079 PyObject *v;
2080 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002081 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002083 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002084 if (PyInt_Check(v))
2085 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002086 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002087 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002088 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002089 v = PyInt_FromLong((long)newflag);
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 (PyObject_SetAttrString(f, "softspace", v) != 0)
2094 PyErr_Clear();
2095 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002096 }
2097 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002098 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002099}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002100
2101/* Interfaces to write objects/strings to file-like objects */
2102
2103int
Fred Drakefd99de62000-07-09 05:02:18 +00002104PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002105{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002107 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002109 return -1;
2110 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002111 else if (PyFile_Check(f)) {
2112 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002113#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002114 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2115 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002116#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002117 if (fp == NULL) {
2118 err_closed();
2119 return -1;
2120 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002121#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002122 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002123 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002124 char *cenc = PyString_AS_STRING(enc);
2125 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2126 if (value == NULL)
2127 return -1;
2128 } else {
2129 value = v;
2130 Py_INCREF(value);
2131 }
2132 result = PyObject_Print(value, fp, flags);
2133 Py_DECREF(value);
2134 return result;
2135#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002137#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002138 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002139 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002140 if (writer == NULL)
2141 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002142 if (flags & Py_PRINT_RAW) {
2143 if (PyUnicode_Check(v)) {
2144 value = v;
2145 Py_INCREF(value);
2146 } else
2147 value = PyObject_Str(v);
2148 }
2149 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002151 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002152 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002153 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002154 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002155 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002156 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157 Py_DECREF(value);
2158 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002159 return -1;
2160 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 result = PyEval_CallObject(writer, args);
2162 Py_DECREF(args);
2163 Py_DECREF(value);
2164 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002165 if (result == NULL)
2166 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002168 return 0;
2169}
2170
Guido van Rossum27a60b11997-05-22 22:25:11 +00002171int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002172PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002173{
2174 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002175 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002176 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002177 PyErr_SetString(PyExc_SystemError,
2178 "null file for PyFile_WriteString");
2179 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002180 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002181 else if (PyFile_Check(f)) {
2182 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002183 if (fp == NULL) {
2184 err_closed();
2185 return -1;
2186 }
2187 fputs(s, fp);
2188 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002190 else if (!PyErr_Occurred()) {
2191 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002192 int err;
2193 if (v == NULL)
2194 return -1;
2195 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2196 Py_DECREF(v);
2197 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002198 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002199 else
2200 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002201}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002202
2203/* Try to get a file-descriptor from a Python object. If the object
2204 is an integer or long integer, its value is returned. If not, the
2205 object's fileno() method is called if it exists; the method must return
2206 an integer or long integer, which is returned as the file descriptor value.
2207 -1 is returned on failure.
2208*/
2209
2210int PyObject_AsFileDescriptor(PyObject *o)
2211{
2212 int fd;
2213 PyObject *meth;
2214
2215 if (PyInt_Check(o)) {
2216 fd = PyInt_AsLong(o);
2217 }
2218 else if (PyLong_Check(o)) {
2219 fd = PyLong_AsLong(o);
2220 }
2221 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2222 {
2223 PyObject *fno = PyEval_CallObject(meth, NULL);
2224 Py_DECREF(meth);
2225 if (fno == NULL)
2226 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002227
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002228 if (PyInt_Check(fno)) {
2229 fd = PyInt_AsLong(fno);
2230 Py_DECREF(fno);
2231 }
2232 else if (PyLong_Check(fno)) {
2233 fd = PyLong_AsLong(fno);
2234 Py_DECREF(fno);
2235 }
2236 else {
2237 PyErr_SetString(PyExc_TypeError,
2238 "fileno() returned a non-integer");
2239 Py_DECREF(fno);
2240 return -1;
2241 }
2242 }
2243 else {
2244 PyErr_SetString(PyExc_TypeError,
2245 "argument must be an int, or have a fileno() method.");
2246 return -1;
2247 }
2248
2249 if (fd < 0) {
2250 PyErr_Format(PyExc_ValueError,
2251 "file descriptor cannot be a negative integer (%i)",
2252 fd);
2253 return -1;
2254 }
2255 return fd;
2256}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002257
Jack Jansen7b8c7542002-04-14 20:12:41 +00002258/* From here on we need access to the real fgets and fread */
2259#undef fgets
2260#undef fread
2261
2262/*
2263** Py_UniversalNewlineFgets is an fgets variation that understands
2264** all of \r, \n and \r\n conventions.
2265** The stream should be opened in binary mode.
2266** If fobj is NULL the routine always does newline conversion, and
2267** it may peek one char ahead to gobble the second char in \r\n.
2268** If fobj is non-NULL it must be a PyFileObject. In this case there
2269** is no readahead but in stead a flag is used to skip a following
2270** \n on the next read. Also, if the file is open in binary mode
2271** the whole conversion is skipped. Finally, the routine keeps track of
2272** the different types of newlines seen.
2273** Note that we need no error handling: fgets() treats error and eof
2274** identically.
2275*/
2276char *
2277Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2278{
2279 char *p = buf;
2280 int c;
2281 int newlinetypes = 0;
2282 int skipnextlf = 0;
2283 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002284
Jack Jansen7b8c7542002-04-14 20:12:41 +00002285 if (fobj) {
2286 if (!PyFile_Check(fobj)) {
2287 errno = ENXIO; /* What can you do... */
2288 return NULL;
2289 }
2290 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2291 if ( !univ_newline )
2292 return fgets(buf, n, stream);
2293 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2294 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2295 }
2296 FLOCKFILE(stream);
2297 c = 'x'; /* Shut up gcc warning */
2298 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2299 if (skipnextlf ) {
2300 skipnextlf = 0;
2301 if (c == '\n') {
2302 /* Seeing a \n here with skipnextlf true
2303 ** means we saw a \r before.
2304 */
2305 newlinetypes |= NEWLINE_CRLF;
2306 c = GETC(stream);
2307 if (c == EOF) break;
2308 } else {
2309 /*
2310 ** Note that c == EOF also brings us here,
2311 ** so we're okay if the last char in the file
2312 ** is a CR.
2313 */
2314 newlinetypes |= NEWLINE_CR;
2315 }
2316 }
2317 if (c == '\r') {
2318 /* A \r is translated into a \n, and we skip
2319 ** an adjacent \n, if any. We don't set the
2320 ** newlinetypes flag until we've seen the next char.
2321 */
2322 skipnextlf = 1;
2323 c = '\n';
2324 } else if ( c == '\n') {
2325 newlinetypes |= NEWLINE_LF;
2326 }
2327 *p++ = c;
2328 if (c == '\n') break;
2329 }
2330 if ( c == EOF && skipnextlf )
2331 newlinetypes |= NEWLINE_CR;
2332 FUNLOCKFILE(stream);
2333 *p = '\0';
2334 if (fobj) {
2335 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2336 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2337 } else if ( skipnextlf ) {
2338 /* If we have no file object we cannot save the
2339 ** skipnextlf flag. We have to readahead, which
2340 ** will cause a pause if we're reading from an
2341 ** interactive stream, but that is very unlikely
2342 ** unless we're doing something silly like
2343 ** execfile("/dev/tty").
2344 */
2345 c = GETC(stream);
2346 if ( c != '\n' )
2347 ungetc(c, stream);
2348 }
2349 if (p == buf)
2350 return NULL;
2351 return buf;
2352}
2353
2354/*
2355** Py_UniversalNewlineFread is an fread variation that understands
2356** all of \r, \n and \r\n conventions.
2357** The stream should be opened in binary mode.
2358** fobj must be a PyFileObject. In this case there
2359** is no readahead but in stead a flag is used to skip a following
2360** \n on the next read. Also, if the file is open in binary mode
2361** the whole conversion is skipped. Finally, the routine keeps track of
2362** the different types of newlines seen.
2363*/
2364size_t
Tim Peters058b1412002-04-21 07:29:14 +00002365Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002366 FILE *stream, PyObject *fobj)
2367{
Tim Peters058b1412002-04-21 07:29:14 +00002368 char *dst = buf;
2369 PyFileObject *f = (PyFileObject *)fobj;
2370 int newlinetypes, skipnextlf;
2371
2372 assert(buf != NULL);
2373 assert(stream != NULL);
2374
Jack Jansen7b8c7542002-04-14 20:12:41 +00002375 if (!fobj || !PyFile_Check(fobj)) {
2376 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002377 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002378 }
Tim Peters058b1412002-04-21 07:29:14 +00002379 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002380 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002381 newlinetypes = f->f_newlinetypes;
2382 skipnextlf = f->f_skipnextlf;
2383 /* Invariant: n is the number of bytes remaining to be filled
2384 * in the buffer.
2385 */
2386 while (n) {
2387 size_t nread;
2388 int shortread;
2389 char *src = dst;
2390
2391 nread = fread(dst, 1, n, stream);
2392 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002393 if (nread == 0)
2394 break;
2395
Tim Peterse1682a82002-04-21 18:15:20 +00002396 n -= nread; /* assuming 1 byte out for each in; will adjust */
2397 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002398 while (nread--) {
2399 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002400 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002401 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002402 *dst++ = '\n';
2403 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002404 }
2405 else if (skipnextlf && c == '\n') {
2406 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002407 skipnextlf = 0;
2408 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002409 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002410 }
2411 else {
2412 /* Normal char to be stored in buffer. Also
2413 * update the newlinetypes flag if either this
2414 * is an LF or the previous char was a CR.
2415 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002416 if (c == '\n')
2417 newlinetypes |= NEWLINE_LF;
2418 else if (skipnextlf)
2419 newlinetypes |= NEWLINE_CR;
2420 *dst++ = c;
2421 skipnextlf = 0;
2422 }
2423 }
Tim Peters058b1412002-04-21 07:29:14 +00002424 if (shortread) {
2425 /* If this is EOF, update type flags. */
2426 if (skipnextlf && feof(stream))
2427 newlinetypes |= NEWLINE_CR;
2428 break;
2429 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002430 }
Tim Peters058b1412002-04-21 07:29:14 +00002431 f->f_newlinetypes = newlinetypes;
2432 f->f_skipnextlf = skipnextlf;
2433 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002434}