blob: 632ab04180207b418778f04da080bb6b8b5a8b39 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossumff7e83d1999-08-27 20:39:37 +00007#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00009#endif /* DONT_HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Mark Hammondc2e85bd2002-10-03 05:10:39 +000019#ifdef _MSC_VER
20/* Need GetVersion to see if on NT so safe to use _wfopen */
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#endif /* _MSC_VER */
24
Andrew MacIntyrec4874392002-02-26 11:36:35 +000025#if defined(PYOS_OS2) && defined(PYCC_GCC)
26#include <io.h>
27#endif
28
Guido van Rossumc0b618a1997-05-02 03:12:38 +000029#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000030
Guido van Rossumff7e83d1999-08-27 20:39:37 +000031#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000032#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000033#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Jack Jansen7b8c7542002-04-14 20:12:41 +000035#ifdef HAVE_GETC_UNLOCKED
36#define GETC(f) getc_unlocked(f)
37#define FLOCKFILE(f) flockfile(f)
38#define FUNLOCKFILE(f) funlockfile(f)
39#else
40#define GETC(f) getc(f)
41#define FLOCKFILE(f)
42#define FUNLOCKFILE(f)
43#endif
44
Jack Jansen7b8c7542002-04-14 20:12:41 +000045/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000050
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051#ifdef __cplusplus
52extern "C" {
53#endif
54
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000056PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000060 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062}
63
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000065PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000068 return NULL;
69 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000070 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000071}
72
Neil Schemenauered19b882002-03-23 02:06:50 +000073/* On Unix, fopen will succeed for directories.
74 In Python, there should be no file objects referring to
75 directories, so we need a check. */
76
77static PyFileObject*
78dircheck(PyFileObject* f)
79{
80#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
81 struct stat buf;
82 if (f->f_fp == NULL)
83 return f;
84 if (fstat(fileno(f->f_fp), &buf) == 0 &&
85 S_ISDIR(buf.st_mode)) {
86#ifdef HAVE_STRERROR
87 char *msg = strerror(EISDIR);
88#else
89 char *msg = "Is a directory";
90#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000091 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000092 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000093 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000094 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000095 return NULL;
96 }
97#endif
98 return f;
99}
100
Tim Peters59c9a642001-09-13 05:38:56 +0000101
102static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000103fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
104 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105{
Tim Peters59c9a642001-09-13 05:38:56 +0000106 assert(f != NULL);
107 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000108 assert(f->f_fp == NULL);
109
110 Py_DECREF(f->f_name);
111 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000112 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000113
114 Py_INCREF (name);
115 f->f_name = name;
116
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000118
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000119 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000120 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000121 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000122 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000123 f->f_univ_newline = (strchr(mode, 'U') != NULL);
124 f->f_newlinetypes = NEWLINE_UNKNOWN;
125 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000126 Py_INCREF(Py_None);
127 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000128
Tim Peters59c9a642001-09-13 05:38:56 +0000129 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000132 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000136/* check for known incorrect mode strings - problem is, platforms are
137 free to accept any mode characters they like and are supposed to
138 ignore stuff they don't understand... write or append mode with
139 universal newline support is expressly forbidden by PEP 278. */
140/* zero return is kewl - one is un-kewl */
141static int
142check_the_mode(char *mode)
143{
Neal Norwitz76dc0812006-01-08 06:13:13 +0000144 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000145
146 switch (len) {
147 case 0:
148 PyErr_SetString(PyExc_ValueError, "empty mode string");
149 return 1;
150
151 /* reject wU, aU */
152 case 2:
153 switch (mode[0]) {
154 case 'w':
155 case 'a':
156 if (mode[1] == 'U') {
157 PyErr_SetString(PyExc_ValueError,
158 "invalid mode string");
159 return 1;
160 }
161 break;
162 }
163 break;
164
165 /* reject w+U, a+U, wU+, aU+ */
166 case 3:
167 switch (mode[0]) {
168 case 'w':
169 case 'a':
170 if ((mode[1] == '+' && mode[2] == 'U') ||
171 (mode[1] == 'U' && mode[2] == '+')) {
172 PyErr_SetString(PyExc_ValueError,
173 "invalid mode string");
174 return 1;
175 }
176 break;
177 }
178 break;
179 }
180
181 return 0;
182}
183
Tim Peters59c9a642001-09-13 05:38:56 +0000184static PyObject *
185open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
Tim Peters59c9a642001-09-13 05:38:56 +0000187 assert(f != NULL);
188 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000189#ifdef MS_WINDOWS
190 /* windows ignores the passed name in order to support Unicode */
191 assert(f->f_name != NULL);
192#else
Tim Peters59c9a642001-09-13 05:38:56 +0000193 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000194#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000195 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000196 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000197
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000198 if (check_the_mode(mode))
199 return NULL;
200
Tim Peters8fa45672001-09-13 21:01:29 +0000201 /* rexec.py can't stop a user from getting the file() constructor --
202 all they have to do is get *any* file object f, and then do
203 type(f). Here we prevent them from doing damage with it. */
204 if (PyEval_GetRestricted()) {
205 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000206 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000207 return NULL;
208 }
Tim Petersa27a1502001-11-09 20:59:14 +0000209 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000210
211 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
212 mode = "rb";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000213#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000214 if (PyUnicode_Check(f->f_name)) {
215 PyObject *wmode;
216 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
217 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000218 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000219 /* PyUnicode_AS_UNICODE OK without thread
220 lock as it is a simple dereference. */
221 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
222 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000223 Py_END_ALLOW_THREADS
224 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000225 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000226 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000227#endif
228 if (NULL == f->f_fp && NULL != name) {
229 Py_BEGIN_ALLOW_THREADS
230 f->f_fp = fopen(name, mode);
231 Py_END_ALLOW_THREADS
232 }
233
Guido van Rossuma08095a1991-02-13 23:25:27 +0000234 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000235#ifdef _MSC_VER
236 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
237 * across all Windows flavors. When it sets EINVAL varies
238 * across Windows flavors, the exact conditions aren't
239 * documented, and the answer lies in the OS's implementation
240 * of Win32's CreateFile function (whose source is secret).
241 * Seems the best we can do is map EINVAL to ENOENT.
242 */
243 if (errno == 0) /* bad mode string */
244 errno = EINVAL;
245 else if (errno == EINVAL) /* unknown, but not a mode string */
246 errno = ENOENT;
247#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000248 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000249 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000250 mode);
251 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000252 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000253 f = NULL;
254 }
Tim Peters2ea91112002-04-08 04:13:12 +0000255 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000256 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000257 return (PyObject *)f;
258}
259
260PyObject *
261PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
262{
Tim Peters44410012001-09-14 03:26:08 +0000263 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
264 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000265 if (f != NULL) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000266 PyObject *o_name = PyString_FromString(name);
267 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000268 Py_DECREF(f);
269 f = NULL;
270 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000271 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000272 }
273 return (PyObject *) f;
274}
275
276PyObject *
277PyFile_FromString(char *name, char *mode)
278{
279 extern int fclose(FILE *);
280 PyFileObject *f;
281
282 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
283 if (f != NULL) {
284 if (open_the_file(f, name, mode) == NULL) {
285 Py_DECREF(f);
286 f = NULL;
287 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000289 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000290}
291
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292void
Fred Drakefd99de62000-07-09 05:02:18 +0000293PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000294{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000295 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000296 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297 int type;
298 switch (bufsize) {
299 case 0:
300 type = _IONBF;
301 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000302#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303 case 1:
304 type = _IOLBF;
305 bufsize = BUFSIZ;
306 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000307#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308 default:
309 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000310#ifndef HAVE_SETVBUF
311 bufsize = BUFSIZ;
312#endif
313 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000315 fflush(file->f_fp);
316 if (type == _IONBF) {
317 PyMem_Free(file->f_setbuf);
318 file->f_setbuf = NULL;
319 } else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
321 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000322 }
323#ifdef HAVE_SETVBUF
324 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000325#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000326 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000327#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000328 }
329}
330
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000331/* Set the encoding used to output Unicode strings.
332 Returh 1 on success, 0 on failure. */
333
334int
335PyFile_SetEncoding(PyObject *f, const char *enc)
336{
337 PyFileObject *file = (PyFileObject*)f;
338 PyObject *str = PyString_FromString(enc);
339 if (!str)
340 return 0;
341 Py_DECREF(file->f_encoding);
342 file->f_encoding = str;
343 return 1;
344}
345
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000346static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000347err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000348{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000349 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000350 return NULL;
351}
352
Thomas Woutersc45251a2006-02-12 11:53:32 +0000353/* Refuse regular file I/O if there's data in the iteration-buffer.
354 * Mixing them would cause data to arrive out of order, as the read*
355 * methods don't use the iteration buffer. */
356static PyObject *
357err_iterbuffered(void)
358{
359 PyErr_SetString(PyExc_ValueError,
360 "Mixing iteration and read methods would lose data");
361 return NULL;
362}
363
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000364static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000365
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366/* Methods */
367
368static void
Fred Drakefd99de62000-07-09 05:02:18 +0000369file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000371 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000372 if (f->weakreflist != NULL)
373 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000374 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000376 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000378 if (sts == EOF)
379#ifdef HAVE_STRERROR
380 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
381#else
382 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
383#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000384 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000385 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000386 Py_XDECREF(f->f_name);
387 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000388 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000389 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000390 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391}
392
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000394file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000396 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000397#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000398 PyObject *ret = NULL;
399 PyObject *name;
400 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
401 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
402 f->f_fp == NULL ? "closed" : "open",
403 PyString_AsString(name),
404 PyString_AsString(f->f_mode),
405 f);
406 Py_XDECREF(name);
407 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000408#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000409 } else {
410 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000411 f->f_fp == NULL ? "closed" : "open",
412 PyString_AsString(f->f_name),
413 PyString_AsString(f->f_mode),
414 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000415 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416}
417
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000419file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000420{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000421 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000423 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000425 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000426 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000427 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000428 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429 f->f_fp = NULL;
430 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000431 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000432 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000433 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000435 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436 return PyInt_FromLong((long)sts);
437 Py_INCREF(Py_None);
438 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439}
440
Trent Mickf29f47b2000-08-11 19:02:59 +0000441
Guido van Rossumb8552162001-09-05 14:58:11 +0000442/* Our very own off_t-like type, 64-bit if possible */
443#if !defined(HAVE_LARGEFILE_SUPPORT)
444typedef off_t Py_off_t;
445#elif SIZEOF_OFF_T >= 8
446typedef off_t Py_off_t;
447#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000448typedef fpos_t Py_off_t;
449#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000450#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000451#endif
452
453
Trent Mickf29f47b2000-08-11 19:02:59 +0000454/* a portable fseek() function
455 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000456static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000457_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000458{
Guido van Rossumb8552162001-09-05 14:58:11 +0000459#if !defined(HAVE_LARGEFILE_SUPPORT)
460 return fseek(fp, offset, whence);
461#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000462 return fseeko(fp, offset, whence);
463#elif defined(HAVE_FSEEK64)
464 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000465#elif defined(__BEOS__)
466 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000467#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000468 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
469 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000470 fpos_t pos;
471 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000472 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000473#ifdef MS_WINDOWS
474 fflush(fp);
475 if (_lseeki64(fileno(fp), 0, 2) == -1)
476 return -1;
477#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000478 if (fseek(fp, 0, SEEK_END) != 0)
479 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000480#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000481 /* fall through */
482 case SEEK_CUR:
483 if (fgetpos(fp, &pos) != 0)
484 return -1;
485 offset += pos;
486 break;
487 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000488 }
489 return fsetpos(fp, &offset);
490#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000491#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000492#endif
493}
494
495
496/* a portable ftell() function
497 Return -1 on failure with errno set appropriately, current file
498 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000499static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000500_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000501{
Guido van Rossumb8552162001-09-05 14:58:11 +0000502#if !defined(HAVE_LARGEFILE_SUPPORT)
503 return ftell(fp);
504#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
505 return ftello(fp);
506#elif defined(HAVE_FTELL64)
507 return ftell64(fp);
508#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000509 fpos_t pos;
510 if (fgetpos(fp, &pos) != 0)
511 return -1;
512 return pos;
513#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000514#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000515#endif
516}
517
518
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000520file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000522 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000523 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000524 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000525 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000526
Guido van Rossumd7297e61992-07-06 14:19:26 +0000527 if (f->f_fp == NULL)
528 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000529 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000530 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000531 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000532 return NULL;
533#if !defined(HAVE_LARGEFILE_SUPPORT)
534 offset = PyInt_AsLong(offobj);
535#else
536 offset = PyLong_Check(offobj) ?
537 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
538#endif
539 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000540 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000543 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000544 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000546
Guido van Rossumff4949e1992-08-05 19:58:53 +0000547 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000549 clearerr(f->f_fp);
550 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000551 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000552 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553 Py_INCREF(Py_None);
554 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000555}
556
Trent Mickf29f47b2000-08-11 19:02:59 +0000557
Guido van Rossumd7047b31995-01-02 19:07:15 +0000558#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000560file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000561{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000562 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000563 PyObject *newsizeobj = NULL;
564 Py_off_t initialpos;
565 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000566
Guido van Rossumd7047b31995-01-02 19:07:15 +0000567 if (f->f_fp == NULL)
568 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000569 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000570 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000571
Tim Petersf1827cf2003-09-07 03:30:18 +0000572 /* Get current file position. If the file happens to be open for
573 * update and the last operation was an input operation, C doesn't
574 * define what the later fflush() will do, but we promise truncate()
575 * won't change the current position (and fflush() *does* change it
576 * then at least on Windows). The easiest thing is to capture
577 * current pos now and seek back to it at the end.
578 */
579 Py_BEGIN_ALLOW_THREADS
580 errno = 0;
581 initialpos = _portable_ftell(f->f_fp);
582 Py_END_ALLOW_THREADS
583 if (initialpos == -1)
584 goto onioerror;
585
Tim Petersfb05db22002-03-11 00:24:00 +0000586 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000587 * specified value.
588 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000589 if (newsizeobj != NULL) {
590#if !defined(HAVE_LARGEFILE_SUPPORT)
591 newsize = PyInt_AsLong(newsizeobj);
592#else
593 newsize = PyLong_Check(newsizeobj) ?
594 PyLong_AsLongLong(newsizeobj) :
595 PyInt_AsLong(newsizeobj);
596#endif
597 if (PyErr_Occurred())
598 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000599 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000600 else /* default to current position */
601 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000602
Tim Petersf1827cf2003-09-07 03:30:18 +0000603 /* Flush the stream. We're mixing stream-level I/O with lower-level
604 * I/O, and a flush may be necessary to synch both platform views
605 * of the current file state.
606 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000608 errno = 0;
609 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000611 if (ret != 0)
612 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000613
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000614#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000615 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000616 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000617 {
Tim Petersfb05db22002-03-11 00:24:00 +0000618 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000619
Tim Petersf1827cf2003-09-07 03:30:18 +0000620 /* Have to move current pos to desired endpoint on Windows. */
621 Py_BEGIN_ALLOW_THREADS
622 errno = 0;
623 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
624 Py_END_ALLOW_THREADS
625 if (ret)
626 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000627
Tim Peters8f01b682002-03-12 03:04:44 +0000628 /* Truncate. Note that this may grow the file! */
629 Py_BEGIN_ALLOW_THREADS
630 errno = 0;
631 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000632 ret = hFile == (HANDLE)-1;
633 if (ret == 0) {
634 ret = SetEndOfFile(hFile) == 0;
635 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000636 errno = EACCES;
637 }
638 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000639 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000640 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000641 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000642#else
643 Py_BEGIN_ALLOW_THREADS
644 errno = 0;
645 ret = ftruncate(fileno(f->f_fp), newsize);
646 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000647 if (ret != 0)
648 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000649#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000650
Tim Petersf1827cf2003-09-07 03:30:18 +0000651 /* Restore original file position. */
652 Py_BEGIN_ALLOW_THREADS
653 errno = 0;
654 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
655 Py_END_ALLOW_THREADS
656 if (ret)
657 goto onioerror;
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659 Py_INCREF(Py_None);
660 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000661
662onioerror:
663 PyErr_SetFromErrno(PyExc_IOError);
664 clearerr(f->f_fp);
665 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000666}
667#endif /* HAVE_FTRUNCATE */
668
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000670file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000671{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000672 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000673
Guido van Rossumd7297e61992-07-06 14:19:26 +0000674 if (f->f_fp == NULL)
675 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000677 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000678 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000680 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000682 clearerr(f->f_fp);
683 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000684 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000685 if (f->f_skipnextlf) {
686 int c;
687 c = GETC(f->f_fp);
688 if (c == '\n') {
689 pos++;
690 f->f_skipnextlf = 0;
691 } else if (c != EOF) ungetc(c, f->f_fp);
692 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000693#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000694 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000695#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000696 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000697#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000698}
699
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000700static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000701file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000702{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000703 if (f->f_fp == NULL)
704 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000706}
707
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000709file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000710{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000711 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000712
Guido van Rossumd7297e61992-07-06 14:19:26 +0000713 if (f->f_fp == NULL)
714 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000715 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000716 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000717 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000719 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000720 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000721 clearerr(f->f_fp);
722 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000723 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 Py_INCREF(Py_None);
725 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000726}
727
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000729file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000730{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000731 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000732 if (f->f_fp == NULL)
733 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000734 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000735 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000737 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000738}
739
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000740
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000741#if BUFSIZ < 8192
742#define SMALLCHUNK 8192
743#else
744#define SMALLCHUNK BUFSIZ
745#endif
746
Guido van Rossum3c259041999-01-14 19:00:14 +0000747#if SIZEOF_INT < 4
748#define BIGCHUNK (512 * 32)
749#else
750#define BIGCHUNK (512 * 1024)
751#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000752
753static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000754new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000755{
756#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000757 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000758 struct stat st;
759 if (fstat(fileno(f->f_fp), &st) == 0) {
760 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000761 /* The following is not a bug: we really need to call lseek()
762 *and* ftell(). The reason is that some stdio libraries
763 mistakenly flush their buffer when ftell() is called and
764 the lseek() call it makes fails, thereby throwing away
765 data that cannot be recovered in any way. To avoid this,
766 we first test lseek(), and only call ftell() if lseek()
767 works. We can't use the lseek() value either, because we
768 need to take the amount of buffered data into account.
769 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000770 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000771 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000772 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000773 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000774 if (pos < 0)
775 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000776 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000777 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000778 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000779 }
780#endif
781 if (currentsize > SMALLCHUNK) {
782 /* Keep doubling until we reach BIGCHUNK;
783 then keep adding BIGCHUNK. */
784 if (currentsize <= BIGCHUNK)
785 return currentsize + currentsize;
786 else
787 return currentsize + BIGCHUNK;
788 }
789 return currentsize + SMALLCHUNK;
790}
791
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000792#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
793#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
794#else
795#ifdef EWOULDBLOCK
796#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
797#else
798#ifdef EAGAIN
799#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
800#else
801#define BLOCKED_ERRNO(x) 0
802#endif
803#endif
804#endif
805
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000807file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000808{
Guido van Rossum789a1611997-05-10 22:33:55 +0000809 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000810 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000812
Guido van Rossumd7297e61992-07-06 14:19:26 +0000813 if (f->f_fp == NULL)
814 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000815 /* refuse to mix with f.next() */
816 if (f->f_buf != NULL &&
817 (f->f_bufend - f->f_bufptr) > 0 &&
818 f->f_buf[0] != '\0')
819 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000820 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000821 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000822 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000823 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000824 else
825 buffersize = bytesrequested;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000827 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000828 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000829 return NULL;
830 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000831 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000832 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000834 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000835 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000836 Py_BEGIN_ALLOW_THREADS
837 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000838 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000839 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000840 Py_END_ALLOW_THREADS
841 if (chunksize == 0) {
842 if (!ferror(f->f_fp))
843 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000844 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000845 /* When in non-blocking mode, data shouldn't
846 * be discarded if a blocking signal was
847 * received. That will also happen if
848 * chunksize != 0, but bytesread < buffersize. */
849 if (bytesread > 0 && BLOCKED_ERRNO(errno))
850 break;
851 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000852 Py_DECREF(v);
853 return NULL;
854 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000855 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000856 if (bytesread < buffersize) {
857 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000858 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000859 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000860 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000861 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000862 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000863 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000864 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000865 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000866 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000867 }
868 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000869 if (bytesread != buffersize)
870 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000871 return v;
872}
873
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000874static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000875file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000876{
877 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000878 Py_ssize_t ntodo;
879 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000880
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000881 if (f->f_fp == NULL)
882 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000883 /* refuse to mix with f.next() */
884 if (f->f_buf != NULL &&
885 (f->f_bufend - f->f_bufptr) > 0 &&
886 f->f_buf[0] != '\0')
887 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000888 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000889 return NULL;
890 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000891 while (ntodo > 0) {
892 Py_BEGIN_ALLOW_THREADS
893 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000894 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000895 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000896 Py_END_ALLOW_THREADS
897 if (nnow == 0) {
898 if (!ferror(f->f_fp))
899 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000900 PyErr_SetFromErrno(PyExc_IOError);
901 clearerr(f->f_fp);
902 return NULL;
903 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000904 ndone += nnow;
905 ntodo -= nnow;
906 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000907 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000908}
909
Tim Peters86821b22001-01-07 21:19:34 +0000910/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000911Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000912
913Under MSVC 6:
914
Tim Peters1c733232001-01-08 04:02:07 +0000915+ MS threadsafe getc is very slow (multiple layers of function calls before+
916 after each character, to lock+unlock the stream).
917+ The stream-locking functions are MS-internal -- can't access them from user
918 code.
919+ There's nothing Tim could find in the MS C or platform SDK libraries that
920 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000921+ MS fgets locks/unlocks only once per line; it's the only hook we have.
922
923So we use fgets for speed(!), despite that it's painful.
924
925MS realloc is also slow.
926
Tim Petersf29b64d2001-01-15 06:33:19 +0000927Reports from other platforms on this method vs getc_unlocked (which MS doesn't
928have):
929 Linux a wash
930 Solaris a wash
931 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000932
Tim Petersf29b64d2001-01-15 06:33:19 +0000933CAUTION: The C std isn't clear about this: in those cases where fgets
934writes something into the buffer, can it write into any position beyond the
935required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
936known on which it does; and it would be a strange way to code fgets. Still,
937getline_via_fgets may not work correctly if it does. The std test
938test_bufio.py should fail if platform fgets() routinely writes beyond the
939trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000940**************************************************************************/
941
Tim Petersf29b64d2001-01-15 06:33:19 +0000942/* Use this routine if told to, or by default on non-get_unlocked()
943 * platforms unless told not to. Yikes! Let's spell that out:
944 * On a platform with getc_unlocked():
945 * By default, use getc_unlocked().
946 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
947 * On a platform without getc_unlocked():
948 * By default, use fgets().
949 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
950 */
951#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
952#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000953#endif
954
Tim Petersf29b64d2001-01-15 06:33:19 +0000955#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
956#undef USE_FGETS_IN_GETLINE
957#endif
958
959#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000960static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000961getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000962{
Tim Peters15b83852001-01-08 00:53:12 +0000963/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000964 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
965 * to fill this much of the buffer with a known value in order to figure out
966 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
967 * than "most" lines, we waste time filling unused buffer slots. 100 is
968 * surely adequate for most peoples' email archives, chewing over source code,
969 * etc -- "regular old text files".
970 * MAXBUFSIZE is the maximum line length that lets us get away with the less
971 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
972 * cautions about boosting that. 300 was chosen because the worst real-life
973 * text-crunching job reported on Python-Dev was a mail-log crawler where over
974 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000975 */
Tim Peters142297a2001-01-15 10:36:56 +0000976#define INITBUFSIZE 100
977#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000978 char* p; /* temp */
979 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000980 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000981 char* pvfree; /* address of next free slot */
982 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000983 size_t nfree; /* # of free buffer slots; pvend-pvfree */
984 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000985 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000986
Tim Peters15b83852001-01-08 00:53:12 +0000987 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000988 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000989 */
Tim Peters142297a2001-01-15 10:36:56 +0000990 total_v_size = INITBUFSIZE; /* start small and pray */
991 pvfree = buf;
992 for (;;) {
993 Py_BEGIN_ALLOW_THREADS
994 pvend = buf + total_v_size;
995 nfree = pvend - pvfree;
996 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000997 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
998 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +0000999 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001000
Tim Peters142297a2001-01-15 10:36:56 +00001001 if (p == NULL) {
1002 clearerr(fp);
1003 if (PyErr_CheckSignals())
1004 return NULL;
1005 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001006 return v;
1007 }
Tim Peters142297a2001-01-15 10:36:56 +00001008 /* fgets read *something* */
1009 p = memchr(pvfree, '\n', nfree);
1010 if (p != NULL) {
1011 /* Did the \n come from fgets or from us?
1012 * Since fgets stops at the first \n, and then writes
1013 * \0, if it's from fgets a \0 must be next. But if
1014 * that's so, it could not have come from us, since
1015 * the \n's we filled the buffer with have only more
1016 * \n's to the right.
1017 */
1018 if (p+1 < pvend && *(p+1) == '\0') {
1019 /* It's from fgets: we win! In particular,
1020 * we haven't done any mallocs yet, and can
1021 * build the final result on the first try.
1022 */
1023 ++p; /* include \n from fgets */
1024 }
1025 else {
1026 /* Must be from us: fgets didn't fill the
1027 * buffer and didn't find a newline, so it
1028 * must be the last and newline-free line of
1029 * the file.
1030 */
1031 assert(p > pvfree && *(p-1) == '\0');
1032 --p; /* don't include \0 from fgets */
1033 }
1034 v = PyString_FromStringAndSize(buf, p - buf);
1035 return v;
1036 }
1037 /* yuck: fgets overwrote all the newlines, i.e. the entire
1038 * buffer. So this line isn't over yet, or maybe it is but
1039 * we're exactly at EOF. If we haven't already, try using the
1040 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001041 */
Tim Peters142297a2001-01-15 10:36:56 +00001042 assert(*(pvend-1) == '\0');
1043 if (pvfree == buf) {
1044 pvfree = pvend - 1; /* overwrite trailing null */
1045 total_v_size = MAXBUFSIZE;
1046 }
1047 else
1048 break;
Tim Peters86821b22001-01-07 21:19:34 +00001049 }
Tim Peters142297a2001-01-15 10:36:56 +00001050
1051 /* The stack buffer isn't big enough; malloc a string object and read
1052 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001053 */
Tim Petersddea2082002-03-23 10:03:50 +00001054 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001055 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001056 if (v == NULL)
1057 return v;
1058 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001059 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1060 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001061
1062 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001063 * after setting p one beyond the end of the line. The code here is
1064 * very much like the code above, except reads into v's buffer; see
1065 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001066 */
1067 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001068 Py_BEGIN_ALLOW_THREADS
1069 pvend = BUF(v) + total_v_size;
1070 nfree = pvend - pvfree;
1071 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072 assert(nfree < INT_MAX);
1073 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001074 Py_END_ALLOW_THREADS
1075
1076 if (p == NULL) {
1077 clearerr(fp);
1078 if (PyErr_CheckSignals()) {
1079 Py_DECREF(v);
1080 return NULL;
1081 }
1082 p = pvfree;
1083 break;
1084 }
Tim Peters86821b22001-01-07 21:19:34 +00001085 p = memchr(pvfree, '\n', nfree);
1086 if (p != NULL) {
1087 if (p+1 < pvend && *(p+1) == '\0') {
1088 /* \n came from fgets */
1089 ++p;
1090 break;
1091 }
1092 /* \n came from us; last line of file, no newline */
1093 assert(p > pvfree && *(p-1) == '\0');
1094 --p;
1095 break;
1096 }
1097 /* expand buffer and try again */
1098 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001099 increment = total_v_size >> 2; /* mild exponential growth */
1100 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001101 if (total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001102 PyErr_SetString(PyExc_OverflowError,
1103 "line is longer than a Python string can hold");
1104 Py_DECREF(v);
1105 return NULL;
1106 }
1107 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1108 return NULL;
1109 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001110 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001111 }
1112 if (BUF(v) + total_v_size != p)
1113 _PyString_Resize(&v, p - BUF(v));
1114 return v;
1115#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001116#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001117}
Tim Petersf29b64d2001-01-15 06:33:19 +00001118#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001119
Guido van Rossum0bd24411991-04-04 15:21:57 +00001120/* Internal routine to get a line.
1121 Size argument interpretation:
1122 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001123 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001124*/
1125
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001126static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001127get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001128{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001129 FILE *fp = f->f_fp;
1130 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001131 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001132 size_t total_v_size; /* total # of slots in buffer */
1133 size_t used_v_size; /* # used slots in buffer */
1134 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001135 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001136 int newlinetypes = f->f_newlinetypes;
1137 int skipnextlf = f->f_skipnextlf;
1138 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001139
Jack Jansen7b8c7542002-04-14 20:12:41 +00001140#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001141 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001142 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001143#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001144 total_v_size = n > 0 ? n : 100;
1145 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001146 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001147 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001148 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001149 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001150
Guido van Rossumce5ba841991-03-06 13:06:18 +00001151 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001152 Py_BEGIN_ALLOW_THREADS
1153 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001154 if (univ_newline) {
1155 c = 'x'; /* Shut up gcc warning */
1156 while ( buf != end && (c = GETC(fp)) != EOF ) {
1157 if (skipnextlf ) {
1158 skipnextlf = 0;
1159 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001160 /* Seeing a \n here with
1161 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001162 * saw a \r before.
1163 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001164 newlinetypes |= NEWLINE_CRLF;
1165 c = GETC(fp);
1166 if (c == EOF) break;
1167 } else {
1168 newlinetypes |= NEWLINE_CR;
1169 }
1170 }
1171 if (c == '\r') {
1172 skipnextlf = 1;
1173 c = '\n';
1174 } else if ( c == '\n')
1175 newlinetypes |= NEWLINE_LF;
1176 *buf++ = c;
1177 if (c == '\n') break;
1178 }
1179 if ( c == EOF && skipnextlf )
1180 newlinetypes |= NEWLINE_CR;
1181 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001182 while ((c = GETC(fp)) != EOF &&
1183 (*buf++ = c) != '\n' &&
1184 buf != end)
1185 ;
1186 FUNLOCKFILE(fp);
1187 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001188 f->f_newlinetypes = newlinetypes;
1189 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001190 if (c == '\n')
1191 break;
1192 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001193 if (ferror(fp)) {
1194 PyErr_SetFromErrno(PyExc_IOError);
1195 clearerr(fp);
1196 Py_DECREF(v);
1197 return NULL;
1198 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001199 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001200 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001201 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001202 return NULL;
1203 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001204 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001205 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001206 /* Must be because buf == end */
1207 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001208 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001209 used_v_size = total_v_size;
1210 increment = total_v_size >> 2; /* mild exponential growth */
1211 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001212 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001213 PyErr_SetString(PyExc_OverflowError,
1214 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001215 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001216 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001217 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001218 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001219 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001220 buf = BUF(v) + used_v_size;
1221 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001222 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001223
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001224 used_v_size = buf - BUF(v);
1225 if (used_v_size != total_v_size)
1226 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001227 return v;
1228}
1229
Guido van Rossum0bd24411991-04-04 15:21:57 +00001230/* External C interface */
1231
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001232PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001233PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001234{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001235 PyObject *result;
1236
Guido van Rossum3165fe61992-09-25 21:59:05 +00001237 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001238 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001239 return NULL;
1240 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001241
1242 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001243 PyFileObject *fo = (PyFileObject *)f;
1244 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001245 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001246 /* refuse to mix with f.next() */
1247 if (fo->f_buf != NULL &&
1248 (fo->f_bufend - fo->f_bufptr) > 0 &&
1249 fo->f_buf[0] != '\0')
1250 return err_iterbuffered();
1251 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001252 }
1253 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001254 PyObject *reader;
1255 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001256
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001257 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001258 if (reader == NULL)
1259 return NULL;
1260 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001261 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001262 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001263 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001264 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001266 return NULL;
1267 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001268 result = PyEval_CallObject(reader, args);
1269 Py_DECREF(reader);
1270 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001271 if (result != NULL && !PyString_Check(result) &&
1272 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001273 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001274 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001275 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001276 "object.readline() returned non-string");
1277 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001278 }
1279
1280 if (n < 0 && result != NULL && PyString_Check(result)) {
1281 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001282 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001283 if (len == 0) {
1284 Py_DECREF(result);
1285 result = NULL;
1286 PyErr_SetString(PyExc_EOFError,
1287 "EOF when reading a line");
1288 }
1289 else if (s[len-1] == '\n') {
1290 if (result->ob_refcnt == 1)
1291 _PyString_Resize(&result, len-1);
1292 else {
1293 PyObject *v;
1294 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001295 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001296 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001297 }
1298 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001299 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001300#ifdef Py_USING_UNICODE
1301 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1302 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001303 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001304 if (len == 0) {
1305 Py_DECREF(result);
1306 result = NULL;
1307 PyErr_SetString(PyExc_EOFError,
1308 "EOF when reading a line");
1309 }
1310 else if (s[len-1] == '\n') {
1311 if (result->ob_refcnt == 1)
1312 PyUnicode_Resize(&result, len-1);
1313 else {
1314 PyObject *v;
1315 v = PyUnicode_FromUnicode(s, len-1);
1316 Py_DECREF(result);
1317 result = v;
1318 }
1319 }
1320 }
1321#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001322 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001323}
1324
1325/* Python method */
1326
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001327static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001328file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001329{
Guido van Rossum789a1611997-05-10 22:33:55 +00001330 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001331
Guido van Rossumd7297e61992-07-06 14:19:26 +00001332 if (f->f_fp == NULL)
1333 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001334 /* refuse to mix with f.next() */
1335 if (f->f_buf != NULL &&
1336 (f->f_bufend - f->f_bufptr) > 0 &&
1337 f->f_buf[0] != '\0')
1338 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001339 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001340 return NULL;
1341 if (n == 0)
1342 return PyString_FromString("");
1343 if (n < 0)
1344 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001345 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001346}
1347
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001348static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001349file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001350{
Guido van Rossum789a1611997-05-10 22:33:55 +00001351 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001352 PyObject *list;
1353 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001354 char small_buffer[SMALLCHUNK];
1355 char *buffer = small_buffer;
1356 size_t buffersize = SMALLCHUNK;
1357 PyObject *big_buffer = NULL;
1358 size_t nfilled = 0;
1359 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001360 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001361 char *p, *q, *end;
1362 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001363 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001364
Guido van Rossumd7297e61992-07-06 14:19:26 +00001365 if (f->f_fp == NULL)
1366 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001367 /* refuse to mix with f.next() */
1368 if (f->f_buf != NULL &&
1369 (f->f_bufend - f->f_bufptr) > 0 &&
1370 f->f_buf[0] != '\0')
1371 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001372 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001373 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001374 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001375 return NULL;
1376 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001377 if (shortread)
1378 nread = 0;
1379 else {
1380 Py_BEGIN_ALLOW_THREADS
1381 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001382 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001383 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001384 Py_END_ALLOW_THREADS
1385 shortread = (nread < buffersize-nfilled);
1386 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001387 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001388 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001389 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001390 break;
1391 PyErr_SetFromErrno(PyExc_IOError);
1392 clearerr(f->f_fp);
1393 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001394 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001395 list = NULL;
1396 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001397 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001398 totalread += nread;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001399 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001400 if (p == NULL) {
1401 /* Need a larger buffer to fit this line */
1402 nfilled += nread;
1403 buffersize *= 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001404 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001405 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001406 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001407 goto error;
1408 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001409 if (big_buffer == NULL) {
1410 /* Create the big buffer */
1411 big_buffer = PyString_FromStringAndSize(
1412 NULL, buffersize);
1413 if (big_buffer == NULL)
1414 goto error;
1415 buffer = PyString_AS_STRING(big_buffer);
1416 memcpy(buffer, small_buffer, nfilled);
1417 }
1418 else {
1419 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001420 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1421 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001422 buffer = PyString_AS_STRING(big_buffer);
1423 }
1424 continue;
1425 }
1426 end = buffer+nfilled+nread;
1427 q = buffer;
1428 do {
1429 /* Process complete lines */
1430 p++;
1431 line = PyString_FromStringAndSize(q, p-q);
1432 if (line == NULL)
1433 goto error;
1434 err = PyList_Append(list, line);
1435 Py_DECREF(line);
1436 if (err != 0)
1437 goto error;
1438 q = p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001439 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001440 } while (p != NULL);
1441 /* Move the remaining incomplete line to the start */
1442 nfilled = end-q;
1443 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001444 if (sizehint > 0)
1445 if (totalread >= (size_t)sizehint)
1446 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001447 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001448 if (nfilled != 0) {
1449 /* Partial last line */
1450 line = PyString_FromStringAndSize(buffer, nfilled);
1451 if (line == NULL)
1452 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001453 if (sizehint > 0) {
1454 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001455 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001456 if (rest == NULL) {
1457 Py_DECREF(line);
1458 goto error;
1459 }
1460 PyString_Concat(&line, rest);
1461 Py_DECREF(rest);
1462 if (line == NULL)
1463 goto error;
1464 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001465 err = PyList_Append(list, line);
1466 Py_DECREF(line);
1467 if (err != 0)
1468 goto error;
1469 }
1470 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001471 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001472 return list;
1473}
1474
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001475static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001476file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001477{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001478 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001479 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001480 if (f->f_fp == NULL)
1481 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001482 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001483 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001484 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001485 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001486 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001487 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001488 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001489 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001491 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001492 return NULL;
1493 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001494 Py_INCREF(Py_None);
1495 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001496}
1497
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001498static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001499file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001500{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001501#define CHUNKSIZE 1000
1502 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001503 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001504 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001505 int index, islist;
1506 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001507
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001508 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001509 if (f->f_fp == NULL)
1510 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001511
1512 result = NULL;
1513 list = NULL;
1514 islist = PyList_Check(seq);
1515 if (islist)
1516 it = NULL;
1517 else {
1518 it = PyObject_GetIter(seq);
1519 if (it == NULL) {
1520 PyErr_SetString(PyExc_TypeError,
1521 "writelines() requires an iterable argument");
1522 return NULL;
1523 }
1524 /* From here on, fail by going to error, to reclaim "it". */
1525 list = PyList_New(CHUNKSIZE);
1526 if (list == NULL)
1527 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001528 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001529
1530 /* Strategy: slurp CHUNKSIZE lines into a private list,
1531 checking that they are all strings, then write that list
1532 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001533 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001534 if (islist) {
1535 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001536 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001537 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001538 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539 j = PyList_GET_SIZE(list);
1540 }
1541 else {
1542 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001543 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001544 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001545 if (PyErr_Occurred())
1546 goto error;
1547 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001548 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001549 PyList_SetItem(list, j, line);
1550 }
1551 }
1552 if (j == 0)
1553 break;
1554
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001555 /* Check that all entries are indeed strings. If not,
1556 apply the same rules as for file.write() and
1557 convert the results to strings. This is slow, but
1558 seems to be the only way since all conversion APIs
1559 could potentially execute Python code. */
1560 for (i = 0; i < j; i++) {
1561 PyObject *v = PyList_GET_ITEM(list, i);
1562 if (!PyString_Check(v)) {
1563 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001564 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001565 PyObject_AsReadBuffer(v,
1566 (const void**)&buffer,
1567 &len)) ||
1568 PyObject_AsCharBuffer(v,
1569 &buffer,
1570 &len))) {
1571 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001572 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001573 goto error;
1574 }
1575 line = PyString_FromStringAndSize(buffer,
1576 len);
1577 if (line == NULL)
1578 goto error;
1579 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001580 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001581 }
1582 }
1583
1584 /* Since we are releasing the global lock, the
1585 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001586 Py_BEGIN_ALLOW_THREADS
1587 f->f_softspace = 0;
1588 errno = 0;
1589 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001590 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001591 len = PyString_GET_SIZE(line);
1592 nwritten = fwrite(PyString_AS_STRING(line),
1593 1, len, f->f_fp);
1594 if (nwritten != len) {
1595 Py_BLOCK_THREADS
1596 PyErr_SetFromErrno(PyExc_IOError);
1597 clearerr(f->f_fp);
1598 goto error;
1599 }
1600 }
1601 Py_END_ALLOW_THREADS
1602
1603 if (j < CHUNKSIZE)
1604 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001605 }
1606
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001607 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001608 result = Py_None;
1609 error:
1610 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001611 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001612 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001613#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001614}
1615
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001616static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001617file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001618{
1619 if (f->f_fp == NULL)
1620 return err_closed();
1621 Py_INCREF(f);
1622 return (PyObject *)f;
1623}
1624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001625PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001626"readline([size]) -> next line from the file, as a string.\n"
1627"\n"
1628"Retain newline. A non-negative size argument limits the maximum\n"
1629"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001630"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001632PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001633"read([size]) -> read at most size bytes, returned as a string.\n"
1634"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001635"If the size argument is negative or omitted, read until EOF is reached.\n"
1636"Notice that when in non-blocking mode, less data than what was requested\n"
1637"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001639PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001640"write(str) -> None. Write string str to file.\n"
1641"\n"
1642"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001643"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001646"fileno() -> integer \"file descriptor\".\n"
1647"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001648"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001650PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001651"seek(offset[, whence]) -> None. Move to new file position.\n"
1652"\n"
1653"Argument offset is a byte count. Optional argument whence defaults to\n"
1654"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1655"(move relative to current position, positive or negative), and 2 (move\n"
1656"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001657"seeking beyond the end of a file). If the file is opened in text mode,\n"
1658"only offsets returned by tell() are legal. Use of other offsets causes\n"
1659"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001660"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001661"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001662
Guido van Rossumd7047b31995-01-02 19:07:15 +00001663#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001664PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001665"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1666"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001667"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001668#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001669
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001670PyDoc_STRVAR(tell_doc,
1671"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001673PyDoc_STRVAR(readinto_doc,
1674"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001675
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001676PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001677"readlines([size]) -> list of strings, each a line from the file.\n"
1678"\n"
1679"Call readline() repeatedly and return a list of the lines so read.\n"
1680"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001681"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001683PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001684"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001685"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001686"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001687"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001689PyDoc_STRVAR(flush_doc,
1690"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001692PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001693"close() -> None or (perhaps) an integer. Close the file.\n"
1694"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001695"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001696"further I/O operations. close() may be called more than once without\n"
1697"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001698"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001699
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001700PyDoc_STRVAR(isatty_doc,
1701"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001702
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001703PyDoc_STRVAR(context_doc,
1704 "__context__() -> self.");
1705
1706PyDoc_STRVAR(enter_doc,
1707 "__enter__() -> self.");
1708
Tim Petersefc3a3a2001-09-20 07:55:22 +00001709static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001710 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1711 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1712 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1713 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1714 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001715#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001716 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001717#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001718 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1719 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1720 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001721 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1722 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1723 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1724 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001725 {"__context__", (PyCFunction)file_self, METH_NOARGS, context_doc},
1726 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Guido van Rossumf6694362006-03-10 02:28:35 +00001727 {"__exit__", (PyCFunction)file_close, METH_VARARGS, close_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001728 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001729};
1730
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001731#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001732
Guido van Rossum6f799372001-09-20 20:46:19 +00001733static PyMemberDef file_memberlist[] = {
1734 {"softspace", T_INT, OFF(f_softspace), 0,
1735 "flag indicating that a space needs to be printed; used by print"},
1736 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001737 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001738 {"name", T_OBJECT, OFF(f_name), RO,
1739 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001740 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1741 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001742 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001743 {NULL} /* Sentinel */
1744};
1745
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001746static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001748{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001749 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001750}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001751static PyObject *
1752get_newlines(PyFileObject *f, void *closure)
1753{
1754 switch (f->f_newlinetypes) {
1755 case NEWLINE_UNKNOWN:
1756 Py_INCREF(Py_None);
1757 return Py_None;
1758 case NEWLINE_CR:
1759 return PyString_FromString("\r");
1760 case NEWLINE_LF:
1761 return PyString_FromString("\n");
1762 case NEWLINE_CR|NEWLINE_LF:
1763 return Py_BuildValue("(ss)", "\r", "\n");
1764 case NEWLINE_CRLF:
1765 return PyString_FromString("\r\n");
1766 case NEWLINE_CR|NEWLINE_CRLF:
1767 return Py_BuildValue("(ss)", "\r", "\r\n");
1768 case NEWLINE_LF|NEWLINE_CRLF:
1769 return Py_BuildValue("(ss)", "\n", "\r\n");
1770 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1771 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1772 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001773 PyErr_Format(PyExc_SystemError,
1774 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001775 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001776 return NULL;
1777 }
1778}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001779
Guido van Rossum32d34c82001-09-20 21:45:26 +00001780static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001781 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001782 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001783 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784 {0},
1785};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001786
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001787static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001788drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001789{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001790 if (f->f_buf != NULL) {
1791 PyMem_Free(f->f_buf);
1792 f->f_buf = NULL;
1793 }
Guido van Rossum65967252001-04-21 13:20:18 +00001794}
1795
Tim Petersf1827cf2003-09-07 03:30:18 +00001796/* Make sure that file has a readahead buffer with at least one byte
1797 (unless at EOF) and no more than bufsize. Returns negative value on
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001798 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001799static int
1800readahead(PyFileObject *f, int bufsize)
1801{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001802 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001803
1804 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001805 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001806 return 0;
1807 else
1808 drop_readahead(f);
1809 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001810 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
1811 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001812 return -1;
1813 }
1814 Py_BEGIN_ALLOW_THREADS
1815 errno = 0;
1816 chunksize = Py_UniversalNewlineFread(
1817 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1818 Py_END_ALLOW_THREADS
1819 if (chunksize == 0) {
1820 if (ferror(f->f_fp)) {
1821 PyErr_SetFromErrno(PyExc_IOError);
1822 clearerr(f->f_fp);
1823 drop_readahead(f);
1824 return -1;
1825 }
1826 }
1827 f->f_bufptr = f->f_buf;
1828 f->f_bufend = f->f_buf + chunksize;
1829 return 0;
1830}
1831
1832/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001833 uninitialized bytes followed by the remainder of the line. Don't be
1834 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001835 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1836
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001837static PyStringObject *
1838readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1839{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001840 PyStringObject* s;
1841 char *bufptr;
1842 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001843 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001844
1845 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001846 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001847 return NULL;
1848
1849 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001850 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001851 return (PyStringObject *)
1852 PyString_FromStringAndSize(NULL, skip);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001853 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001854 if (bufptr != NULL) {
1855 bufptr++; /* Count the '\n' */
1856 len = bufptr - f->f_bufptr;
1857 s = (PyStringObject *)
1858 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001859 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001860 return NULL;
1861 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1862 f->f_bufptr = bufptr;
1863 if (bufptr == f->f_bufend)
1864 drop_readahead(f);
1865 } else {
1866 bufptr = f->f_bufptr;
1867 buf = f->f_buf;
1868 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001869 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001870 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001871 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001872 if (s == NULL) {
1873 PyMem_Free(buf);
1874 return NULL;
1875 }
1876 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1877 PyMem_Free(buf);
1878 }
1879 return s;
1880}
1881
1882/* A larger buffer size may actually decrease performance. */
1883#define READAHEAD_BUFSIZE 8192
1884
1885static PyObject *
1886file_iternext(PyFileObject *f)
1887{
1888 PyStringObject* l;
1889
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001890 if (f->f_fp == NULL)
1891 return err_closed();
1892
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001893 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1894 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1895 Py_XDECREF(l);
1896 return NULL;
1897 }
1898 return (PyObject *)l;
1899}
1900
1901
Tim Peters59c9a642001-09-13 05:38:56 +00001902static PyObject *
1903file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1904{
Tim Peters44410012001-09-14 03:26:08 +00001905 PyObject *self;
1906 static PyObject *not_yet_string;
1907
1908 assert(type != NULL && type->tp_alloc != NULL);
1909
1910 if (not_yet_string == NULL) {
1911 not_yet_string = PyString_FromString("<uninitialized file>");
1912 if (not_yet_string == NULL)
1913 return NULL;
1914 }
1915
1916 self = type->tp_alloc(type, 0);
1917 if (self != NULL) {
1918 /* Always fill in the name and mode, so that nobody else
1919 needs to special-case NULLs there. */
1920 Py_INCREF(not_yet_string);
1921 ((PyFileObject *)self)->f_name = not_yet_string;
1922 Py_INCREF(not_yet_string);
1923 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001924 Py_INCREF(Py_None);
1925 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001926 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001927 }
1928 return self;
1929}
1930
1931static int
1932file_init(PyObject *self, PyObject *args, PyObject *kwds)
1933{
1934 PyFileObject *foself = (PyFileObject *)self;
1935 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001936 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001937 char *name = NULL;
1938 char *mode = "r";
1939 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001940 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001941
1942 assert(PyFile_Check(self));
1943 if (foself->f_fp != NULL) {
1944 /* Have to close the existing file first. */
1945 PyObject *closeresult = file_close(foself);
1946 if (closeresult == NULL)
1947 return -1;
1948 Py_DECREF(closeresult);
1949 }
Tim Peters59c9a642001-09-13 05:38:56 +00001950
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001951#ifdef Py_WIN_WIDE_FILENAMES
1952 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1953 PyObject *po;
1954 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1955 kwlist, &po, &mode, &bufsize)) {
1956 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001957 if (fill_file_fields(foself, NULL, po, mode,
1958 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001959 goto Error;
1960 } else {
1961 /* Drop the argument parsing error as narrow
1962 strings are also valid. */
1963 PyErr_Clear();
1964 }
1965 }
1966#endif
1967
1968 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001969 PyObject *o_name;
1970
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001971 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1972 Py_FileSystemDefaultEncoding,
1973 &name,
1974 &mode, &bufsize))
1975 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001976
1977 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001978 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1979 kwlist, &o_name, &mode,
1980 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001981 return -1;
1982
1983 if (fill_file_fields(foself, NULL, o_name, mode,
1984 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001985 goto Error;
1986 }
Tim Peters44410012001-09-14 03:26:08 +00001987 if (open_the_file(foself, name, mode) == NULL)
1988 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001989 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001990 PyFile_SetBufSize(self, bufsize);
1991 goto Done;
1992
1993Error:
1994 ret = -1;
1995 /* fall through */
1996Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001997 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001998 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001999}
2000
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002001PyDoc_VAR(file_doc) =
2002PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002003"file(name[, mode[, buffering]]) -> file object\n"
2004"\n"
2005"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2006"writing or appending. The file will be created if it doesn't exist\n"
2007"when opened for writing or appending; it will be truncated when\n"
2008"opened for writing. Add a 'b' to the mode for binary files.\n"
2009"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2010"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002011"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002012)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002013PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002014"Add a 'U' to mode to open the file for input with universal newline\n"
2015"support. Any line ending in the input file will be seen as a '\\n'\n"
2016"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2017"the value for this attribute is one of None (no newline read yet),\n"
2018"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2019"\n"
2020"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002021)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002022PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002023"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024"Note: open() is an alias for file()."
2025);
Tim Peters59c9a642001-09-13 05:38:56 +00002026
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002027PyTypeObject PyFile_Type = {
2028 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002029 0,
2030 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002031 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002032 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002033 (destructor)file_dealloc, /* tp_dealloc */
2034 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 0, /* tp_getattr */
2036 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002037 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002039 0, /* tp_as_number */
2040 0, /* tp_as_sequence */
2041 0, /* tp_as_mapping */
2042 0, /* tp_hash */
2043 0, /* tp_call */
2044 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002046 /* softspace is writable: we must supply tp_setattro */
2047 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002048 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002049 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002050 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051 0, /* tp_traverse */
2052 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002053 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002054 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002055 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002056 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057 file_methods, /* tp_methods */
2058 file_memberlist, /* tp_members */
2059 file_getsetlist, /* tp_getset */
2060 0, /* tp_base */
2061 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002062 0, /* tp_descr_get */
2063 0, /* tp_descr_set */
2064 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002065 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002066 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002067 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002068 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002069};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002070
2071/* Interface for the 'soft space' between print items. */
2072
2073int
Fred Drakefd99de62000-07-09 05:02:18 +00002074PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002075{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002076 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002077 if (f == NULL) {
2078 /* Do nothing */
2079 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002080 else if (PyFile_Check(f)) {
2081 oldflag = ((PyFileObject *)f)->f_softspace;
2082 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002083 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002084 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002085 PyObject *v;
2086 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002087 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002088 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002089 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002090 if (PyInt_Check(v))
2091 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002092 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002094 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002095 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002096 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002097 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002098 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2100 PyErr_Clear();
2101 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002102 }
2103 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002104 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002105}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002106
2107/* Interfaces to write objects/strings to file-like objects */
2108
2109int
Fred Drakefd99de62000-07-09 05:02:18 +00002110PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002111{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002112 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002113 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002114 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002115 return -1;
2116 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 else if (PyFile_Check(f)) {
2118 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002119#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002120 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2121 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002122#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002123 if (fp == NULL) {
2124 err_closed();
2125 return -1;
2126 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002127#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002128 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002129 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002130 char *cenc = PyString_AS_STRING(enc);
2131 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2132 if (value == NULL)
2133 return -1;
2134 } else {
2135 value = v;
2136 Py_INCREF(value);
2137 }
2138 result = PyObject_Print(value, fp, flags);
2139 Py_DECREF(value);
2140 return result;
2141#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002142 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002143#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002144 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002145 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002146 if (writer == NULL)
2147 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002148 if (flags & Py_PRINT_RAW) {
2149 if (PyUnicode_Check(v)) {
2150 value = v;
2151 Py_INCREF(value);
2152 } else
2153 value = PyObject_Str(v);
2154 }
2155 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002156 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002157 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002158 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002159 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002160 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002161 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002162 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002163 Py_DECREF(value);
2164 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002165 return -1;
2166 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167 result = PyEval_CallObject(writer, args);
2168 Py_DECREF(args);
2169 Py_DECREF(value);
2170 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002171 if (result == NULL)
2172 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002174 return 0;
2175}
2176
Guido van Rossum27a60b11997-05-22 22:25:11 +00002177int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002178PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002179{
2180 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002181 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002182 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002183 PyErr_SetString(PyExc_SystemError,
2184 "null file for PyFile_WriteString");
2185 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002186 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187 else if (PyFile_Check(f)) {
2188 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002189 if (fp == NULL) {
2190 err_closed();
2191 return -1;
2192 }
2193 fputs(s, fp);
2194 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002195 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196 else if (!PyErr_Occurred()) {
2197 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002198 int err;
2199 if (v == NULL)
2200 return -1;
2201 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2202 Py_DECREF(v);
2203 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002204 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002205 else
2206 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002207}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002208
2209/* Try to get a file-descriptor from a Python object. If the object
2210 is an integer or long integer, its value is returned. If not, the
2211 object's fileno() method is called if it exists; the method must return
2212 an integer or long integer, which is returned as the file descriptor value.
2213 -1 is returned on failure.
2214*/
2215
2216int PyObject_AsFileDescriptor(PyObject *o)
2217{
2218 int fd;
2219 PyObject *meth;
2220
2221 if (PyInt_Check(o)) {
2222 fd = PyInt_AsLong(o);
2223 }
2224 else if (PyLong_Check(o)) {
2225 fd = PyLong_AsLong(o);
2226 }
2227 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2228 {
2229 PyObject *fno = PyEval_CallObject(meth, NULL);
2230 Py_DECREF(meth);
2231 if (fno == NULL)
2232 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002233
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002234 if (PyInt_Check(fno)) {
2235 fd = PyInt_AsLong(fno);
2236 Py_DECREF(fno);
2237 }
2238 else if (PyLong_Check(fno)) {
2239 fd = PyLong_AsLong(fno);
2240 Py_DECREF(fno);
2241 }
2242 else {
2243 PyErr_SetString(PyExc_TypeError,
2244 "fileno() returned a non-integer");
2245 Py_DECREF(fno);
2246 return -1;
2247 }
2248 }
2249 else {
2250 PyErr_SetString(PyExc_TypeError,
2251 "argument must be an int, or have a fileno() method.");
2252 return -1;
2253 }
2254
2255 if (fd < 0) {
2256 PyErr_Format(PyExc_ValueError,
2257 "file descriptor cannot be a negative integer (%i)",
2258 fd);
2259 return -1;
2260 }
2261 return fd;
2262}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002263
Jack Jansen7b8c7542002-04-14 20:12:41 +00002264/* From here on we need access to the real fgets and fread */
2265#undef fgets
2266#undef fread
2267
2268/*
2269** Py_UniversalNewlineFgets is an fgets variation that understands
2270** all of \r, \n and \r\n conventions.
2271** The stream should be opened in binary mode.
2272** If fobj is NULL the routine always does newline conversion, and
2273** it may peek one char ahead to gobble the second char in \r\n.
2274** If fobj is non-NULL it must be a PyFileObject. In this case there
2275** is no readahead but in stead a flag is used to skip a following
2276** \n on the next read. Also, if the file is open in binary mode
2277** the whole conversion is skipped. Finally, the routine keeps track of
2278** the different types of newlines seen.
2279** Note that we need no error handling: fgets() treats error and eof
2280** identically.
2281*/
2282char *
2283Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2284{
2285 char *p = buf;
2286 int c;
2287 int newlinetypes = 0;
2288 int skipnextlf = 0;
2289 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002290
Jack Jansen7b8c7542002-04-14 20:12:41 +00002291 if (fobj) {
2292 if (!PyFile_Check(fobj)) {
2293 errno = ENXIO; /* What can you do... */
2294 return NULL;
2295 }
2296 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2297 if ( !univ_newline )
2298 return fgets(buf, n, stream);
2299 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2300 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2301 }
2302 FLOCKFILE(stream);
2303 c = 'x'; /* Shut up gcc warning */
2304 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2305 if (skipnextlf ) {
2306 skipnextlf = 0;
2307 if (c == '\n') {
2308 /* Seeing a \n here with skipnextlf true
2309 ** means we saw a \r before.
2310 */
2311 newlinetypes |= NEWLINE_CRLF;
2312 c = GETC(stream);
2313 if (c == EOF) break;
2314 } else {
2315 /*
2316 ** Note that c == EOF also brings us here,
2317 ** so we're okay if the last char in the file
2318 ** is a CR.
2319 */
2320 newlinetypes |= NEWLINE_CR;
2321 }
2322 }
2323 if (c == '\r') {
2324 /* A \r is translated into a \n, and we skip
2325 ** an adjacent \n, if any. We don't set the
2326 ** newlinetypes flag until we've seen the next char.
2327 */
2328 skipnextlf = 1;
2329 c = '\n';
2330 } else if ( c == '\n') {
2331 newlinetypes |= NEWLINE_LF;
2332 }
2333 *p++ = c;
2334 if (c == '\n') break;
2335 }
2336 if ( c == EOF && skipnextlf )
2337 newlinetypes |= NEWLINE_CR;
2338 FUNLOCKFILE(stream);
2339 *p = '\0';
2340 if (fobj) {
2341 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2342 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2343 } else if ( skipnextlf ) {
2344 /* If we have no file object we cannot save the
2345 ** skipnextlf flag. We have to readahead, which
2346 ** will cause a pause if we're reading from an
2347 ** interactive stream, but that is very unlikely
2348 ** unless we're doing something silly like
2349 ** execfile("/dev/tty").
2350 */
2351 c = GETC(stream);
2352 if ( c != '\n' )
2353 ungetc(c, stream);
2354 }
2355 if (p == buf)
2356 return NULL;
2357 return buf;
2358}
2359
2360/*
2361** Py_UniversalNewlineFread is an fread variation that understands
2362** all of \r, \n and \r\n conventions.
2363** The stream should be opened in binary mode.
2364** fobj must be a PyFileObject. In this case there
2365** is no readahead but in stead a flag is used to skip a following
2366** \n on the next read. Also, if the file is open in binary mode
2367** the whole conversion is skipped. Finally, the routine keeps track of
2368** the different types of newlines seen.
2369*/
2370size_t
Tim Peters058b1412002-04-21 07:29:14 +00002371Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002372 FILE *stream, PyObject *fobj)
2373{
Tim Peters058b1412002-04-21 07:29:14 +00002374 char *dst = buf;
2375 PyFileObject *f = (PyFileObject *)fobj;
2376 int newlinetypes, skipnextlf;
2377
2378 assert(buf != NULL);
2379 assert(stream != NULL);
2380
Jack Jansen7b8c7542002-04-14 20:12:41 +00002381 if (!fobj || !PyFile_Check(fobj)) {
2382 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002383 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002384 }
Tim Peters058b1412002-04-21 07:29:14 +00002385 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002386 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002387 newlinetypes = f->f_newlinetypes;
2388 skipnextlf = f->f_skipnextlf;
2389 /* Invariant: n is the number of bytes remaining to be filled
2390 * in the buffer.
2391 */
2392 while (n) {
2393 size_t nread;
2394 int shortread;
2395 char *src = dst;
2396
2397 nread = fread(dst, 1, n, stream);
2398 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002399 if (nread == 0)
2400 break;
2401
Tim Peterse1682a82002-04-21 18:15:20 +00002402 n -= nread; /* assuming 1 byte out for each in; will adjust */
2403 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002404 while (nread--) {
2405 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002406 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002407 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002408 *dst++ = '\n';
2409 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002410 }
2411 else if (skipnextlf && c == '\n') {
2412 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002413 skipnextlf = 0;
2414 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002415 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002416 }
2417 else {
2418 /* Normal char to be stored in buffer. Also
2419 * update the newlinetypes flag if either this
2420 * is an LF or the previous char was a CR.
2421 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002422 if (c == '\n')
2423 newlinetypes |= NEWLINE_LF;
2424 else if (skipnextlf)
2425 newlinetypes |= NEWLINE_CR;
2426 *dst++ = c;
2427 skipnextlf = 0;
2428 }
2429 }
Tim Peters058b1412002-04-21 07:29:14 +00002430 if (shortread) {
2431 /* If this is EOF, update type flags. */
2432 if (skipnextlf && feof(stream))
2433 newlinetypes |= NEWLINE_CR;
2434 break;
2435 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002436 }
Tim Peters058b1412002-04-21 07:29:14 +00002437 f->f_newlinetypes = newlinetypes;
2438 f->f_skipnextlf = skipnextlf;
2439 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002440}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002441
2442#ifdef __cplusplus
2443}
2444#endif
2445