blob: 0f166cdb6c432f4a9817009743c9aa1d6cb65b34 [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
Anthony Baxterac6bd462006-04-13 02:06:09 +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 {
Anthony Baxter377be112006-04-11 06:54:30 +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;
Martin v. Löwis2a190742006-04-13 07:37:25 +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;
Martin v. Löwis2a190742006-04-13 07:37:25 +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;
Martin v. Löwis2a190742006-04-13 07:37:25 +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;
Anthony Baxter377be112006-04-11 06:54:30 +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;
Martin v. Löwis2a190742006-04-13 07:37:25 +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;
Anthony Baxter377be112006-04-11 06:54:30 +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(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001684"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001685"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001686"For backward compatibility. File objects now include the performance\n"
1687"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001689PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001690"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001691"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001692"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001693"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001695PyDoc_STRVAR(flush_doc,
1696"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001698PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001699"close() -> None or (perhaps) an integer. Close the file.\n"
1700"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001701"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001702"further I/O operations. close() may be called more than once without\n"
1703"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001704"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001706PyDoc_STRVAR(isatty_doc,
1707"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001708
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001709PyDoc_STRVAR(enter_doc,
1710 "__enter__() -> self.");
1711
Tim Petersefc3a3a2001-09-20 07:55:22 +00001712static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001713 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1714 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1715 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1716 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1717 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001718#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001719 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001720#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001721 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1722 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1723 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001724 {"xreadlines",(PyCFunction)file_self, METH_NOARGS, xreadlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001725 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1726 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1727 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1728 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001729 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Guido van Rossumf6694362006-03-10 02:28:35 +00001730 {"__exit__", (PyCFunction)file_close, METH_VARARGS, close_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001731 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001732};
1733
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001734#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001735
Guido van Rossum6f799372001-09-20 20:46:19 +00001736static PyMemberDef file_memberlist[] = {
1737 {"softspace", T_INT, OFF(f_softspace), 0,
1738 "flag indicating that a space needs to be printed; used by print"},
1739 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001740 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001741 {"name", T_OBJECT, OFF(f_name), RO,
1742 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001743 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1744 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001745 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001746 {NULL} /* Sentinel */
1747};
1748
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001749static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001750get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001751{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001752 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001753}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001754static PyObject *
1755get_newlines(PyFileObject *f, void *closure)
1756{
1757 switch (f->f_newlinetypes) {
1758 case NEWLINE_UNKNOWN:
1759 Py_INCREF(Py_None);
1760 return Py_None;
1761 case NEWLINE_CR:
1762 return PyString_FromString("\r");
1763 case NEWLINE_LF:
1764 return PyString_FromString("\n");
1765 case NEWLINE_CR|NEWLINE_LF:
1766 return Py_BuildValue("(ss)", "\r", "\n");
1767 case NEWLINE_CRLF:
1768 return PyString_FromString("\r\n");
1769 case NEWLINE_CR|NEWLINE_CRLF:
1770 return Py_BuildValue("(ss)", "\r", "\r\n");
1771 case NEWLINE_LF|NEWLINE_CRLF:
1772 return Py_BuildValue("(ss)", "\n", "\r\n");
1773 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1774 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1775 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001776 PyErr_Format(PyExc_SystemError,
1777 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001778 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001779 return NULL;
1780 }
1781}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001782
Guido van Rossum32d34c82001-09-20 21:45:26 +00001783static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001784 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001785 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001786 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 {0},
1788};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001789
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001790static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001791drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001792{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001793 if (f->f_buf != NULL) {
1794 PyMem_Free(f->f_buf);
1795 f->f_buf = NULL;
1796 }
Guido van Rossum65967252001-04-21 13:20:18 +00001797}
1798
Tim Petersf1827cf2003-09-07 03:30:18 +00001799/* Make sure that file has a readahead buffer with at least one byte
1800 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00001801 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001802static int
1803readahead(PyFileObject *f, int bufsize)
1804{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001805 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001806
1807 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001808 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001809 return 0;
1810 else
1811 drop_readahead(f);
1812 }
Anthony Baxter377be112006-04-11 06:54:30 +00001813 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00001814 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001815 return -1;
1816 }
1817 Py_BEGIN_ALLOW_THREADS
1818 errno = 0;
1819 chunksize = Py_UniversalNewlineFread(
1820 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1821 Py_END_ALLOW_THREADS
1822 if (chunksize == 0) {
1823 if (ferror(f->f_fp)) {
1824 PyErr_SetFromErrno(PyExc_IOError);
1825 clearerr(f->f_fp);
1826 drop_readahead(f);
1827 return -1;
1828 }
1829 }
1830 f->f_bufptr = f->f_buf;
1831 f->f_bufend = f->f_buf + chunksize;
1832 return 0;
1833}
1834
1835/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001836 uninitialized bytes followed by the remainder of the line. Don't be
1837 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001838 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1839
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001840static PyStringObject *
1841readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1842{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001843 PyStringObject* s;
1844 char *bufptr;
1845 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001846 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001847
1848 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001849 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001850 return NULL;
1851
1852 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001853 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001854 return (PyStringObject *)
1855 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00001856 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001857 if (bufptr != NULL) {
1858 bufptr++; /* Count the '\n' */
1859 len = bufptr - f->f_bufptr;
1860 s = (PyStringObject *)
1861 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001862 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001863 return NULL;
1864 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1865 f->f_bufptr = bufptr;
1866 if (bufptr == f->f_bufend)
1867 drop_readahead(f);
1868 } else {
1869 bufptr = f->f_bufptr;
1870 buf = f->f_buf;
1871 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001872 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001873 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001874 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001875 if (s == NULL) {
1876 PyMem_Free(buf);
1877 return NULL;
1878 }
1879 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1880 PyMem_Free(buf);
1881 }
1882 return s;
1883}
1884
1885/* A larger buffer size may actually decrease performance. */
1886#define READAHEAD_BUFSIZE 8192
1887
1888static PyObject *
1889file_iternext(PyFileObject *f)
1890{
1891 PyStringObject* l;
1892
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001893 if (f->f_fp == NULL)
1894 return err_closed();
1895
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001896 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1897 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1898 Py_XDECREF(l);
1899 return NULL;
1900 }
1901 return (PyObject *)l;
1902}
1903
1904
Tim Peters59c9a642001-09-13 05:38:56 +00001905static PyObject *
1906file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1907{
Tim Peters44410012001-09-14 03:26:08 +00001908 PyObject *self;
1909 static PyObject *not_yet_string;
1910
1911 assert(type != NULL && type->tp_alloc != NULL);
1912
1913 if (not_yet_string == NULL) {
1914 not_yet_string = PyString_FromString("<uninitialized file>");
1915 if (not_yet_string == NULL)
1916 return NULL;
1917 }
1918
1919 self = type->tp_alloc(type, 0);
1920 if (self != NULL) {
1921 /* Always fill in the name and mode, so that nobody else
1922 needs to special-case NULLs there. */
1923 Py_INCREF(not_yet_string);
1924 ((PyFileObject *)self)->f_name = not_yet_string;
1925 Py_INCREF(not_yet_string);
1926 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001927 Py_INCREF(Py_None);
1928 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001929 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001930 }
1931 return self;
1932}
1933
1934static int
1935file_init(PyObject *self, PyObject *args, PyObject *kwds)
1936{
1937 PyFileObject *foself = (PyFileObject *)self;
1938 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001939 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001940 char *name = NULL;
1941 char *mode = "r";
1942 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001943 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001944
1945 assert(PyFile_Check(self));
1946 if (foself->f_fp != NULL) {
1947 /* Have to close the existing file first. */
1948 PyObject *closeresult = file_close(foself);
1949 if (closeresult == NULL)
1950 return -1;
1951 Py_DECREF(closeresult);
1952 }
Tim Peters59c9a642001-09-13 05:38:56 +00001953
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001954#ifdef Py_WIN_WIDE_FILENAMES
1955 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1956 PyObject *po;
1957 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1958 kwlist, &po, &mode, &bufsize)) {
1959 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001960 if (fill_file_fields(foself, NULL, po, mode,
1961 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001962 goto Error;
1963 } else {
1964 /* Drop the argument parsing error as narrow
1965 strings are also valid. */
1966 PyErr_Clear();
1967 }
1968 }
1969#endif
1970
1971 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001972 PyObject *o_name;
1973
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001974 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1975 Py_FileSystemDefaultEncoding,
1976 &name,
1977 &mode, &bufsize))
1978 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001979
1980 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001981 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1982 kwlist, &o_name, &mode,
1983 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001984 return -1;
1985
1986 if (fill_file_fields(foself, NULL, o_name, mode,
1987 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001988 goto Error;
1989 }
Tim Peters44410012001-09-14 03:26:08 +00001990 if (open_the_file(foself, name, mode) == NULL)
1991 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001992 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001993 PyFile_SetBufSize(self, bufsize);
1994 goto Done;
1995
1996Error:
1997 ret = -1;
1998 /* fall through */
1999Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002000 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002001 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002002}
2003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002004PyDoc_VAR(file_doc) =
2005PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002006"file(name[, mode[, buffering]]) -> file object\n"
2007"\n"
2008"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2009"writing or appending. The file will be created if it doesn't exist\n"
2010"when opened for writing or appending; it will be truncated when\n"
2011"opened for writing. Add a 'b' to the mode for binary files.\n"
2012"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2013"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002014"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002015)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002016PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002017"Add a 'U' to mode to open the file for input with universal newline\n"
2018"support. Any line ending in the input file will be seen as a '\\n'\n"
2019"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2020"the value for this attribute is one of None (no newline read yet),\n"
2021"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2022"\n"
2023"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024);
Tim Peters59c9a642001-09-13 05:38:56 +00002025
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002026PyTypeObject PyFile_Type = {
2027 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002028 0,
2029 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002031 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002032 (destructor)file_dealloc, /* tp_dealloc */
2033 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034 0, /* tp_getattr */
2035 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002036 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002038 0, /* tp_as_number */
2039 0, /* tp_as_sequence */
2040 0, /* tp_as_mapping */
2041 0, /* tp_hash */
2042 0, /* tp_call */
2043 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002045 /* softspace is writable: we must supply tp_setattro */
2046 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002047 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002048 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002049 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050 0, /* tp_traverse */
2051 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002052 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002053 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002054 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002055 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 file_methods, /* tp_methods */
2057 file_memberlist, /* tp_members */
2058 file_getsetlist, /* tp_getset */
2059 0, /* tp_base */
2060 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002061 0, /* tp_descr_get */
2062 0, /* tp_descr_set */
2063 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002064 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002065 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002066 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002067 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002068};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002069
2070/* Interface for the 'soft space' between print items. */
2071
2072int
Fred Drakefd99de62000-07-09 05:02:18 +00002073PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002074{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002075 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002076 if (f == NULL) {
2077 /* Do nothing */
2078 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002079 else if (PyFile_Check(f)) {
2080 oldflag = ((PyFileObject *)f)->f_softspace;
2081 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002082 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002083 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002084 PyObject *v;
2085 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002086 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002087 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002088 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002089 if (PyInt_Check(v))
2090 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002091 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002092 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002093 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002094 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002095 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002097 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2099 PyErr_Clear();
2100 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002101 }
2102 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002103 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002104}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002105
2106/* Interfaces to write objects/strings to file-like objects */
2107
2108int
Fred Drakefd99de62000-07-09 05:02:18 +00002109PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002110{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002111 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002112 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002114 return -1;
2115 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002116 else if (PyFile_Check(f)) {
2117 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002118#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002119 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2120 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002121#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002122 if (fp == NULL) {
2123 err_closed();
2124 return -1;
2125 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002126#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002127 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002128 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002129 char *cenc = PyString_AS_STRING(enc);
2130 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2131 if (value == NULL)
2132 return -1;
2133 } else {
2134 value = v;
2135 Py_INCREF(value);
2136 }
2137 result = PyObject_Print(value, fp, flags);
2138 Py_DECREF(value);
2139 return result;
2140#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002142#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002143 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002145 if (writer == NULL)
2146 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002147 if (flags & Py_PRINT_RAW) {
2148 if (PyUnicode_Check(v)) {
2149 value = v;
2150 Py_INCREF(value);
2151 } else
2152 value = PyObject_Str(v);
2153 }
2154 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002155 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002156 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002158 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002159 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002160 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002161 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002162 Py_DECREF(value);
2163 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002164 return -1;
2165 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166 result = PyEval_CallObject(writer, args);
2167 Py_DECREF(args);
2168 Py_DECREF(value);
2169 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002170 if (result == NULL)
2171 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002173 return 0;
2174}
2175
Guido van Rossum27a60b11997-05-22 22:25:11 +00002176int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002177PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002178{
2179 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002180 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002181 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002182 PyErr_SetString(PyExc_SystemError,
2183 "null file for PyFile_WriteString");
2184 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002185 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186 else if (PyFile_Check(f)) {
2187 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002188 if (fp == NULL) {
2189 err_closed();
2190 return -1;
2191 }
2192 fputs(s, fp);
2193 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002194 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 else if (!PyErr_Occurred()) {
2196 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002197 int err;
2198 if (v == NULL)
2199 return -1;
2200 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2201 Py_DECREF(v);
2202 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002203 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002204 else
2205 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002206}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002207
2208/* Try to get a file-descriptor from a Python object. If the object
2209 is an integer or long integer, its value is returned. If not, the
2210 object's fileno() method is called if it exists; the method must return
2211 an integer or long integer, which is returned as the file descriptor value.
2212 -1 is returned on failure.
2213*/
2214
2215int PyObject_AsFileDescriptor(PyObject *o)
2216{
2217 int fd;
2218 PyObject *meth;
2219
2220 if (PyInt_Check(o)) {
2221 fd = PyInt_AsLong(o);
2222 }
2223 else if (PyLong_Check(o)) {
2224 fd = PyLong_AsLong(o);
2225 }
2226 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2227 {
2228 PyObject *fno = PyEval_CallObject(meth, NULL);
2229 Py_DECREF(meth);
2230 if (fno == NULL)
2231 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002232
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002233 if (PyInt_Check(fno)) {
2234 fd = PyInt_AsLong(fno);
2235 Py_DECREF(fno);
2236 }
2237 else if (PyLong_Check(fno)) {
2238 fd = PyLong_AsLong(fno);
2239 Py_DECREF(fno);
2240 }
2241 else {
2242 PyErr_SetString(PyExc_TypeError,
2243 "fileno() returned a non-integer");
2244 Py_DECREF(fno);
2245 return -1;
2246 }
2247 }
2248 else {
2249 PyErr_SetString(PyExc_TypeError,
2250 "argument must be an int, or have a fileno() method.");
2251 return -1;
2252 }
2253
2254 if (fd < 0) {
2255 PyErr_Format(PyExc_ValueError,
2256 "file descriptor cannot be a negative integer (%i)",
2257 fd);
2258 return -1;
2259 }
2260 return fd;
2261}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002262
Jack Jansen7b8c7542002-04-14 20:12:41 +00002263/* From here on we need access to the real fgets and fread */
2264#undef fgets
2265#undef fread
2266
2267/*
2268** Py_UniversalNewlineFgets is an fgets variation that understands
2269** all of \r, \n and \r\n conventions.
2270** The stream should be opened in binary mode.
2271** If fobj is NULL the routine always does newline conversion, and
2272** it may peek one char ahead to gobble the second char in \r\n.
2273** If fobj is non-NULL it must be a PyFileObject. In this case there
2274** is no readahead but in stead a flag is used to skip a following
2275** \n on the next read. Also, if the file is open in binary mode
2276** the whole conversion is skipped. Finally, the routine keeps track of
2277** the different types of newlines seen.
2278** Note that we need no error handling: fgets() treats error and eof
2279** identically.
2280*/
2281char *
2282Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2283{
2284 char *p = buf;
2285 int c;
2286 int newlinetypes = 0;
2287 int skipnextlf = 0;
2288 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002289
Jack Jansen7b8c7542002-04-14 20:12:41 +00002290 if (fobj) {
2291 if (!PyFile_Check(fobj)) {
2292 errno = ENXIO; /* What can you do... */
2293 return NULL;
2294 }
2295 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2296 if ( !univ_newline )
2297 return fgets(buf, n, stream);
2298 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2299 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2300 }
2301 FLOCKFILE(stream);
2302 c = 'x'; /* Shut up gcc warning */
2303 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2304 if (skipnextlf ) {
2305 skipnextlf = 0;
2306 if (c == '\n') {
2307 /* Seeing a \n here with skipnextlf true
2308 ** means we saw a \r before.
2309 */
2310 newlinetypes |= NEWLINE_CRLF;
2311 c = GETC(stream);
2312 if (c == EOF) break;
2313 } else {
2314 /*
2315 ** Note that c == EOF also brings us here,
2316 ** so we're okay if the last char in the file
2317 ** is a CR.
2318 */
2319 newlinetypes |= NEWLINE_CR;
2320 }
2321 }
2322 if (c == '\r') {
2323 /* A \r is translated into a \n, and we skip
2324 ** an adjacent \n, if any. We don't set the
2325 ** newlinetypes flag until we've seen the next char.
2326 */
2327 skipnextlf = 1;
2328 c = '\n';
2329 } else if ( c == '\n') {
2330 newlinetypes |= NEWLINE_LF;
2331 }
2332 *p++ = c;
2333 if (c == '\n') break;
2334 }
2335 if ( c == EOF && skipnextlf )
2336 newlinetypes |= NEWLINE_CR;
2337 FUNLOCKFILE(stream);
2338 *p = '\0';
2339 if (fobj) {
2340 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2341 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2342 } else if ( skipnextlf ) {
2343 /* If we have no file object we cannot save the
2344 ** skipnextlf flag. We have to readahead, which
2345 ** will cause a pause if we're reading from an
2346 ** interactive stream, but that is very unlikely
2347 ** unless we're doing something silly like
2348 ** execfile("/dev/tty").
2349 */
2350 c = GETC(stream);
2351 if ( c != '\n' )
2352 ungetc(c, stream);
2353 }
2354 if (p == buf)
2355 return NULL;
2356 return buf;
2357}
2358
2359/*
2360** Py_UniversalNewlineFread is an fread variation that understands
2361** all of \r, \n and \r\n conventions.
2362** The stream should be opened in binary mode.
2363** fobj must be a PyFileObject. In this case there
2364** is no readahead but in stead a flag is used to skip a following
2365** \n on the next read. Also, if the file is open in binary mode
2366** the whole conversion is skipped. Finally, the routine keeps track of
2367** the different types of newlines seen.
2368*/
2369size_t
Tim Peters058b1412002-04-21 07:29:14 +00002370Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002371 FILE *stream, PyObject *fobj)
2372{
Tim Peters058b1412002-04-21 07:29:14 +00002373 char *dst = buf;
2374 PyFileObject *f = (PyFileObject *)fobj;
2375 int newlinetypes, skipnextlf;
2376
2377 assert(buf != NULL);
2378 assert(stream != NULL);
2379
Jack Jansen7b8c7542002-04-14 20:12:41 +00002380 if (!fobj || !PyFile_Check(fobj)) {
2381 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002382 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002383 }
Tim Peters058b1412002-04-21 07:29:14 +00002384 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002385 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002386 newlinetypes = f->f_newlinetypes;
2387 skipnextlf = f->f_skipnextlf;
2388 /* Invariant: n is the number of bytes remaining to be filled
2389 * in the buffer.
2390 */
2391 while (n) {
2392 size_t nread;
2393 int shortread;
2394 char *src = dst;
2395
2396 nread = fread(dst, 1, n, stream);
2397 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002398 if (nread == 0)
2399 break;
2400
Tim Peterse1682a82002-04-21 18:15:20 +00002401 n -= nread; /* assuming 1 byte out for each in; will adjust */
2402 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002403 while (nread--) {
2404 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002405 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002406 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002407 *dst++ = '\n';
2408 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002409 }
2410 else if (skipnextlf && c == '\n') {
2411 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002412 skipnextlf = 0;
2413 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002414 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002415 }
2416 else {
2417 /* Normal char to be stored in buffer. Also
2418 * update the newlinetypes flag if either this
2419 * is an LF or the previous char was a CR.
2420 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002421 if (c == '\n')
2422 newlinetypes |= NEWLINE_LF;
2423 else if (skipnextlf)
2424 newlinetypes |= NEWLINE_CR;
2425 *dst++ = c;
2426 skipnextlf = 0;
2427 }
2428 }
Tim Peters058b1412002-04-21 07:29:14 +00002429 if (shortread) {
2430 /* If this is EOF, update type flags. */
2431 if (skipnextlf && feof(stream))
2432 newlinetypes |= NEWLINE_CR;
2433 break;
2434 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002435 }
Tim Peters058b1412002-04-21 07:29:14 +00002436 f->f_newlinetypes = newlinetypes;
2437 f->f_skipnextlf = skipnextlf;
2438 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002439}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002440
2441#ifdef __cplusplus
2442}
2443#endif