blob: 997792a34c76c5268e0df21b1d23e48a7149be2d [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossumff7e83d1999-08-27 20:39:37 +00007#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00009#endif /* DONT_HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Mark Hammondc2e85bd2002-10-03 05:10:39 +000019#ifdef _MSC_VER
20/* Need GetVersion to see if on NT so safe to use _wfopen */
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#endif /* _MSC_VER */
24
Andrew MacIntyrec4874392002-02-26 11:36:35 +000025#if defined(PYOS_OS2) && defined(PYCC_GCC)
26#include <io.h>
27#endif
28
Guido van Rossumc0b618a1997-05-02 03:12:38 +000029#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000030
Guido van Rossumff7e83d1999-08-27 20:39:37 +000031#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000032#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000033#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Jack Jansen7b8c7542002-04-14 20:12:41 +000035#ifdef HAVE_GETC_UNLOCKED
36#define GETC(f) getc_unlocked(f)
37#define FLOCKFILE(f) flockfile(f)
38#define FUNLOCKFILE(f) funlockfile(f)
39#else
40#define GETC(f) getc(f)
41#define FLOCKFILE(f)
42#define FUNLOCKFILE(f)
43#endif
44
Jack Jansen7b8c7542002-04-14 20:12:41 +000045/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000050
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051#ifdef __cplusplus
52extern "C" {
53#endif
54
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000056PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000060 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062}
63
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000065PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000068 return NULL;
69 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000070 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000071}
72
Neil Schemenauered19b882002-03-23 02:06:50 +000073/* On Unix, fopen will succeed for directories.
74 In Python, there should be no file objects referring to
75 directories, so we need a check. */
76
77static PyFileObject*
78dircheck(PyFileObject* f)
79{
80#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
81 struct stat buf;
82 if (f->f_fp == NULL)
83 return f;
84 if (fstat(fileno(f->f_fp), &buf) == 0 &&
85 S_ISDIR(buf.st_mode)) {
86#ifdef HAVE_STRERROR
87 char *msg = strerror(EISDIR);
88#else
89 char *msg = "Is a directory";
90#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000091 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000092 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000093 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000094 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000095 return NULL;
96 }
97#endif
98 return f;
99}
100
Tim Peters59c9a642001-09-13 05:38:56 +0000101
102static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000103fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
104 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105{
Tim Peters59c9a642001-09-13 05:38:56 +0000106 assert(f != NULL);
107 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000108 assert(f->f_fp == NULL);
109
110 Py_DECREF(f->f_name);
111 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000112 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000113
114 Py_INCREF (name);
115 f->f_name = name;
116
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000118
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000119 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000120 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000121 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000122 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000123 f->f_univ_newline = (strchr(mode, 'U') != NULL);
124 f->f_newlinetypes = NEWLINE_UNKNOWN;
125 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000126 Py_INCREF(Py_None);
127 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000128
Tim Peters59c9a642001-09-13 05:38:56 +0000129 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000132 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000136/* check for known incorrect mode strings - problem is, platforms are
137 free to accept any mode characters they like and are supposed to
138 ignore stuff they don't understand... write or append mode with
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139 universal newline support is expressly forbidden by PEP 278.
140 Additionally, remove the 'U' from the mode string as platforms
141 won't know what it is. */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000142/* zero return is kewl - one is un-kewl */
143static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000144sanitize_the_mode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000145{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000146 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000147 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000148
Thomas Wouters477c8d52006-05-27 19:21:47 +0000149 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000150 PyErr_SetString(PyExc_ValueError, "empty mode string");
151 return 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000152 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000153
Thomas Wouters477c8d52006-05-27 19:21:47 +0000154 upos = strchr(mode, 'U');
155 if (upos) {
156 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000157
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158 if (mode[0] == 'w' || mode[0] == 'a') {
159 PyErr_Format(PyExc_ValueError, "universal newline "
160 "mode can only be used with modes "
161 "starting with 'r'");
162 return 1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000163 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000164
165 if (mode[0] != 'r') {
166 memmove(mode+1, mode, strlen(mode)+1);
167 mode[0] = 'r';
168 }
169
170 if (!strchr(mode, 'b')) {
171 memmove(mode+2, mode+1, strlen(mode));
172 mode[1] = 'b';
173 }
174 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
175 PyErr_Format(PyExc_ValueError, "mode string must begin with "
176 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
177 return 1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000178 }
179
180 return 0;
181}
182
Tim Peters59c9a642001-09-13 05:38:56 +0000183static PyObject *
184open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000186 char *newmode;
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
Thomas Wouters477c8d52006-05-27 19:21:47 +0000198 /* probably need to replace 'U' by 'rb' */
199 newmode = PyMem_MALLOC(strlen(mode) + 3);
200 if (!newmode) {
201 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000202 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000203 }
204 strcpy(newmode, mode);
205
206 if (sanitize_the_mode(newmode)) {
207 f = NULL;
208 goto cleanup;
209 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000210
Tim Peters8fa45672001-09-13 21:01:29 +0000211 /* rexec.py can't stop a user from getting the file() constructor --
212 all they have to do is get *any* file object f, and then do
213 type(f). Here we prevent them from doing damage with it. */
214 if (PyEval_GetRestricted()) {
215 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000216 "file() constructor not accessible in restricted mode");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000217 f = NULL;
218 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000219 }
Tim Petersa27a1502001-11-09 20:59:14 +0000220 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000221
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000222#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000223 if (PyUnicode_Check(f->f_name)) {
224 PyObject *wmode;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000225 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000226 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000227 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000228 /* PyUnicode_AS_UNICODE OK without thread
229 lock as it is a simple dereference. */
230 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
231 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000232 Py_END_ALLOW_THREADS
233 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000234 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000235 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000236#endif
237 if (NULL == f->f_fp && NULL != name) {
238 Py_BEGIN_ALLOW_THREADS
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239 f->f_fp = fopen(name, newmode);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000240 Py_END_ALLOW_THREADS
241 }
242
Guido van Rossuma08095a1991-02-13 23:25:27 +0000243 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000244#ifdef _MSC_VER
245 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
246 * across all Windows flavors. When it sets EINVAL varies
247 * across Windows flavors, the exact conditions aren't
248 * documented, and the answer lies in the OS's implementation
249 * of Win32's CreateFile function (whose source is secret).
250 * Seems the best we can do is map EINVAL to ENOENT.
251 */
252 if (errno == 0) /* bad mode string */
253 errno = EINVAL;
254 else if (errno == EINVAL) /* unknown, but not a mode string */
255 errno = ENOENT;
256#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000257 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000258 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000259 mode);
260 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000261 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000262 f = NULL;
263 }
Tim Peters2ea91112002-04-08 04:13:12 +0000264 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000265 f = dircheck(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000266
267cleanup:
268 PyMem_FREE(newmode);
269
Tim Peters59c9a642001-09-13 05:38:56 +0000270 return (PyObject *)f;
271}
272
273PyObject *
274PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
275{
Tim Peters44410012001-09-14 03:26:08 +0000276 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
277 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000278 if (f != NULL) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000279 PyObject *o_name = PyString_FromString(name);
280 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000281 Py_DECREF(f);
282 f = NULL;
283 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000284 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000285 }
286 return (PyObject *) f;
287}
288
289PyObject *
290PyFile_FromString(char *name, char *mode)
291{
292 extern int fclose(FILE *);
293 PyFileObject *f;
294
295 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
296 if (f != NULL) {
297 if (open_the_file(f, name, mode) == NULL) {
298 Py_DECREF(f);
299 f = NULL;
300 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303}
304
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305void
Fred Drakefd99de62000-07-09 05:02:18 +0000306PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000307{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000308 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000309 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310 int type;
311 switch (bufsize) {
312 case 0:
313 type = _IONBF;
314 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000315#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000316 case 1:
317 type = _IOLBF;
318 bufsize = BUFSIZ;
319 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000320#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000321 default:
322 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000323#ifndef HAVE_SETVBUF
324 bufsize = BUFSIZ;
325#endif
326 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000327 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000328 fflush(file->f_fp);
329 if (type == _IONBF) {
330 PyMem_Free(file->f_setbuf);
331 file->f_setbuf = NULL;
332 } else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000333 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
334 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000335 }
336#ifdef HAVE_SETVBUF
337 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000338#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000339 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000340#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000341 }
342}
343
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000344/* Set the encoding used to output Unicode strings.
345 Returh 1 on success, 0 on failure. */
346
347int
348PyFile_SetEncoding(PyObject *f, const char *enc)
349{
350 PyFileObject *file = (PyFileObject*)f;
351 PyObject *str = PyString_FromString(enc);
352 if (!str)
353 return 0;
354 Py_DECREF(file->f_encoding);
355 file->f_encoding = str;
356 return 1;
357}
358
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000359static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000360err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000361{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000362 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000363 return NULL;
364}
365
Thomas Woutersc45251a2006-02-12 11:53:32 +0000366/* Refuse regular file I/O if there's data in the iteration-buffer.
367 * Mixing them would cause data to arrive out of order, as the read*
368 * methods don't use the iteration buffer. */
369static PyObject *
370err_iterbuffered(void)
371{
372 PyErr_SetString(PyExc_ValueError,
373 "Mixing iteration and read methods would lose data");
374 return NULL;
375}
376
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000377static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000378
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379/* Methods */
380
381static void
Fred Drakefd99de62000-07-09 05:02:18 +0000382file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000384 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000385 if (f->weakreflist != NULL)
386 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000387 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000389 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000390 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000391 if (sts == EOF)
392#ifdef HAVE_STRERROR
393 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
394#else
395 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
396#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000397 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000398 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000399 Py_XDECREF(f->f_name);
400 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000401 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000402 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000403 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000407file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000409 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000410#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000411 PyObject *ret = NULL;
412 PyObject *name;
413 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
414 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
415 f->f_fp == NULL ? "closed" : "open",
416 PyString_AsString(name),
417 PyString_AsString(f->f_mode),
418 f);
419 Py_XDECREF(name);
420 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000421#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000422 } else {
423 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000424 f->f_fp == NULL ? "closed" : "open",
425 PyString_AsString(f->f_name),
426 PyString_AsString(f->f_mode),
427 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000428 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429}
430
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000431static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000432file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000434 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000436 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000438 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000439 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000441 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442 f->f_fp = NULL;
443 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000444 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000445 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000446 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000447 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000448 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449 return PyInt_FromLong((long)sts);
450 Py_INCREF(Py_None);
451 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452}
453
Trent Mickf29f47b2000-08-11 19:02:59 +0000454
Guido van Rossumb8552162001-09-05 14:58:11 +0000455/* Our very own off_t-like type, 64-bit if possible */
456#if !defined(HAVE_LARGEFILE_SUPPORT)
457typedef off_t Py_off_t;
458#elif SIZEOF_OFF_T >= 8
459typedef off_t Py_off_t;
460#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000461typedef fpos_t Py_off_t;
462#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000463#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000464#endif
465
466
Trent Mickf29f47b2000-08-11 19:02:59 +0000467/* a portable fseek() function
468 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000469static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000470_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000471{
Guido van Rossumb8552162001-09-05 14:58:11 +0000472#if !defined(HAVE_LARGEFILE_SUPPORT)
473 return fseek(fp, offset, whence);
474#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000475 return fseeko(fp, offset, whence);
476#elif defined(HAVE_FSEEK64)
477 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000478#elif defined(__BEOS__)
479 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000480#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000481 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
482 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000483 fpos_t pos;
484 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000485 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000486#ifdef MS_WINDOWS
487 fflush(fp);
488 if (_lseeki64(fileno(fp), 0, 2) == -1)
489 return -1;
490#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000491 if (fseek(fp, 0, SEEK_END) != 0)
492 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000493#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000494 /* fall through */
495 case SEEK_CUR:
496 if (fgetpos(fp, &pos) != 0)
497 return -1;
498 offset += pos;
499 break;
500 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000501 }
502 return fsetpos(fp, &offset);
503#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000504#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000505#endif
506}
507
508
509/* a portable ftell() function
510 Return -1 on failure with errno set appropriately, current file
511 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000512static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000513_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000514{
Guido van Rossumb8552162001-09-05 14:58:11 +0000515#if !defined(HAVE_LARGEFILE_SUPPORT)
516 return ftell(fp);
517#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
518 return ftello(fp);
519#elif defined(HAVE_FTELL64)
520 return ftell64(fp);
521#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000522 fpos_t pos;
523 if (fgetpos(fp, &pos) != 0)
524 return -1;
525 return pos;
526#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000527#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000528#endif
529}
530
531
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000533file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000534{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000535 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000536 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000537 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000538 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000539
Guido van Rossumd7297e61992-07-06 14:19:26 +0000540 if (f->f_fp == NULL)
541 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000542 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000543 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000544 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000545 return NULL;
546#if !defined(HAVE_LARGEFILE_SUPPORT)
547 offset = PyInt_AsLong(offobj);
548#else
549 offset = PyLong_Check(offobj) ?
550 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
551#endif
552 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000553 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000554
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000556 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000557 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000559
Guido van Rossumff4949e1992-08-05 19:58:53 +0000560 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000562 clearerr(f->f_fp);
563 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000564 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000565 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000566 Py_INCREF(Py_None);
567 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000568}
569
Trent Mickf29f47b2000-08-11 19:02:59 +0000570
Guido van Rossumd7047b31995-01-02 19:07:15 +0000571#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000573file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000574{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000575 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000576 PyObject *newsizeobj = NULL;
577 Py_off_t initialpos;
578 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000579
Guido van Rossumd7047b31995-01-02 19:07:15 +0000580 if (f->f_fp == NULL)
581 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000582 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000583 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000584
Tim Petersf1827cf2003-09-07 03:30:18 +0000585 /* Get current file position. If the file happens to be open for
586 * update and the last operation was an input operation, C doesn't
587 * define what the later fflush() will do, but we promise truncate()
588 * won't change the current position (and fflush() *does* change it
589 * then at least on Windows). The easiest thing is to capture
590 * current pos now and seek back to it at the end.
591 */
592 Py_BEGIN_ALLOW_THREADS
593 errno = 0;
594 initialpos = _portable_ftell(f->f_fp);
595 Py_END_ALLOW_THREADS
596 if (initialpos == -1)
597 goto onioerror;
598
Tim Petersfb05db22002-03-11 00:24:00 +0000599 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000600 * specified value.
601 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000602 if (newsizeobj != NULL) {
603#if !defined(HAVE_LARGEFILE_SUPPORT)
604 newsize = PyInt_AsLong(newsizeobj);
605#else
606 newsize = PyLong_Check(newsizeobj) ?
607 PyLong_AsLongLong(newsizeobj) :
608 PyInt_AsLong(newsizeobj);
609#endif
610 if (PyErr_Occurred())
611 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000612 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000613 else /* default to current position */
614 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000615
Tim Petersf1827cf2003-09-07 03:30:18 +0000616 /* Flush the stream. We're mixing stream-level I/O with lower-level
617 * I/O, and a flush may be necessary to synch both platform views
618 * of the current file state.
619 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000620 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000621 errno = 0;
622 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000624 if (ret != 0)
625 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000626
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000627#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000628 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000629 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000630 {
Tim Petersfb05db22002-03-11 00:24:00 +0000631 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000632
Tim Petersf1827cf2003-09-07 03:30:18 +0000633 /* Have to move current pos to desired endpoint on Windows. */
634 Py_BEGIN_ALLOW_THREADS
635 errno = 0;
636 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
637 Py_END_ALLOW_THREADS
638 if (ret)
639 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000640
Tim Peters8f01b682002-03-12 03:04:44 +0000641 /* Truncate. Note that this may grow the file! */
642 Py_BEGIN_ALLOW_THREADS
643 errno = 0;
644 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000645 ret = hFile == (HANDLE)-1;
646 if (ret == 0) {
647 ret = SetEndOfFile(hFile) == 0;
648 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000649 errno = EACCES;
650 }
651 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000652 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000653 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000654 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000655#else
656 Py_BEGIN_ALLOW_THREADS
657 errno = 0;
658 ret = ftruncate(fileno(f->f_fp), newsize);
659 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000660 if (ret != 0)
661 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000662#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000663
Tim Petersf1827cf2003-09-07 03:30:18 +0000664 /* Restore original file position. */
665 Py_BEGIN_ALLOW_THREADS
666 errno = 0;
667 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
668 Py_END_ALLOW_THREADS
669 if (ret)
670 goto onioerror;
671
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000672 Py_INCREF(Py_None);
673 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000674
675onioerror:
676 PyErr_SetFromErrno(PyExc_IOError);
677 clearerr(f->f_fp);
678 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000679}
680#endif /* HAVE_FTRUNCATE */
681
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000683file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000684{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000685 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000686
Guido van Rossumd7297e61992-07-06 14:19:26 +0000687 if (f->f_fp == NULL)
688 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000689 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000690 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000691 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000692 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000693 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000695 clearerr(f->f_fp);
696 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000697 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000698 if (f->f_skipnextlf) {
699 int c;
700 c = GETC(f->f_fp);
701 if (c == '\n') {
702 pos++;
703 f->f_skipnextlf = 0;
704 } else if (c != EOF) ungetc(c, f->f_fp);
705 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000706#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000707 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000708#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000709 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000710#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000711}
712
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000713static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000714file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000715{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000716 if (f->f_fp == NULL)
717 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000719}
720
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000721static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000722file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000723{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000724 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000725
Guido van Rossumd7297e61992-07-06 14:19:26 +0000726 if (f->f_fp == NULL)
727 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000729 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000730 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000732 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000733 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000734 clearerr(f->f_fp);
735 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000736 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737 Py_INCREF(Py_None);
738 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000739}
740
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000742file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000743{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000744 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000745 if (f->f_fp == NULL)
746 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000747 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000748 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000749 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000750 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000751}
752
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000753
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000754#if BUFSIZ < 8192
755#define SMALLCHUNK 8192
756#else
757#define SMALLCHUNK BUFSIZ
758#endif
759
Guido van Rossum3c259041999-01-14 19:00:14 +0000760#if SIZEOF_INT < 4
761#define BIGCHUNK (512 * 32)
762#else
763#define BIGCHUNK (512 * 1024)
764#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000765
766static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000767new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000768{
769#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000770 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000771 struct stat st;
772 if (fstat(fileno(f->f_fp), &st) == 0) {
773 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000774 /* The following is not a bug: we really need to call lseek()
775 *and* ftell(). The reason is that some stdio libraries
776 mistakenly flush their buffer when ftell() is called and
777 the lseek() call it makes fails, thereby throwing away
778 data that cannot be recovered in any way. To avoid this,
779 we first test lseek(), and only call ftell() if lseek()
780 works. We can't use the lseek() value either, because we
781 need to take the amount of buffered data into account.
782 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000783 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000784 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000785 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000786 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000787 if (pos < 0)
788 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000789 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000790 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000791 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000792 }
793#endif
794 if (currentsize > SMALLCHUNK) {
795 /* Keep doubling until we reach BIGCHUNK;
796 then keep adding BIGCHUNK. */
797 if (currentsize <= BIGCHUNK)
798 return currentsize + currentsize;
799 else
800 return currentsize + BIGCHUNK;
801 }
802 return currentsize + SMALLCHUNK;
803}
804
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000805#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
806#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
807#else
808#ifdef EWOULDBLOCK
809#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
810#else
811#ifdef EAGAIN
812#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
813#else
814#define BLOCKED_ERRNO(x) 0
815#endif
816#endif
817#endif
818
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000819static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000820file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000821{
Guido van Rossum789a1611997-05-10 22:33:55 +0000822 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000823 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000825
Guido van Rossumd7297e61992-07-06 14:19:26 +0000826 if (f->f_fp == NULL)
827 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000828 /* refuse to mix with f.next() */
829 if (f->f_buf != NULL &&
830 (f->f_bufend - f->f_bufptr) > 0 &&
831 f->f_buf[0] != '\0')
832 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000833 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000834 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000835 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000836 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000837 else
838 buffersize = bytesrequested;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000840 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000841 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000842 return NULL;
843 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000844 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000845 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000846 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000847 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000848 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000849 Py_BEGIN_ALLOW_THREADS
850 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000851 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000852 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000853 Py_END_ALLOW_THREADS
854 if (chunksize == 0) {
855 if (!ferror(f->f_fp))
856 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000857 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000858 /* When in non-blocking mode, data shouldn't
859 * be discarded if a blocking signal was
860 * received. That will also happen if
861 * chunksize != 0, but bytesread < buffersize. */
862 if (bytesread > 0 && BLOCKED_ERRNO(errno))
863 break;
864 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000865 Py_DECREF(v);
866 return NULL;
867 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000868 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000869 if (bytesread < buffersize) {
870 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000871 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000872 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000873 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000874 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000875 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000876 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000877 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000878 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000879 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000880 }
881 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000882 if (bytesread != buffersize)
883 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884 return v;
885}
886
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000887static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000888file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000889{
890 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000891 Py_ssize_t ntodo;
892 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000893
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000894 if (f->f_fp == NULL)
895 return err_closed();
Guido van Rossumd624f182006-04-24 13:47:05 +0000896 if (!f->f_binary) {
897 PyErr_SetString(PyExc_TypeError,
898 "readinto() requires binary mode");
899 return NULL;
900 }
Thomas Woutersc45251a2006-02-12 11:53:32 +0000901 /* refuse to mix with f.next() */
902 if (f->f_buf != NULL &&
903 (f->f_bufend - f->f_bufptr) > 0 &&
904 f->f_buf[0] != '\0')
905 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000906 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000907 return NULL;
908 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000909 while (ntodo > 0) {
910 Py_BEGIN_ALLOW_THREADS
911 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000912 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000913 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000914 Py_END_ALLOW_THREADS
915 if (nnow == 0) {
916 if (!ferror(f->f_fp))
917 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000918 PyErr_SetFromErrno(PyExc_IOError);
919 clearerr(f->f_fp);
920 return NULL;
921 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000922 ndone += nnow;
923 ntodo -= nnow;
924 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000925 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000926}
927
Tim Peters86821b22001-01-07 21:19:34 +0000928/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000929Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000930
931Under MSVC 6:
932
Tim Peters1c733232001-01-08 04:02:07 +0000933+ MS threadsafe getc is very slow (multiple layers of function calls before+
934 after each character, to lock+unlock the stream).
935+ The stream-locking functions are MS-internal -- can't access them from user
936 code.
937+ There's nothing Tim could find in the MS C or platform SDK libraries that
938 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000939+ MS fgets locks/unlocks only once per line; it's the only hook we have.
940
941So we use fgets for speed(!), despite that it's painful.
942
943MS realloc is also slow.
944
Tim Petersf29b64d2001-01-15 06:33:19 +0000945Reports from other platforms on this method vs getc_unlocked (which MS doesn't
946have):
947 Linux a wash
948 Solaris a wash
949 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000950
Tim Petersf29b64d2001-01-15 06:33:19 +0000951CAUTION: The C std isn't clear about this: in those cases where fgets
952writes something into the buffer, can it write into any position beyond the
953required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
954known on which it does; and it would be a strange way to code fgets. Still,
955getline_via_fgets may not work correctly if it does. The std test
956test_bufio.py should fail if platform fgets() routinely writes beyond the
957trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000958**************************************************************************/
959
Tim Petersf29b64d2001-01-15 06:33:19 +0000960/* Use this routine if told to, or by default on non-get_unlocked()
961 * platforms unless told not to. Yikes! Let's spell that out:
962 * On a platform with getc_unlocked():
963 * By default, use getc_unlocked().
964 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
965 * On a platform without getc_unlocked():
966 * By default, use fgets().
967 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
968 */
969#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
970#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000971#endif
972
Tim Petersf29b64d2001-01-15 06:33:19 +0000973#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
974#undef USE_FGETS_IN_GETLINE
975#endif
976
977#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000978static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000979getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000980{
Tim Peters15b83852001-01-08 00:53:12 +0000981/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000982 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
983 * to fill this much of the buffer with a known value in order to figure out
984 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
985 * than "most" lines, we waste time filling unused buffer slots. 100 is
986 * surely adequate for most peoples' email archives, chewing over source code,
987 * etc -- "regular old text files".
988 * MAXBUFSIZE is the maximum line length that lets us get away with the less
989 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
990 * cautions about boosting that. 300 was chosen because the worst real-life
991 * text-crunching job reported on Python-Dev was a mail-log crawler where over
992 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000993 */
Tim Peters142297a2001-01-15 10:36:56 +0000994#define INITBUFSIZE 100
995#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000996 char* p; /* temp */
997 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000998 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000999 char* pvfree; /* address of next free slot */
1000 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001001 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1002 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001003 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +00001004
Tim Peters15b83852001-01-08 00:53:12 +00001005 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001006 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001007 */
Tim Peters142297a2001-01-15 10:36:56 +00001008 total_v_size = INITBUFSIZE; /* start small and pray */
1009 pvfree = buf;
1010 for (;;) {
1011 Py_BEGIN_ALLOW_THREADS
1012 pvend = buf + total_v_size;
1013 nfree = pvend - pvfree;
1014 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001015 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1016 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +00001017 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001018
Tim Peters142297a2001-01-15 10:36:56 +00001019 if (p == NULL) {
1020 clearerr(fp);
1021 if (PyErr_CheckSignals())
1022 return NULL;
1023 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001024 return v;
1025 }
Tim Peters142297a2001-01-15 10:36:56 +00001026 /* fgets read *something* */
1027 p = memchr(pvfree, '\n', nfree);
1028 if (p != NULL) {
1029 /* Did the \n come from fgets or from us?
1030 * Since fgets stops at the first \n, and then writes
1031 * \0, if it's from fgets a \0 must be next. But if
1032 * that's so, it could not have come from us, since
1033 * the \n's we filled the buffer with have only more
1034 * \n's to the right.
1035 */
1036 if (p+1 < pvend && *(p+1) == '\0') {
1037 /* It's from fgets: we win! In particular,
1038 * we haven't done any mallocs yet, and can
1039 * build the final result on the first try.
1040 */
1041 ++p; /* include \n from fgets */
1042 }
1043 else {
1044 /* Must be from us: fgets didn't fill the
1045 * buffer and didn't find a newline, so it
1046 * must be the last and newline-free line of
1047 * the file.
1048 */
1049 assert(p > pvfree && *(p-1) == '\0');
1050 --p; /* don't include \0 from fgets */
1051 }
1052 v = PyString_FromStringAndSize(buf, p - buf);
1053 return v;
1054 }
1055 /* yuck: fgets overwrote all the newlines, i.e. the entire
1056 * buffer. So this line isn't over yet, or maybe it is but
1057 * we're exactly at EOF. If we haven't already, try using the
1058 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001059 */
Tim Peters142297a2001-01-15 10:36:56 +00001060 assert(*(pvend-1) == '\0');
1061 if (pvfree == buf) {
1062 pvfree = pvend - 1; /* overwrite trailing null */
1063 total_v_size = MAXBUFSIZE;
1064 }
1065 else
1066 break;
Tim Peters86821b22001-01-07 21:19:34 +00001067 }
Tim Peters142297a2001-01-15 10:36:56 +00001068
1069 /* The stack buffer isn't big enough; malloc a string object and read
1070 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001071 */
Tim Petersddea2082002-03-23 10:03:50 +00001072 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001073 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001074 if (v == NULL)
1075 return v;
1076 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001077 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1078 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001079
1080 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001081 * after setting p one beyond the end of the line. The code here is
1082 * very much like the code above, except reads into v's buffer; see
1083 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001084 */
1085 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001086 Py_BEGIN_ALLOW_THREADS
1087 pvend = BUF(v) + total_v_size;
1088 nfree = pvend - pvfree;
1089 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001090 assert(nfree < INT_MAX);
1091 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001092 Py_END_ALLOW_THREADS
1093
1094 if (p == NULL) {
1095 clearerr(fp);
1096 if (PyErr_CheckSignals()) {
1097 Py_DECREF(v);
1098 return NULL;
1099 }
1100 p = pvfree;
1101 break;
1102 }
Tim Peters86821b22001-01-07 21:19:34 +00001103 p = memchr(pvfree, '\n', nfree);
1104 if (p != NULL) {
1105 if (p+1 < pvend && *(p+1) == '\0') {
1106 /* \n came from fgets */
1107 ++p;
1108 break;
1109 }
1110 /* \n came from us; last line of file, no newline */
1111 assert(p > pvfree && *(p-1) == '\0');
1112 --p;
1113 break;
1114 }
1115 /* expand buffer and try again */
1116 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001117 increment = total_v_size >> 2; /* mild exponential growth */
1118 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001119 if (total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001120 PyErr_SetString(PyExc_OverflowError,
1121 "line is longer than a Python string can hold");
1122 Py_DECREF(v);
1123 return NULL;
1124 }
1125 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1126 return NULL;
1127 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001128 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001129 }
1130 if (BUF(v) + total_v_size != p)
1131 _PyString_Resize(&v, p - BUF(v));
1132 return v;
1133#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001134#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001135}
Tim Petersf29b64d2001-01-15 06:33:19 +00001136#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001137
Guido van Rossum0bd24411991-04-04 15:21:57 +00001138/* Internal routine to get a line.
1139 Size argument interpretation:
1140 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001141 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001142*/
1143
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001144static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001145get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001146{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001147 FILE *fp = f->f_fp;
1148 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001149 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001150 size_t total_v_size; /* total # of slots in buffer */
1151 size_t used_v_size; /* # used slots in buffer */
1152 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001153 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001154 int newlinetypes = f->f_newlinetypes;
1155 int skipnextlf = f->f_skipnextlf;
1156 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001157
Jack Jansen7b8c7542002-04-14 20:12:41 +00001158#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001159 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001160 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001161#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001162 total_v_size = n > 0 ? n : 100;
1163 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001164 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001165 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001166 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001167 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001168
Guido van Rossumce5ba841991-03-06 13:06:18 +00001169 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001170 Py_BEGIN_ALLOW_THREADS
1171 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001172 if (univ_newline) {
1173 c = 'x'; /* Shut up gcc warning */
1174 while ( buf != end && (c = GETC(fp)) != EOF ) {
1175 if (skipnextlf ) {
1176 skipnextlf = 0;
1177 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001178 /* Seeing a \n here with
1179 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001180 * saw a \r before.
1181 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001182 newlinetypes |= NEWLINE_CRLF;
1183 c = GETC(fp);
1184 if (c == EOF) break;
1185 } else {
1186 newlinetypes |= NEWLINE_CR;
1187 }
1188 }
1189 if (c == '\r') {
1190 skipnextlf = 1;
1191 c = '\n';
1192 } else if ( c == '\n')
1193 newlinetypes |= NEWLINE_LF;
1194 *buf++ = c;
1195 if (c == '\n') break;
1196 }
1197 if ( c == EOF && skipnextlf )
1198 newlinetypes |= NEWLINE_CR;
1199 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001200 while ((c = GETC(fp)) != EOF &&
1201 (*buf++ = c) != '\n' &&
1202 buf != end)
1203 ;
1204 FUNLOCKFILE(fp);
1205 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001206 f->f_newlinetypes = newlinetypes;
1207 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001208 if (c == '\n')
1209 break;
1210 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001211 if (ferror(fp)) {
1212 PyErr_SetFromErrno(PyExc_IOError);
1213 clearerr(fp);
1214 Py_DECREF(v);
1215 return NULL;
1216 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001217 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001218 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001219 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001220 return NULL;
1221 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001222 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001223 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001224 /* Must be because buf == end */
1225 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001226 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001227 used_v_size = total_v_size;
1228 increment = total_v_size >> 2; /* mild exponential growth */
1229 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001230 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001231 PyErr_SetString(PyExc_OverflowError,
1232 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001233 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001234 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001235 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001236 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001237 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001238 buf = BUF(v) + used_v_size;
1239 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001240 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001241
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001242 used_v_size = buf - BUF(v);
1243 if (used_v_size != total_v_size)
1244 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001245 return v;
1246}
1247
Guido van Rossum0bd24411991-04-04 15:21:57 +00001248/* External C interface */
1249
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001250PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001251PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001252{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001253 PyObject *result;
1254
Guido van Rossum3165fe61992-09-25 21:59:05 +00001255 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001256 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001257 return NULL;
1258 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001259
1260 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001261 PyFileObject *fo = (PyFileObject *)f;
1262 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001263 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001264 /* refuse to mix with f.next() */
1265 if (fo->f_buf != NULL &&
1266 (fo->f_bufend - fo->f_bufptr) > 0 &&
1267 fo->f_buf[0] != '\0')
1268 return err_iterbuffered();
1269 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001270 }
1271 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001272 PyObject *reader;
1273 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001275 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001276 if (reader == NULL)
1277 return NULL;
1278 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001279 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001280 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001281 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001282 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001283 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001284 return NULL;
1285 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001286 result = PyEval_CallObject(reader, args);
1287 Py_DECREF(reader);
1288 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001289 if (result != NULL && !PyString_Check(result) &&
1290 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001291 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001292 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001293 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001294 "object.readline() returned non-string");
1295 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001296 }
1297
1298 if (n < 0 && result != NULL && PyString_Check(result)) {
1299 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001300 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001301 if (len == 0) {
1302 Py_DECREF(result);
1303 result = NULL;
1304 PyErr_SetString(PyExc_EOFError,
1305 "EOF when reading a line");
1306 }
1307 else if (s[len-1] == '\n') {
1308 if (result->ob_refcnt == 1)
1309 _PyString_Resize(&result, len-1);
1310 else {
1311 PyObject *v;
1312 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001314 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001315 }
1316 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001317 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001318#ifdef Py_USING_UNICODE
1319 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1320 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001321 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001322 if (len == 0) {
1323 Py_DECREF(result);
1324 result = NULL;
1325 PyErr_SetString(PyExc_EOFError,
1326 "EOF when reading a line");
1327 }
1328 else if (s[len-1] == '\n') {
1329 if (result->ob_refcnt == 1)
1330 PyUnicode_Resize(&result, len-1);
1331 else {
1332 PyObject *v;
1333 v = PyUnicode_FromUnicode(s, len-1);
1334 Py_DECREF(result);
1335 result = v;
1336 }
1337 }
1338 }
1339#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001340 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001341}
1342
1343/* Python method */
1344
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001345static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001346file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001347{
Guido van Rossum789a1611997-05-10 22:33:55 +00001348 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001349
Guido van Rossumd7297e61992-07-06 14:19:26 +00001350 if (f->f_fp == NULL)
1351 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001352 /* refuse to mix with f.next() */
1353 if (f->f_buf != NULL &&
1354 (f->f_bufend - f->f_bufptr) > 0 &&
1355 f->f_buf[0] != '\0')
1356 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001357 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001358 return NULL;
1359 if (n == 0)
1360 return PyString_FromString("");
1361 if (n < 0)
1362 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001363 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001364}
1365
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001366static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001367file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001368{
Guido van Rossum789a1611997-05-10 22:33:55 +00001369 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001370 PyObject *list;
1371 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001372 char small_buffer[SMALLCHUNK];
1373 char *buffer = small_buffer;
1374 size_t buffersize = SMALLCHUNK;
1375 PyObject *big_buffer = NULL;
1376 size_t nfilled = 0;
1377 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001378 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001379 char *p, *q, *end;
1380 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001381 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001382
Guido van Rossumd7297e61992-07-06 14:19:26 +00001383 if (f->f_fp == NULL)
1384 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001385 /* refuse to mix with f.next() */
1386 if (f->f_buf != NULL &&
1387 (f->f_bufend - f->f_bufptr) > 0 &&
1388 f->f_buf[0] != '\0')
1389 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001390 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001391 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001392 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001393 return NULL;
1394 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001395 if (shortread)
1396 nread = 0;
1397 else {
1398 Py_BEGIN_ALLOW_THREADS
1399 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001400 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001401 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001402 Py_END_ALLOW_THREADS
1403 shortread = (nread < buffersize-nfilled);
1404 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001405 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001406 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001407 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001408 break;
1409 PyErr_SetFromErrno(PyExc_IOError);
1410 clearerr(f->f_fp);
1411 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001412 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001413 list = NULL;
1414 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001415 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001416 totalread += nread;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001417 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001418 if (p == NULL) {
1419 /* Need a larger buffer to fit this line */
1420 nfilled += nread;
1421 buffersize *= 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001422 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001423 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001424 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001425 goto error;
1426 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001427 if (big_buffer == NULL) {
1428 /* Create the big buffer */
1429 big_buffer = PyString_FromStringAndSize(
1430 NULL, buffersize);
1431 if (big_buffer == NULL)
1432 goto error;
1433 buffer = PyString_AS_STRING(big_buffer);
1434 memcpy(buffer, small_buffer, nfilled);
1435 }
1436 else {
1437 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001438 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1439 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001440 buffer = PyString_AS_STRING(big_buffer);
1441 }
1442 continue;
1443 }
1444 end = buffer+nfilled+nread;
1445 q = buffer;
1446 do {
1447 /* Process complete lines */
1448 p++;
1449 line = PyString_FromStringAndSize(q, p-q);
1450 if (line == NULL)
1451 goto error;
1452 err = PyList_Append(list, line);
1453 Py_DECREF(line);
1454 if (err != 0)
1455 goto error;
1456 q = p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001457 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001458 } while (p != NULL);
1459 /* Move the remaining incomplete line to the start */
1460 nfilled = end-q;
1461 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001462 if (sizehint > 0)
1463 if (totalread >= (size_t)sizehint)
1464 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001465 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001466 if (nfilled != 0) {
1467 /* Partial last line */
1468 line = PyString_FromStringAndSize(buffer, nfilled);
1469 if (line == NULL)
1470 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001471 if (sizehint > 0) {
1472 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001473 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001474 if (rest == NULL) {
1475 Py_DECREF(line);
1476 goto error;
1477 }
1478 PyString_Concat(&line, rest);
1479 Py_DECREF(rest);
1480 if (line == NULL)
1481 goto error;
1482 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001483 err = PyList_Append(list, line);
1484 Py_DECREF(line);
1485 if (err != 0)
1486 goto error;
1487 }
1488 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001489 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001490 return list;
1491}
1492
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001493static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001494file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001495{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001496 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001497 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001498 if (f->f_fp == NULL)
1499 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001500 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001501 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001502 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001503 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001504 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001505 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001506 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001507 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001508 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001509 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001510 return NULL;
1511 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001512 Py_INCREF(Py_None);
1513 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001514}
1515
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001516static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001517file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001518{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001519#define CHUNKSIZE 1000
1520 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001521 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001522 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001523 int index, islist;
1524 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001525
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001526 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001527 if (f->f_fp == NULL)
1528 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001529
1530 result = NULL;
1531 list = NULL;
1532 islist = PyList_Check(seq);
1533 if (islist)
1534 it = NULL;
1535 else {
1536 it = PyObject_GetIter(seq);
1537 if (it == NULL) {
1538 PyErr_SetString(PyExc_TypeError,
1539 "writelines() requires an iterable argument");
1540 return NULL;
1541 }
1542 /* From here on, fail by going to error, to reclaim "it". */
1543 list = PyList_New(CHUNKSIZE);
1544 if (list == NULL)
1545 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001546 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001547
1548 /* Strategy: slurp CHUNKSIZE lines into a private list,
1549 checking that they are all strings, then write that list
1550 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001551 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001552 if (islist) {
1553 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001554 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001555 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001556 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001557 j = PyList_GET_SIZE(list);
1558 }
1559 else {
1560 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001561 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001562 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001563 if (PyErr_Occurred())
1564 goto error;
1565 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001566 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001567 PyList_SetItem(list, j, line);
1568 }
1569 }
1570 if (j == 0)
1571 break;
1572
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001573 /* Check that all entries are indeed strings. If not,
1574 apply the same rules as for file.write() and
1575 convert the results to strings. This is slow, but
1576 seems to be the only way since all conversion APIs
1577 could potentially execute Python code. */
1578 for (i = 0; i < j; i++) {
1579 PyObject *v = PyList_GET_ITEM(list, i);
1580 if (!PyString_Check(v)) {
1581 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001582 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001583 PyObject_AsReadBuffer(v,
1584 (const void**)&buffer,
1585 &len)) ||
1586 PyObject_AsCharBuffer(v,
1587 &buffer,
1588 &len))) {
1589 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001590 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001591 goto error;
1592 }
1593 line = PyString_FromStringAndSize(buffer,
1594 len);
1595 if (line == NULL)
1596 goto error;
1597 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001598 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001599 }
1600 }
1601
1602 /* Since we are releasing the global lock, the
1603 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001604 Py_BEGIN_ALLOW_THREADS
1605 f->f_softspace = 0;
1606 errno = 0;
1607 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001608 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001609 len = PyString_GET_SIZE(line);
1610 nwritten = fwrite(PyString_AS_STRING(line),
1611 1, len, f->f_fp);
1612 if (nwritten != len) {
1613 Py_BLOCK_THREADS
1614 PyErr_SetFromErrno(PyExc_IOError);
1615 clearerr(f->f_fp);
1616 goto error;
1617 }
1618 }
1619 Py_END_ALLOW_THREADS
1620
1621 if (j < CHUNKSIZE)
1622 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001623 }
1624
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001625 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001626 result = Py_None;
1627 error:
1628 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001629 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001630 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001631#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001632}
1633
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001634static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001635file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001636{
1637 if (f->f_fp == NULL)
1638 return err_closed();
1639 Py_INCREF(f);
1640 return (PyObject *)f;
1641}
1642
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001643PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001644"readline([size]) -> next line from the file, as a string.\n"
1645"\n"
1646"Retain newline. A non-negative size argument limits the maximum\n"
1647"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001648"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001650PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001651"read([size]) -> read at most size bytes, returned as a string.\n"
1652"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001653"If the size argument is negative or omitted, read until EOF is reached.\n"
1654"Notice that when in non-blocking mode, less data than what was requested\n"
1655"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001657PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001658"write(str) -> None. Write string str to file.\n"
1659"\n"
1660"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001661"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001663PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001664"fileno() -> integer \"file descriptor\".\n"
1665"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001666"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001668PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001669"seek(offset[, whence]) -> None. Move to new file position.\n"
1670"\n"
1671"Argument offset is a byte count. Optional argument whence defaults to\n"
1672"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1673"(move relative to current position, positive or negative), and 2 (move\n"
1674"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001675"seeking beyond the end of a file). If the file is opened in text mode,\n"
1676"only offsets returned by tell() are legal. Use of other offsets causes\n"
1677"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001678"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001679"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001680
Guido van Rossumd7047b31995-01-02 19:07:15 +00001681#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001682PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001683"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1684"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001685"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001686#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001687
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001688PyDoc_STRVAR(tell_doc,
1689"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001691PyDoc_STRVAR(readinto_doc,
1692"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001694PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001695"readlines([size]) -> list of strings, each a line from the file.\n"
1696"\n"
1697"Call readline() repeatedly and return a list of the lines so read.\n"
1698"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001699"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001701PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001702"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001703"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001704"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001705"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001707PyDoc_STRVAR(flush_doc,
1708"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001710PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001711"close() -> None or (perhaps) an integer. Close the file.\n"
1712"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001713"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001714"further I/O operations. close() may be called more than once without\n"
1715"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001716"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001718PyDoc_STRVAR(isatty_doc,
1719"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001720
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001721PyDoc_STRVAR(enter_doc,
1722 "__enter__() -> self.");
1723
Tim Petersefc3a3a2001-09-20 07:55:22 +00001724static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001725 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1726 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1727 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1728 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1729 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001730#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001731 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001732#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001733 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1734 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1735 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001736 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1737 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1738 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1739 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001740 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Guido van Rossumf6694362006-03-10 02:28:35 +00001741 {"__exit__", (PyCFunction)file_close, METH_VARARGS, close_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001742 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001743};
1744
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001745#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001746
Guido van Rossum6f799372001-09-20 20:46:19 +00001747static PyMemberDef file_memberlist[] = {
1748 {"softspace", T_INT, OFF(f_softspace), 0,
1749 "flag indicating that a space needs to be printed; used by print"},
1750 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001751 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001752 {"name", T_OBJECT, OFF(f_name), RO,
1753 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001754 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1755 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001756 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001757 {NULL} /* Sentinel */
1758};
1759
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001760static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001762{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001763 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001764}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001765static PyObject *
1766get_newlines(PyFileObject *f, void *closure)
1767{
1768 switch (f->f_newlinetypes) {
1769 case NEWLINE_UNKNOWN:
1770 Py_INCREF(Py_None);
1771 return Py_None;
1772 case NEWLINE_CR:
1773 return PyString_FromString("\r");
1774 case NEWLINE_LF:
1775 return PyString_FromString("\n");
1776 case NEWLINE_CR|NEWLINE_LF:
1777 return Py_BuildValue("(ss)", "\r", "\n");
1778 case NEWLINE_CRLF:
1779 return PyString_FromString("\r\n");
1780 case NEWLINE_CR|NEWLINE_CRLF:
1781 return Py_BuildValue("(ss)", "\r", "\r\n");
1782 case NEWLINE_LF|NEWLINE_CRLF:
1783 return Py_BuildValue("(ss)", "\n", "\r\n");
1784 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1785 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1786 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001787 PyErr_Format(PyExc_SystemError,
1788 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001789 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001790 return NULL;
1791 }
1792}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001793
Guido van Rossum32d34c82001-09-20 21:45:26 +00001794static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001795 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001796 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001797 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 {0},
1799};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001800
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001801static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001802drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001803{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001804 if (f->f_buf != NULL) {
1805 PyMem_Free(f->f_buf);
1806 f->f_buf = NULL;
1807 }
Guido van Rossum65967252001-04-21 13:20:18 +00001808}
1809
Tim Petersf1827cf2003-09-07 03:30:18 +00001810/* Make sure that file has a readahead buffer with at least one byte
1811 (unless at EOF) and no more than bufsize. Returns negative value on
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001812 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001813static int
1814readahead(PyFileObject *f, int bufsize)
1815{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001816 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001817
1818 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001819 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001820 return 0;
1821 else
1822 drop_readahead(f);
1823 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001824 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
1825 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001826 return -1;
1827 }
1828 Py_BEGIN_ALLOW_THREADS
1829 errno = 0;
1830 chunksize = Py_UniversalNewlineFread(
1831 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1832 Py_END_ALLOW_THREADS
1833 if (chunksize == 0) {
1834 if (ferror(f->f_fp)) {
1835 PyErr_SetFromErrno(PyExc_IOError);
1836 clearerr(f->f_fp);
1837 drop_readahead(f);
1838 return -1;
1839 }
1840 }
1841 f->f_bufptr = f->f_buf;
1842 f->f_bufend = f->f_buf + chunksize;
1843 return 0;
1844}
1845
1846/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001847 uninitialized bytes followed by the remainder of the line. Don't be
1848 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001849 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1850
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001851static PyStringObject *
1852readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1853{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001854 PyStringObject* s;
1855 char *bufptr;
1856 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001857 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001858
1859 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001860 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001861 return NULL;
1862
1863 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001864 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001865 return (PyStringObject *)
1866 PyString_FromStringAndSize(NULL, skip);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001867 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001868 if (bufptr != NULL) {
1869 bufptr++; /* Count the '\n' */
1870 len = bufptr - f->f_bufptr;
1871 s = (PyStringObject *)
1872 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001873 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001874 return NULL;
1875 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1876 f->f_bufptr = bufptr;
1877 if (bufptr == f->f_bufend)
1878 drop_readahead(f);
1879 } else {
1880 bufptr = f->f_bufptr;
1881 buf = f->f_buf;
1882 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001883 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001884 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001885 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001886 if (s == NULL) {
1887 PyMem_Free(buf);
1888 return NULL;
1889 }
1890 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1891 PyMem_Free(buf);
1892 }
1893 return s;
1894}
1895
1896/* A larger buffer size may actually decrease performance. */
1897#define READAHEAD_BUFSIZE 8192
1898
1899static PyObject *
1900file_iternext(PyFileObject *f)
1901{
1902 PyStringObject* l;
1903
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001904 if (f->f_fp == NULL)
1905 return err_closed();
1906
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001907 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1908 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1909 Py_XDECREF(l);
1910 return NULL;
1911 }
1912 return (PyObject *)l;
1913}
1914
1915
Tim Peters59c9a642001-09-13 05:38:56 +00001916static PyObject *
1917file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1918{
Tim Peters44410012001-09-14 03:26:08 +00001919 PyObject *self;
1920 static PyObject *not_yet_string;
1921
1922 assert(type != NULL && type->tp_alloc != NULL);
1923
1924 if (not_yet_string == NULL) {
1925 not_yet_string = PyString_FromString("<uninitialized file>");
1926 if (not_yet_string == NULL)
1927 return NULL;
1928 }
1929
1930 self = type->tp_alloc(type, 0);
1931 if (self != NULL) {
1932 /* Always fill in the name and mode, so that nobody else
1933 needs to special-case NULLs there. */
1934 Py_INCREF(not_yet_string);
1935 ((PyFileObject *)self)->f_name = not_yet_string;
1936 Py_INCREF(not_yet_string);
1937 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001938 Py_INCREF(Py_None);
1939 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001940 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001941 }
1942 return self;
1943}
1944
1945static int
1946file_init(PyObject *self, PyObject *args, PyObject *kwds)
1947{
1948 PyFileObject *foself = (PyFileObject *)self;
1949 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001950 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001951 char *name = NULL;
1952 char *mode = "r";
1953 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001954 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001955
1956 assert(PyFile_Check(self));
1957 if (foself->f_fp != NULL) {
1958 /* Have to close the existing file first. */
1959 PyObject *closeresult = file_close(foself);
1960 if (closeresult == NULL)
1961 return -1;
1962 Py_DECREF(closeresult);
1963 }
Tim Peters59c9a642001-09-13 05:38:56 +00001964
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001965#ifdef Py_WIN_WIDE_FILENAMES
1966 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1967 PyObject *po;
1968 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1969 kwlist, &po, &mode, &bufsize)) {
1970 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001971 if (fill_file_fields(foself, NULL, po, mode,
1972 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001973 goto Error;
1974 } else {
1975 /* Drop the argument parsing error as narrow
1976 strings are also valid. */
1977 PyErr_Clear();
1978 }
1979 }
1980#endif
1981
1982 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001983 PyObject *o_name;
1984
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001985 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1986 Py_FileSystemDefaultEncoding,
1987 &name,
1988 &mode, &bufsize))
1989 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001990
1991 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001992 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1993 kwlist, &o_name, &mode,
1994 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001995 return -1;
1996
1997 if (fill_file_fields(foself, NULL, o_name, mode,
1998 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001999 goto Error;
2000 }
Tim Peters44410012001-09-14 03:26:08 +00002001 if (open_the_file(foself, name, mode) == NULL)
2002 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002003 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002004 PyFile_SetBufSize(self, bufsize);
2005 goto Done;
2006
2007Error:
2008 ret = -1;
2009 /* fall through */
2010Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002011 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002012 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002013}
2014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002015PyDoc_VAR(file_doc) =
2016PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002017"file(name[, mode[, buffering]]) -> file object\n"
2018"\n"
2019"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2020"writing or appending. The file will be created if it doesn't exist\n"
2021"when opened for writing or appending; it will be truncated when\n"
2022"opened for writing. Add a 'b' to the mode for binary files.\n"
2023"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2024"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002025"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002026)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002028"Add a 'U' to mode to open the file for input with universal newline\n"
2029"support. Any line ending in the input file will be seen as a '\\n'\n"
2030"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2031"the value for this attribute is one of None (no newline read yet),\n"
2032"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2033"\n"
2034"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002035);
Tim Peters59c9a642001-09-13 05:38:56 +00002036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037PyTypeObject PyFile_Type = {
2038 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002039 0,
2040 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002041 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002042 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002043 (destructor)file_dealloc, /* tp_dealloc */
2044 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 0, /* tp_getattr */
2046 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002047 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002049 0, /* tp_as_number */
2050 0, /* tp_as_sequence */
2051 0, /* tp_as_mapping */
2052 0, /* tp_hash */
2053 0, /* tp_call */
2054 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002056 /* softspace is writable: we must supply tp_setattro */
2057 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002058 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002059 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002060 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061 0, /* tp_traverse */
2062 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002063 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002064 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002065 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002066 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 file_methods, /* tp_methods */
2068 file_memberlist, /* tp_members */
2069 file_getsetlist, /* tp_getset */
2070 0, /* tp_base */
2071 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002072 0, /* tp_descr_get */
2073 0, /* tp_descr_set */
2074 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002075 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002076 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002077 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002078 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002079};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002080
2081/* Interface for the 'soft space' between print items. */
2082
2083int
Fred Drakefd99de62000-07-09 05:02:18 +00002084PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002085{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002086 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002087 if (f == NULL) {
2088 /* Do nothing */
2089 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002090 else if (PyFile_Check(f)) {
2091 oldflag = ((PyFileObject *)f)->f_softspace;
2092 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002093 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002094 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002095 PyObject *v;
2096 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002097 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002099 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 if (PyInt_Check(v))
2101 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002102 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002103 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002104 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002106 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002108 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002109 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2110 PyErr_Clear();
2111 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002112 }
2113 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002114 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002115}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002116
2117/* Interfaces to write objects/strings to file-like objects */
2118
2119int
Fred Drakefd99de62000-07-09 05:02:18 +00002120PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002121{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002123 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002124 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002125 return -1;
2126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002127 else if (PyFile_Check(f)) {
2128 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002129#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002130 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2131 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002132#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002133 if (fp == NULL) {
2134 err_closed();
2135 return -1;
2136 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002137#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002138 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002139 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002140 char *cenc = PyString_AS_STRING(enc);
2141 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2142 if (value == NULL)
2143 return -1;
2144 } else {
2145 value = v;
2146 Py_INCREF(value);
2147 }
2148 result = PyObject_Print(value, fp, flags);
2149 Py_DECREF(value);
2150 return result;
2151#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002152 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002153#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002154 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002155 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002156 if (writer == NULL)
2157 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002158 if (flags & Py_PRINT_RAW) {
2159 if (PyUnicode_Check(v)) {
2160 value = v;
2161 Py_INCREF(value);
2162 } else
2163 value = PyObject_Str(v);
2164 }
2165 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002167 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002168 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002169 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002170 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002171 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002172 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173 Py_DECREF(value);
2174 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002175 return -1;
2176 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002177 result = PyEval_CallObject(writer, args);
2178 Py_DECREF(args);
2179 Py_DECREF(value);
2180 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002181 if (result == NULL)
2182 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002183 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002184 return 0;
2185}
2186
Guido van Rossum27a60b11997-05-22 22:25:11 +00002187int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002188PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002189{
2190 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002191 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002192 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002193 PyErr_SetString(PyExc_SystemError,
2194 "null file for PyFile_WriteString");
2195 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002196 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002197 else if (PyFile_Check(f)) {
2198 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002199 if (fp == NULL) {
2200 err_closed();
2201 return -1;
2202 }
2203 fputs(s, fp);
2204 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002205 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002206 else if (!PyErr_Occurred()) {
2207 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002208 int err;
2209 if (v == NULL)
2210 return -1;
2211 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2212 Py_DECREF(v);
2213 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002214 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002215 else
2216 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002217}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002218
2219/* Try to get a file-descriptor from a Python object. If the object
2220 is an integer or long integer, its value is returned. If not, the
2221 object's fileno() method is called if it exists; the method must return
2222 an integer or long integer, which is returned as the file descriptor value.
2223 -1 is returned on failure.
2224*/
2225
2226int PyObject_AsFileDescriptor(PyObject *o)
2227{
2228 int fd;
2229 PyObject *meth;
2230
2231 if (PyInt_Check(o)) {
2232 fd = PyInt_AsLong(o);
2233 }
2234 else if (PyLong_Check(o)) {
2235 fd = PyLong_AsLong(o);
2236 }
2237 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2238 {
2239 PyObject *fno = PyEval_CallObject(meth, NULL);
2240 Py_DECREF(meth);
2241 if (fno == NULL)
2242 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002243
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002244 if (PyInt_Check(fno)) {
2245 fd = PyInt_AsLong(fno);
2246 Py_DECREF(fno);
2247 }
2248 else if (PyLong_Check(fno)) {
2249 fd = PyLong_AsLong(fno);
2250 Py_DECREF(fno);
2251 }
2252 else {
2253 PyErr_SetString(PyExc_TypeError,
2254 "fileno() returned a non-integer");
2255 Py_DECREF(fno);
2256 return -1;
2257 }
2258 }
2259 else {
2260 PyErr_SetString(PyExc_TypeError,
2261 "argument must be an int, or have a fileno() method.");
2262 return -1;
2263 }
2264
2265 if (fd < 0) {
2266 PyErr_Format(PyExc_ValueError,
2267 "file descriptor cannot be a negative integer (%i)",
2268 fd);
2269 return -1;
2270 }
2271 return fd;
2272}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002273
Jack Jansen7b8c7542002-04-14 20:12:41 +00002274/* From here on we need access to the real fgets and fread */
2275#undef fgets
2276#undef fread
2277
2278/*
2279** Py_UniversalNewlineFgets is an fgets variation that understands
2280** all of \r, \n and \r\n conventions.
2281** The stream should be opened in binary mode.
2282** If fobj is NULL the routine always does newline conversion, and
2283** it may peek one char ahead to gobble the second char in \r\n.
2284** If fobj is non-NULL it must be a PyFileObject. In this case there
2285** is no readahead but in stead a flag is used to skip a following
2286** \n on the next read. Also, if the file is open in binary mode
2287** the whole conversion is skipped. Finally, the routine keeps track of
2288** the different types of newlines seen.
2289** Note that we need no error handling: fgets() treats error and eof
2290** identically.
2291*/
2292char *
2293Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2294{
2295 char *p = buf;
2296 int c;
2297 int newlinetypes = 0;
2298 int skipnextlf = 0;
2299 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002300
Jack Jansen7b8c7542002-04-14 20:12:41 +00002301 if (fobj) {
2302 if (!PyFile_Check(fobj)) {
2303 errno = ENXIO; /* What can you do... */
2304 return NULL;
2305 }
2306 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2307 if ( !univ_newline )
2308 return fgets(buf, n, stream);
2309 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2310 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2311 }
2312 FLOCKFILE(stream);
2313 c = 'x'; /* Shut up gcc warning */
2314 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2315 if (skipnextlf ) {
2316 skipnextlf = 0;
2317 if (c == '\n') {
2318 /* Seeing a \n here with skipnextlf true
2319 ** means we saw a \r before.
2320 */
2321 newlinetypes |= NEWLINE_CRLF;
2322 c = GETC(stream);
2323 if (c == EOF) break;
2324 } else {
2325 /*
2326 ** Note that c == EOF also brings us here,
2327 ** so we're okay if the last char in the file
2328 ** is a CR.
2329 */
2330 newlinetypes |= NEWLINE_CR;
2331 }
2332 }
2333 if (c == '\r') {
2334 /* A \r is translated into a \n, and we skip
2335 ** an adjacent \n, if any. We don't set the
2336 ** newlinetypes flag until we've seen the next char.
2337 */
2338 skipnextlf = 1;
2339 c = '\n';
2340 } else if ( c == '\n') {
2341 newlinetypes |= NEWLINE_LF;
2342 }
2343 *p++ = c;
2344 if (c == '\n') break;
2345 }
2346 if ( c == EOF && skipnextlf )
2347 newlinetypes |= NEWLINE_CR;
2348 FUNLOCKFILE(stream);
2349 *p = '\0';
2350 if (fobj) {
2351 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2352 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2353 } else if ( skipnextlf ) {
2354 /* If we have no file object we cannot save the
2355 ** skipnextlf flag. We have to readahead, which
2356 ** will cause a pause if we're reading from an
2357 ** interactive stream, but that is very unlikely
2358 ** unless we're doing something silly like
2359 ** execfile("/dev/tty").
2360 */
2361 c = GETC(stream);
2362 if ( c != '\n' )
2363 ungetc(c, stream);
2364 }
2365 if (p == buf)
2366 return NULL;
2367 return buf;
2368}
2369
2370/*
2371** Py_UniversalNewlineFread is an fread variation that understands
2372** all of \r, \n and \r\n conventions.
2373** The stream should be opened in binary mode.
2374** fobj must be a PyFileObject. In this case there
2375** is no readahead but in stead a flag is used to skip a following
2376** \n on the next read. Also, if the file is open in binary mode
2377** the whole conversion is skipped. Finally, the routine keeps track of
2378** the different types of newlines seen.
2379*/
2380size_t
Tim Peters058b1412002-04-21 07:29:14 +00002381Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002382 FILE *stream, PyObject *fobj)
2383{
Tim Peters058b1412002-04-21 07:29:14 +00002384 char *dst = buf;
2385 PyFileObject *f = (PyFileObject *)fobj;
2386 int newlinetypes, skipnextlf;
2387
2388 assert(buf != NULL);
2389 assert(stream != NULL);
2390
Jack Jansen7b8c7542002-04-14 20:12:41 +00002391 if (!fobj || !PyFile_Check(fobj)) {
2392 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002393 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002394 }
Tim Peters058b1412002-04-21 07:29:14 +00002395 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002396 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002397 newlinetypes = f->f_newlinetypes;
2398 skipnextlf = f->f_skipnextlf;
2399 /* Invariant: n is the number of bytes remaining to be filled
2400 * in the buffer.
2401 */
2402 while (n) {
2403 size_t nread;
2404 int shortread;
2405 char *src = dst;
2406
2407 nread = fread(dst, 1, n, stream);
2408 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002409 if (nread == 0)
2410 break;
2411
Tim Peterse1682a82002-04-21 18:15:20 +00002412 n -= nread; /* assuming 1 byte out for each in; will adjust */
2413 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002414 while (nread--) {
2415 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002416 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002417 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002418 *dst++ = '\n';
2419 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002420 }
2421 else if (skipnextlf && c == '\n') {
2422 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002423 skipnextlf = 0;
2424 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002425 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002426 }
2427 else {
2428 /* Normal char to be stored in buffer. Also
2429 * update the newlinetypes flag if either this
2430 * is an LF or the previous char was a CR.
2431 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002432 if (c == '\n')
2433 newlinetypes |= NEWLINE_LF;
2434 else if (skipnextlf)
2435 newlinetypes |= NEWLINE_CR;
2436 *dst++ = c;
2437 skipnextlf = 0;
2438 }
2439 }
Tim Peters058b1412002-04-21 07:29:14 +00002440 if (shortread) {
2441 /* If this is EOF, update type flags. */
2442 if (skipnextlf && feof(stream))
2443 newlinetypes |= NEWLINE_CR;
2444 break;
2445 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002446 }
Tim Peters058b1412002-04-21 07:29:14 +00002447 f->f_newlinetypes = newlinetypes;
2448 f->f_skipnextlf = skipnextlf;
2449 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002450}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002451
2452#ifdef __cplusplus
2453}
2454#endif