blob: 50b3cd676fdb187d2a9c0243db2179100e6e3429 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009#endif /* 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{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000107 assert(f != NULL);
108 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000109 assert(f->f_fp == NULL);
110
111 Py_DECREF(f->f_name);
112 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000113 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000114
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000115 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000116 f->f_name = name;
117
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000119
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000120 f->f_close = close;
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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000129 if (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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000141 won't know what it is. Non-zero return signals an exception */
142int
143_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000144{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000146 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000147
Thomas Wouters477c8d52006-05-27 19:21:47 +0000148 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000149 PyErr_SetString(PyExc_ValueError, "empty mode string");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000151 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000152
Thomas Wouters477c8d52006-05-27 19:21:47 +0000153 upos = strchr(mode, 'U');
154 if (upos) {
155 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000156
Thomas Wouters477c8d52006-05-27 19:21:47 +0000157 if (mode[0] == 'w' || mode[0] == 'a') {
158 PyErr_Format(PyExc_ValueError, "universal newline "
159 "mode can only be used with modes "
160 "starting with 'r'");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000162 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000163
164 if (mode[0] != 'r') {
165 memmove(mode+1, mode, strlen(mode)+1);
166 mode[0] = 'r';
167 }
168
169 if (!strchr(mode, 'b')) {
170 memmove(mode+2, mode+1, strlen(mode));
171 mode[1] = 'b';
172 }
173 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
174 PyErr_Format(PyExc_ValueError, "mode string must begin with "
175 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000176 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000177 }
178
179 return 0;
180}
181
Tim Peters59c9a642001-09-13 05:38:56 +0000182static PyObject *
183open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000185 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000186 assert(f != NULL);
187 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000188#ifdef MS_WINDOWS
189 /* windows ignores the passed name in order to support Unicode */
190 assert(f->f_name != NULL);
191#else
Tim Peters59c9a642001-09-13 05:38:56 +0000192 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000193#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000194 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000195 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000196
Thomas Wouters477c8d52006-05-27 19:21:47 +0000197 /* probably need to replace 'U' by 'rb' */
198 newmode = PyMem_MALLOC(strlen(mode) + 3);
199 if (!newmode) {
200 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000201 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000202 }
203 strcpy(newmode, mode);
204
Guido van Rossumd8faa362007-04-27 19:54:29 +0000205 if (_PyFile_SanitizeMode(newmode)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000206 f = NULL;
207 goto cleanup;
208 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000209
Tim Peters8fa45672001-09-13 21:01:29 +0000210 /* rexec.py can't stop a user from getting the file() constructor --
211 all they have to do is get *any* file object f, and then do
212 type(f). Here we prevent them from doing damage with it. */
213 if (PyEval_GetRestricted()) {
214 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000215 "file() constructor not accessible in restricted mode");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000216 f = NULL;
217 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000218 }
Tim Petersa27a1502001-11-09 20:59:14 +0000219 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000220
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000221#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000222 if (PyUnicode_Check(f->f_name)) {
223 PyObject *wmode;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000224 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000225 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000226 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000227 /* PyUnicode_AS_UNICODE OK without thread
228 lock as it is a simple dereference. */
229 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
230 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000231 Py_END_ALLOW_THREADS
232 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000233 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000234 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000235#endif
236 if (NULL == f->f_fp && NULL != name) {
237 Py_BEGIN_ALLOW_THREADS
Thomas Wouters477c8d52006-05-27 19:21:47 +0000238 f->f_fp = fopen(name, newmode);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000239 Py_END_ALLOW_THREADS
240 }
241
Guido van Rossuma08095a1991-02-13 23:25:27 +0000242 if (f->f_fp == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000243#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000244 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
245 * across all Windows flavors. When it sets EINVAL varies
246 * across Windows flavors, the exact conditions aren't
247 * documented, and the answer lies in the OS's implementation
248 * of Win32's CreateFile function (whose source is secret).
249 * Seems the best we can do is map EINVAL to ENOENT.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000250 * Starting with Visual Studio .NET 2005, EINVAL is correctly
251 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000252 */
253 if (errno == 0) /* bad mode string */
254 errno = EINVAL;
255 else if (errno == EINVAL) /* unknown, but not a mode string */
256 errno = ENOENT;
257#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000258 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000259 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000260 mode);
261 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000262 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000263 f = NULL;
264 }
Tim Peters2ea91112002-04-08 04:13:12 +0000265 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000266 f = dircheck(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000267
268cleanup:
269 PyMem_FREE(newmode);
270
Tim Peters59c9a642001-09-13 05:38:56 +0000271 return (PyObject *)f;
272}
273
274PyObject *
275PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
276{
Tim Peters44410012001-09-14 03:26:08 +0000277 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
278 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000279 if (f != NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000280 PyObject *o_name = PyString_FromString(name);
281 if (o_name == NULL)
282 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000283 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000284 Py_DECREF(f);
285 f = NULL;
286 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000287 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000288 }
289 return (PyObject *) f;
290}
291
292PyObject *
293PyFile_FromString(char *name, char *mode)
294{
295 extern int fclose(FILE *);
296 PyFileObject *f;
297
298 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
299 if (f != NULL) {
300 if (open_the_file(f, name, mode) == NULL) {
301 Py_DECREF(f);
302 f = NULL;
303 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306}
307
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308void
Fred Drakefd99de62000-07-09 05:02:18 +0000309PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000311 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000312 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000313 int type;
314 switch (bufsize) {
315 case 0:
316 type = _IONBF;
317 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000318#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000319 case 1:
320 type = _IOLBF;
321 bufsize = BUFSIZ;
322 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000323#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000324 default:
325 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000326#ifndef HAVE_SETVBUF
327 bufsize = BUFSIZ;
328#endif
329 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000330 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000331 fflush(file->f_fp);
332 if (type == _IONBF) {
333 PyMem_Free(file->f_setbuf);
334 file->f_setbuf = NULL;
335 } else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000336 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
337 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000338 }
339#ifdef HAVE_SETVBUF
340 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000341#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000342 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000343#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000344 }
345}
346
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000347/* Set the encoding used to output Unicode strings.
348 Returh 1 on success, 0 on failure. */
349
350int
351PyFile_SetEncoding(PyObject *f, const char *enc)
352{
353 PyFileObject *file = (PyFileObject*)f;
354 PyObject *str = PyString_FromString(enc);
Thomas Woutersb2137042007-02-01 18:02:27 +0000355
356 assert(PyFile_Check(f));
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000357 if (!str)
358 return 0;
359 Py_DECREF(file->f_encoding);
360 file->f_encoding = str;
361 return 1;
362}
363
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000365err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000366{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000368 return NULL;
369}
370
Thomas Woutersc45251a2006-02-12 11:53:32 +0000371/* Refuse regular file I/O if there's data in the iteration-buffer.
372 * Mixing them would cause data to arrive out of order, as the read*
373 * methods don't use the iteration buffer. */
374static PyObject *
375err_iterbuffered(void)
376{
377 PyErr_SetString(PyExc_ValueError,
378 "Mixing iteration and read methods would lose data");
379 return NULL;
380}
381
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000382static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000383
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384/* Methods */
385
386static void
Fred Drakefd99de62000-07-09 05:02:18 +0000387file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000388{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000389 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000390 if (f->weakreflist != NULL)
391 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000392 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000394 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000396 if (sts == EOF)
397#ifdef HAVE_STRERROR
398 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
399#else
400 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
401#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000402 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000403 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000404 Py_XDECREF(f->f_name);
405 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000406 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000407 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000408 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409}
410
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000412file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000414 if (PyUnicode_Check(f->f_name)) {
415 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000416 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
417 const char *name_str = name ? PyString_AsString(name) : "?";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000418 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
419 f->f_fp == NULL ? "closed" : "open",
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000420 name_str,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000421 PyString_AsString(f->f_mode),
422 f);
423 Py_XDECREF(name);
424 return ret;
425 } else {
426 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000427 f->f_fp == NULL ? "closed" : "open",
428 PyString_AsString(f->f_name),
429 PyString_AsString(f->f_mode),
430 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000431 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432}
433
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000435file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000437 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000439 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000441 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000442 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000443 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000444 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445 f->f_fp = NULL;
446 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000447 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000448 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000449 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000451 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 return PyInt_FromLong((long)sts);
453 Py_INCREF(Py_None);
454 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455}
456
Trent Mickf29f47b2000-08-11 19:02:59 +0000457
Guido van Rossumb8552162001-09-05 14:58:11 +0000458/* Our very own off_t-like type, 64-bit if possible */
459#if !defined(HAVE_LARGEFILE_SUPPORT)
460typedef off_t Py_off_t;
461#elif SIZEOF_OFF_T >= 8
462typedef off_t Py_off_t;
463#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000464typedef fpos_t Py_off_t;
465#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000466#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000467#endif
468
469
Trent Mickf29f47b2000-08-11 19:02:59 +0000470/* a portable fseek() function
471 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000472static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000473_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000474{
Guido van Rossumb8552162001-09-05 14:58:11 +0000475#if !defined(HAVE_LARGEFILE_SUPPORT)
476 return fseek(fp, offset, whence);
477#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000478 return fseeko(fp, offset, whence);
479#elif defined(HAVE_FSEEK64)
480 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000481#elif defined(__BEOS__)
482 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000483#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000484 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
485 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000486 fpos_t pos;
487 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000488 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000489#ifdef MS_WINDOWS
490 fflush(fp);
491 if (_lseeki64(fileno(fp), 0, 2) == -1)
492 return -1;
493#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000494 if (fseek(fp, 0, SEEK_END) != 0)
495 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000496#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000497 /* fall through */
498 case SEEK_CUR:
499 if (fgetpos(fp, &pos) != 0)
500 return -1;
501 offset += pos;
502 break;
503 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000504 }
505 return fsetpos(fp, &offset);
506#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000507#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000508#endif
509}
510
511
512/* a portable ftell() function
513 Return -1 on failure with errno set appropriately, current file
514 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000515static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000516_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000517{
Guido van Rossumb8552162001-09-05 14:58:11 +0000518#if !defined(HAVE_LARGEFILE_SUPPORT)
519 return ftell(fp);
520#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
521 return ftello(fp);
522#elif defined(HAVE_FTELL64)
523 return ftell64(fp);
524#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000525 fpos_t pos;
526 if (fgetpos(fp, &pos) != 0)
527 return -1;
528 return pos;
529#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000530#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000531#endif
532}
533
534
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000536file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000538 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000539 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000540 Py_off_t offset;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000541 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000542
Guido van Rossumd7297e61992-07-06 14:19:26 +0000543 if (f->f_fp == NULL)
544 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000545 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000546 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000547 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000548 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000549 off_index = PyNumber_Index(offobj);
550 if (!off_index) {
551 if (!PyFloat_Check(offobj))
552 return NULL;
553 /* Deprecated in 2.6 */
554 PyErr_Clear();
555 if (PyErr_Warn(PyExc_DeprecationWarning,
556 "integer argument expected, got float"))
557 return NULL;
558 off_index = offobj;
559 Py_INCREF(offobj);
560 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000561#if !defined(HAVE_LARGEFILE_SUPPORT)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000562 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000563#else
Thomas Wouters89f507f2006-12-13 04:49:30 +0000564 offset = PyLong_Check(off_index) ?
565 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000566#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000567 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000568 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000569 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000570
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000572 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000573 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000575
Guido van Rossumff4949e1992-08-05 19:58:53 +0000576 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000578 clearerr(f->f_fp);
579 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000580 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000581 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582 Py_INCREF(Py_None);
583 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000584}
585
Trent Mickf29f47b2000-08-11 19:02:59 +0000586
Guido van Rossumd7047b31995-01-02 19:07:15 +0000587#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000589file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000590{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000591 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000592 PyObject *newsizeobj = NULL;
593 Py_off_t initialpos;
594 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000595
Guido van Rossumd7047b31995-01-02 19:07:15 +0000596 if (f->f_fp == NULL)
597 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000598 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000599 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000600
Tim Petersf1827cf2003-09-07 03:30:18 +0000601 /* Get current file position. If the file happens to be open for
602 * update and the last operation was an input operation, C doesn't
603 * define what the later fflush() will do, but we promise truncate()
604 * won't change the current position (and fflush() *does* change it
605 * then at least on Windows). The easiest thing is to capture
606 * current pos now and seek back to it at the end.
607 */
608 Py_BEGIN_ALLOW_THREADS
609 errno = 0;
610 initialpos = _portable_ftell(f->f_fp);
611 Py_END_ALLOW_THREADS
612 if (initialpos == -1)
613 goto onioerror;
614
Tim Petersfb05db22002-03-11 00:24:00 +0000615 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000616 * specified value.
617 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000618 if (newsizeobj != NULL) {
619#if !defined(HAVE_LARGEFILE_SUPPORT)
620 newsize = PyInt_AsLong(newsizeobj);
621#else
622 newsize = PyLong_Check(newsizeobj) ?
623 PyLong_AsLongLong(newsizeobj) :
624 PyInt_AsLong(newsizeobj);
625#endif
626 if (PyErr_Occurred())
627 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000628 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000629 else /* default to current position */
630 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000631
Tim Petersf1827cf2003-09-07 03:30:18 +0000632 /* Flush the stream. We're mixing stream-level I/O with lower-level
633 * I/O, and a flush may be necessary to synch both platform views
634 * of the current file state.
635 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000636 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000637 errno = 0;
638 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000640 if (ret != 0)
641 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000642
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000643#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000644 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000645 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000646 {
Tim Petersfb05db22002-03-11 00:24:00 +0000647 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000648
Tim Petersf1827cf2003-09-07 03:30:18 +0000649 /* Have to move current pos to desired endpoint on Windows. */
650 Py_BEGIN_ALLOW_THREADS
651 errno = 0;
652 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
653 Py_END_ALLOW_THREADS
654 if (ret)
655 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000656
Tim Peters8f01b682002-03-12 03:04:44 +0000657 /* Truncate. Note that this may grow the file! */
658 Py_BEGIN_ALLOW_THREADS
659 errno = 0;
660 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000661 ret = hFile == (HANDLE)-1;
662 if (ret == 0) {
663 ret = SetEndOfFile(hFile) == 0;
664 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000665 errno = EACCES;
666 }
667 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000668 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000669 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000670 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000671#else
672 Py_BEGIN_ALLOW_THREADS
673 errno = 0;
674 ret = ftruncate(fileno(f->f_fp), newsize);
675 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000676 if (ret != 0)
677 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000678#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000679
Tim Petersf1827cf2003-09-07 03:30:18 +0000680 /* Restore original file position. */
681 Py_BEGIN_ALLOW_THREADS
682 errno = 0;
683 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
684 Py_END_ALLOW_THREADS
685 if (ret)
686 goto onioerror;
687
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000688 Py_INCREF(Py_None);
689 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000690
691onioerror:
692 PyErr_SetFromErrno(PyExc_IOError);
693 clearerr(f->f_fp);
694 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000695}
696#endif /* HAVE_FTRUNCATE */
697
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000698static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000699file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000700{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000701 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000702
Guido van Rossumd7297e61992-07-06 14:19:26 +0000703 if (f->f_fp == NULL)
704 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000706 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000707 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000709 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000710 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000711 clearerr(f->f_fp);
712 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000713 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000714 if (f->f_skipnextlf) {
715 int c;
716 c = GETC(f->f_fp);
717 if (c == '\n') {
718 pos++;
719 f->f_skipnextlf = 0;
720 } else if (c != EOF) ungetc(c, f->f_fp);
721 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000722#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000723 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000724#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000725 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000726#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000727}
728
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000730file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000731{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000732 if (f->f_fp == NULL)
733 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000734 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000735}
736
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000738file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000739{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000740 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000741
Guido van Rossumd7297e61992-07-06 14:19:26 +0000742 if (f->f_fp == NULL)
743 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000745 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000746 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000747 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000748 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000749 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000750 clearerr(f->f_fp);
751 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000752 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000753 Py_INCREF(Py_None);
754 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000755}
756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000758file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000759{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000760 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000761 if (f->f_fp == NULL)
762 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000763 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000764 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000766 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000767}
768
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000769
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000770#if BUFSIZ < 8192
771#define SMALLCHUNK 8192
772#else
773#define SMALLCHUNK BUFSIZ
774#endif
775
Guido van Rossum3c259041999-01-14 19:00:14 +0000776#if SIZEOF_INT < 4
777#define BIGCHUNK (512 * 32)
778#else
779#define BIGCHUNK (512 * 1024)
780#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000781
782static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000783new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000784{
785#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000786 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000787 struct stat st;
788 if (fstat(fileno(f->f_fp), &st) == 0) {
789 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000790 /* The following is not a bug: we really need to call lseek()
791 *and* ftell(). The reason is that some stdio libraries
792 mistakenly flush their buffer when ftell() is called and
793 the lseek() call it makes fails, thereby throwing away
794 data that cannot be recovered in any way. To avoid this,
795 we first test lseek(), and only call ftell() if lseek()
796 works. We can't use the lseek() value either, because we
797 need to take the amount of buffered data into account.
798 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000799 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000800 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000801 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000802 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000803 if (pos < 0)
804 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000805 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000806 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000807 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000808 }
809#endif
810 if (currentsize > SMALLCHUNK) {
811 /* Keep doubling until we reach BIGCHUNK;
812 then keep adding BIGCHUNK. */
813 if (currentsize <= BIGCHUNK)
814 return currentsize + currentsize;
815 else
816 return currentsize + BIGCHUNK;
817 }
818 return currentsize + SMALLCHUNK;
819}
820
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000821#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
822#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
823#else
824#ifdef EWOULDBLOCK
825#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
826#else
827#ifdef EAGAIN
828#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
829#else
830#define BLOCKED_ERRNO(x) 0
831#endif
832#endif
833#endif
834
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000835static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000836file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000837{
Guido van Rossum789a1611997-05-10 22:33:55 +0000838 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000839 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000840 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000841
Guido van Rossumd7297e61992-07-06 14:19:26 +0000842 if (f->f_fp == NULL)
843 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000844 /* refuse to mix with f.next() */
845 if (f->f_buf != NULL &&
846 (f->f_bufend - f->f_bufptr) > 0 &&
847 f->f_buf[0] != '\0')
848 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000849 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000850 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000851 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000852 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000853 else
854 buffersize = bytesrequested;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000855 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000856 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000857 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000858 return NULL;
859 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000860 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000861 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000862 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000863 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000864 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000865 Py_BEGIN_ALLOW_THREADS
866 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000867 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000868 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000869 Py_END_ALLOW_THREADS
870 if (chunksize == 0) {
871 if (!ferror(f->f_fp))
872 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000873 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000874 /* When in non-blocking mode, data shouldn't
875 * be discarded if a blocking signal was
876 * received. That will also happen if
877 * chunksize != 0, but bytesread < buffersize. */
878 if (bytesread > 0 && BLOCKED_ERRNO(errno))
879 break;
880 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000881 Py_DECREF(v);
882 return NULL;
883 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000884 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000885 if (bytesread < buffersize) {
886 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000887 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000888 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000889 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000890 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000891 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000892 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000893 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000894 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000895 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000896 }
897 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000898 if (bytesread != buffersize)
899 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000900 return v;
901}
902
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000903static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000904file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000905{
906 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000907 Py_ssize_t ntodo;
908 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000909
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000910 if (f->f_fp == NULL)
911 return err_closed();
Guido van Rossumd624f182006-04-24 13:47:05 +0000912 if (!f->f_binary) {
913 PyErr_SetString(PyExc_TypeError,
914 "readinto() requires binary mode");
915 return NULL;
916 }
Thomas Woutersc45251a2006-02-12 11:53:32 +0000917 /* refuse to mix with f.next() */
918 if (f->f_buf != NULL &&
919 (f->f_bufend - f->f_bufptr) > 0 &&
920 f->f_buf[0] != '\0')
921 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000922 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000923 return NULL;
924 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000925 while (ntodo > 0) {
926 Py_BEGIN_ALLOW_THREADS
927 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000928 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000929 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000930 Py_END_ALLOW_THREADS
931 if (nnow == 0) {
932 if (!ferror(f->f_fp))
933 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000934 PyErr_SetFromErrno(PyExc_IOError);
935 clearerr(f->f_fp);
936 return NULL;
937 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000938 ndone += nnow;
939 ntodo -= nnow;
940 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000941 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000942}
943
Tim Peters86821b22001-01-07 21:19:34 +0000944/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000945Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000946
947Under MSVC 6:
948
Tim Peters1c733232001-01-08 04:02:07 +0000949+ MS threadsafe getc is very slow (multiple layers of function calls before+
950 after each character, to lock+unlock the stream).
951+ The stream-locking functions are MS-internal -- can't access them from user
952 code.
953+ There's nothing Tim could find in the MS C or platform SDK libraries that
954 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000955+ MS fgets locks/unlocks only once per line; it's the only hook we have.
956
957So we use fgets for speed(!), despite that it's painful.
958
959MS realloc is also slow.
960
Tim Petersf29b64d2001-01-15 06:33:19 +0000961Reports from other platforms on this method vs getc_unlocked (which MS doesn't
962have):
963 Linux a wash
964 Solaris a wash
965 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000966
Tim Petersf29b64d2001-01-15 06:33:19 +0000967CAUTION: The C std isn't clear about this: in those cases where fgets
968writes something into the buffer, can it write into any position beyond the
969required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
970known on which it does; and it would be a strange way to code fgets. Still,
971getline_via_fgets may not work correctly if it does. The std test
972test_bufio.py should fail if platform fgets() routinely writes beyond the
973trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000974**************************************************************************/
975
Tim Petersf29b64d2001-01-15 06:33:19 +0000976/* Use this routine if told to, or by default on non-get_unlocked()
977 * platforms unless told not to. Yikes! Let's spell that out:
978 * On a platform with getc_unlocked():
979 * By default, use getc_unlocked().
980 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
981 * On a platform without getc_unlocked():
982 * By default, use fgets().
983 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
984 */
985#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
986#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000987#endif
988
Tim Petersf29b64d2001-01-15 06:33:19 +0000989#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
990#undef USE_FGETS_IN_GETLINE
991#endif
992
993#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000994static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000995getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000996{
Tim Peters15b83852001-01-08 00:53:12 +0000997/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000998 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
999 * to fill this much of the buffer with a known value in order to figure out
1000 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1001 * than "most" lines, we waste time filling unused buffer slots. 100 is
1002 * surely adequate for most peoples' email archives, chewing over source code,
1003 * etc -- "regular old text files".
1004 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1005 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1006 * cautions about boosting that. 300 was chosen because the worst real-life
1007 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1008 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001009 */
Tim Peters142297a2001-01-15 10:36:56 +00001010#define INITBUFSIZE 100
1011#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001012 char* p; /* temp */
1013 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001014 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001015 char* pvfree; /* address of next free slot */
1016 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001017 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1018 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001019 size_t increment; /* amount to increment the buffer */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001020 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001021
Tim Peters15b83852001-01-08 00:53:12 +00001022 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001023 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001024 */
Tim Peters142297a2001-01-15 10:36:56 +00001025 total_v_size = INITBUFSIZE; /* start small and pray */
1026 pvfree = buf;
1027 for (;;) {
1028 Py_BEGIN_ALLOW_THREADS
1029 pvend = buf + total_v_size;
1030 nfree = pvend - pvfree;
1031 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001032 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1033 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +00001034 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001035
Tim Peters142297a2001-01-15 10:36:56 +00001036 if (p == NULL) {
1037 clearerr(fp);
1038 if (PyErr_CheckSignals())
1039 return NULL;
1040 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001041 return v;
1042 }
Tim Peters142297a2001-01-15 10:36:56 +00001043 /* fgets read *something* */
1044 p = memchr(pvfree, '\n', nfree);
1045 if (p != NULL) {
1046 /* Did the \n come from fgets or from us?
1047 * Since fgets stops at the first \n, and then writes
1048 * \0, if it's from fgets a \0 must be next. But if
1049 * that's so, it could not have come from us, since
1050 * the \n's we filled the buffer with have only more
1051 * \n's to the right.
1052 */
1053 if (p+1 < pvend && *(p+1) == '\0') {
1054 /* It's from fgets: we win! In particular,
1055 * we haven't done any mallocs yet, and can
1056 * build the final result on the first try.
1057 */
1058 ++p; /* include \n from fgets */
1059 }
1060 else {
1061 /* Must be from us: fgets didn't fill the
1062 * buffer and didn't find a newline, so it
1063 * must be the last and newline-free line of
1064 * the file.
1065 */
1066 assert(p > pvfree && *(p-1) == '\0');
1067 --p; /* don't include \0 from fgets */
1068 }
1069 v = PyString_FromStringAndSize(buf, p - buf);
1070 return v;
1071 }
1072 /* yuck: fgets overwrote all the newlines, i.e. the entire
1073 * buffer. So this line isn't over yet, or maybe it is but
1074 * we're exactly at EOF. If we haven't already, try using the
1075 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001076 */
Tim Peters142297a2001-01-15 10:36:56 +00001077 assert(*(pvend-1) == '\0');
1078 if (pvfree == buf) {
1079 pvfree = pvend - 1; /* overwrite trailing null */
1080 total_v_size = MAXBUFSIZE;
1081 }
1082 else
1083 break;
Tim Peters86821b22001-01-07 21:19:34 +00001084 }
Tim Peters142297a2001-01-15 10:36:56 +00001085
1086 /* The stack buffer isn't big enough; malloc a string object and read
1087 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001088 */
Tim Petersddea2082002-03-23 10:03:50 +00001089 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001090 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001091 if (v == NULL)
1092 return v;
1093 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001094 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1095 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001096
1097 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001098 * after setting p one beyond the end of the line. The code here is
1099 * very much like the code above, except reads into v's buffer; see
1100 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001101 */
1102 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001103 Py_BEGIN_ALLOW_THREADS
1104 pvend = BUF(v) + total_v_size;
1105 nfree = pvend - pvfree;
1106 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001107 assert(nfree < INT_MAX);
1108 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001109 Py_END_ALLOW_THREADS
1110
1111 if (p == NULL) {
1112 clearerr(fp);
1113 if (PyErr_CheckSignals()) {
1114 Py_DECREF(v);
1115 return NULL;
1116 }
1117 p = pvfree;
1118 break;
1119 }
Tim Peters86821b22001-01-07 21:19:34 +00001120 p = memchr(pvfree, '\n', nfree);
1121 if (p != NULL) {
1122 if (p+1 < pvend && *(p+1) == '\0') {
1123 /* \n came from fgets */
1124 ++p;
1125 break;
1126 }
1127 /* \n came from us; last line of file, no newline */
1128 assert(p > pvfree && *(p-1) == '\0');
1129 --p;
1130 break;
1131 }
1132 /* expand buffer and try again */
1133 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001134 increment = total_v_size >> 2; /* mild exponential growth */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001135 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001136 total_v_size += increment;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001137 /* check for overflow */
1138 if (total_v_size <= prev_v_size ||
1139 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001140 PyErr_SetString(PyExc_OverflowError,
1141 "line is longer than a Python string can hold");
1142 Py_DECREF(v);
1143 return NULL;
1144 }
1145 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1146 return NULL;
1147 /* overwrite the trailing null byte */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001148 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001149 }
1150 if (BUF(v) + total_v_size != p)
1151 _PyString_Resize(&v, p - BUF(v));
1152 return v;
1153#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001154#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001155}
Tim Petersf29b64d2001-01-15 06:33:19 +00001156#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001157
Guido van Rossum0bd24411991-04-04 15:21:57 +00001158/* Internal routine to get a line.
1159 Size argument interpretation:
1160 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001161 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001162*/
1163
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001164static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001165get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001166{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001167 FILE *fp = f->f_fp;
1168 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001169 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001170 size_t total_v_size; /* total # of slots in buffer */
1171 size_t used_v_size; /* # used slots in buffer */
1172 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001173 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001174 int newlinetypes = f->f_newlinetypes;
1175 int skipnextlf = f->f_skipnextlf;
1176 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001177
Jack Jansen7b8c7542002-04-14 20:12:41 +00001178#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001179 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001180 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001181#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001182 total_v_size = n > 0 ? n : 100;
1183 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001184 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001185 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001186 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001187 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001188
Guido van Rossumce5ba841991-03-06 13:06:18 +00001189 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001190 Py_BEGIN_ALLOW_THREADS
1191 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001192 if (univ_newline) {
1193 c = 'x'; /* Shut up gcc warning */
1194 while ( buf != end && (c = GETC(fp)) != EOF ) {
1195 if (skipnextlf ) {
1196 skipnextlf = 0;
1197 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001198 /* Seeing a \n here with
1199 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001200 * saw a \r before.
1201 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001202 newlinetypes |= NEWLINE_CRLF;
1203 c = GETC(fp);
1204 if (c == EOF) break;
1205 } else {
1206 newlinetypes |= NEWLINE_CR;
1207 }
1208 }
1209 if (c == '\r') {
1210 skipnextlf = 1;
1211 c = '\n';
1212 } else if ( c == '\n')
1213 newlinetypes |= NEWLINE_LF;
1214 *buf++ = c;
1215 if (c == '\n') break;
1216 }
1217 if ( c == EOF && skipnextlf )
1218 newlinetypes |= NEWLINE_CR;
1219 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001220 while ((c = GETC(fp)) != EOF &&
1221 (*buf++ = c) != '\n' &&
1222 buf != end)
1223 ;
1224 FUNLOCKFILE(fp);
1225 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001226 f->f_newlinetypes = newlinetypes;
1227 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001228 if (c == '\n')
1229 break;
1230 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001231 if (ferror(fp)) {
1232 PyErr_SetFromErrno(PyExc_IOError);
1233 clearerr(fp);
1234 Py_DECREF(v);
1235 return NULL;
1236 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001237 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001238 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001239 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001240 return NULL;
1241 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001242 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001243 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001244 /* Must be because buf == end */
1245 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001246 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001247 used_v_size = total_v_size;
1248 increment = total_v_size >> 2; /* mild exponential growth */
1249 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001250 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001251 PyErr_SetString(PyExc_OverflowError,
1252 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001253 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001254 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001255 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001256 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001257 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001258 buf = BUF(v) + used_v_size;
1259 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001260 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001261
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001262 used_v_size = buf - BUF(v);
1263 if (used_v_size != total_v_size)
1264 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001265 return v;
1266}
1267
Guido van Rossum0bd24411991-04-04 15:21:57 +00001268/* External C interface */
1269
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001270PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001271PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001272{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001273 PyObject *result;
1274
Guido van Rossum3165fe61992-09-25 21:59:05 +00001275 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001276 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001277 return NULL;
1278 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001279
1280 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001281 PyFileObject *fo = (PyFileObject *)f;
1282 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001283 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001284 /* refuse to mix with f.next() */
1285 if (fo->f_buf != NULL &&
1286 (fo->f_bufend - fo->f_bufptr) > 0 &&
1287 fo->f_buf[0] != '\0')
1288 return err_iterbuffered();
1289 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001290 }
1291 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001292 PyObject *reader;
1293 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001294
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001295 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001296 if (reader == NULL)
1297 return NULL;
1298 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001299 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001300 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001301 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001302 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001303 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001304 return NULL;
1305 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001306 result = PyEval_CallObject(reader, args);
1307 Py_DECREF(reader);
1308 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001309 if (result != NULL && !PyString_Check(result) &&
1310 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001311 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001312 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001314 "object.readline() returned non-string");
1315 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001316 }
1317
1318 if (n < 0 && result != NULL && PyString_Check(result)) {
1319 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001320 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001321 if (len == 0) {
1322 Py_DECREF(result);
1323 result = NULL;
1324 PyErr_SetString(PyExc_EOFError,
1325 "EOF when reading a line");
1326 }
1327 else if (s[len-1] == '\n') {
1328 if (result->ob_refcnt == 1)
1329 _PyString_Resize(&result, len-1);
1330 else {
1331 PyObject *v;
1332 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001333 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001334 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001335 }
1336 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001337 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001338 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1339 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001340 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001341 if (len == 0) {
1342 Py_DECREF(result);
1343 result = NULL;
1344 PyErr_SetString(PyExc_EOFError,
1345 "EOF when reading a line");
1346 }
1347 else if (s[len-1] == '\n') {
1348 if (result->ob_refcnt == 1)
1349 PyUnicode_Resize(&result, len-1);
1350 else {
1351 PyObject *v;
1352 v = PyUnicode_FromUnicode(s, len-1);
1353 Py_DECREF(result);
1354 result = v;
1355 }
1356 }
1357 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001358 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001359}
1360
1361/* Python method */
1362
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001363static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001364file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001365{
Guido van Rossum789a1611997-05-10 22:33:55 +00001366 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001367
Guido van Rossumd7297e61992-07-06 14:19:26 +00001368 if (f->f_fp == NULL)
1369 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001370 /* refuse to mix with f.next() */
1371 if (f->f_buf != NULL &&
1372 (f->f_bufend - f->f_bufptr) > 0 &&
1373 f->f_buf[0] != '\0')
1374 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001375 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001376 return NULL;
1377 if (n == 0)
1378 return PyString_FromString("");
1379 if (n < 0)
1380 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001381 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001382}
1383
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001384static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001385file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001386{
Guido van Rossum789a1611997-05-10 22:33:55 +00001387 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388 PyObject *list;
1389 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001390 char small_buffer[SMALLCHUNK];
1391 char *buffer = small_buffer;
1392 size_t buffersize = SMALLCHUNK;
1393 PyObject *big_buffer = NULL;
1394 size_t nfilled = 0;
1395 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001396 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001397 char *p, *q, *end;
1398 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001399 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001400
Guido van Rossumd7297e61992-07-06 14:19:26 +00001401 if (f->f_fp == NULL)
1402 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001403 /* refuse to mix with f.next() */
1404 if (f->f_buf != NULL &&
1405 (f->f_bufend - f->f_bufptr) > 0 &&
1406 f->f_buf[0] != '\0')
1407 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001408 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001409 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001410 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001411 return NULL;
1412 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001413 if (shortread)
1414 nread = 0;
1415 else {
1416 Py_BEGIN_ALLOW_THREADS
1417 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001418 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001419 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001420 Py_END_ALLOW_THREADS
1421 shortread = (nread < buffersize-nfilled);
1422 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001423 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001424 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001425 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001426 break;
1427 PyErr_SetFromErrno(PyExc_IOError);
1428 clearerr(f->f_fp);
1429 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001430 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001431 list = NULL;
1432 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001433 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001434 totalread += nread;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001435 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001436 if (p == NULL) {
1437 /* Need a larger buffer to fit this line */
1438 nfilled += nread;
1439 buffersize *= 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001440 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001441 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001442 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001443 goto error;
1444 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001445 if (big_buffer == NULL) {
1446 /* Create the big buffer */
1447 big_buffer = PyString_FromStringAndSize(
1448 NULL, buffersize);
1449 if (big_buffer == NULL)
1450 goto error;
1451 buffer = PyString_AS_STRING(big_buffer);
1452 memcpy(buffer, small_buffer, nfilled);
1453 }
1454 else {
1455 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001456 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1457 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001458 buffer = PyString_AS_STRING(big_buffer);
1459 }
1460 continue;
1461 }
1462 end = buffer+nfilled+nread;
1463 q = buffer;
1464 do {
1465 /* Process complete lines */
1466 p++;
1467 line = PyString_FromStringAndSize(q, p-q);
1468 if (line == NULL)
1469 goto error;
1470 err = PyList_Append(list, line);
1471 Py_DECREF(line);
1472 if (err != 0)
1473 goto error;
1474 q = p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001475 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001476 } while (p != NULL);
1477 /* Move the remaining incomplete line to the start */
1478 nfilled = end-q;
1479 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001480 if (sizehint > 0)
1481 if (totalread >= (size_t)sizehint)
1482 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001483 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001484 if (nfilled != 0) {
1485 /* Partial last line */
1486 line = PyString_FromStringAndSize(buffer, nfilled);
1487 if (line == NULL)
1488 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001489 if (sizehint > 0) {
1490 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001491 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001492 if (rest == NULL) {
1493 Py_DECREF(line);
1494 goto error;
1495 }
1496 PyString_Concat(&line, rest);
1497 Py_DECREF(rest);
1498 if (line == NULL)
1499 goto error;
1500 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001501 err = PyList_Append(list, line);
1502 Py_DECREF(line);
1503 if (err != 0)
1504 goto error;
1505 }
1506 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001507 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001508 return list;
1509}
1510
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001511static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001512file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001513{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001514 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001515 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001516 if (f->f_fp == NULL)
1517 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001518 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001519 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001520 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001521 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001522 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001523 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001524 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001525 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001526 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001527 return NULL;
1528 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001529 Py_INCREF(Py_None);
1530 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001531}
1532
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001533static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001534file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001535{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001536#define CHUNKSIZE 1000
1537 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001538 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001540 int index, islist;
1541 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001542
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001543 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001544 if (f->f_fp == NULL)
1545 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001546
1547 result = NULL;
1548 list = NULL;
1549 islist = PyList_Check(seq);
1550 if (islist)
1551 it = NULL;
1552 else {
1553 it = PyObject_GetIter(seq);
1554 if (it == NULL) {
1555 PyErr_SetString(PyExc_TypeError,
1556 "writelines() requires an iterable argument");
1557 return NULL;
1558 }
1559 /* From here on, fail by going to error, to reclaim "it". */
1560 list = PyList_New(CHUNKSIZE);
1561 if (list == NULL)
1562 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001563 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001564
1565 /* Strategy: slurp CHUNKSIZE lines into a private list,
1566 checking that they are all strings, then write that list
1567 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001568 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001569 if (islist) {
1570 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001571 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001572 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001573 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001574 j = PyList_GET_SIZE(list);
1575 }
1576 else {
1577 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001578 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001579 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001580 if (PyErr_Occurred())
1581 goto error;
1582 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001583 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001584 PyList_SetItem(list, j, line);
1585 }
1586 }
1587 if (j == 0)
1588 break;
1589
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001590 /* Check that all entries are indeed strings. If not,
1591 apply the same rules as for file.write() and
1592 convert the results to strings. This is slow, but
1593 seems to be the only way since all conversion APIs
1594 could potentially execute Python code. */
1595 for (i = 0; i < j; i++) {
1596 PyObject *v = PyList_GET_ITEM(list, i);
1597 if (!PyString_Check(v)) {
1598 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001599 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001600 PyObject_AsReadBuffer(v,
1601 (const void**)&buffer,
1602 &len)) ||
1603 PyObject_AsCharBuffer(v,
1604 &buffer,
1605 &len))) {
1606 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001607 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001608 goto error;
1609 }
1610 line = PyString_FromStringAndSize(buffer,
1611 len);
1612 if (line == NULL)
1613 goto error;
1614 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001615 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001616 }
1617 }
1618
1619 /* Since we are releasing the global lock, the
1620 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001621 Py_BEGIN_ALLOW_THREADS
Guido van Rossumee70ad12000-03-13 16:27:06 +00001622 errno = 0;
1623 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001624 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001625 len = PyString_GET_SIZE(line);
1626 nwritten = fwrite(PyString_AS_STRING(line),
1627 1, len, f->f_fp);
1628 if (nwritten != len) {
1629 Py_BLOCK_THREADS
1630 PyErr_SetFromErrno(PyExc_IOError);
1631 clearerr(f->f_fp);
1632 goto error;
1633 }
1634 }
1635 Py_END_ALLOW_THREADS
1636
1637 if (j < CHUNKSIZE)
1638 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001639 }
1640
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001641 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001642 result = Py_None;
1643 error:
1644 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001645 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001646 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001647#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001648}
1649
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001650static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001651file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001652{
1653 if (f->f_fp == NULL)
1654 return err_closed();
1655 Py_INCREF(f);
1656 return (PyObject *)f;
1657}
1658
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001659static PyObject *
1660file_exit(PyFileObject *f, PyObject *args)
1661{
1662 PyObject *ret = file_close(f);
1663 if (!ret)
1664 /* If error occurred, pass through */
1665 return NULL;
1666 Py_DECREF(ret);
1667 /* We cannot return the result of close since a true
1668 * value will be interpreted as "yes, swallow the
1669 * exception if one was raised inside the with block". */
1670 Py_RETURN_NONE;
1671}
1672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001673PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001674"readline([size]) -> next line from the file, as a string.\n"
1675"\n"
1676"Retain newline. A non-negative size argument limits the maximum\n"
1677"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001678"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001679
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001680PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001681"read([size]) -> read at most size bytes, returned as a string.\n"
1682"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001683"If the size argument is negative or omitted, read until EOF is reached.\n"
1684"Notice that when in non-blocking mode, less data than what was requested\n"
1685"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001687PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001688"write(str) -> None. Write string str to file.\n"
1689"\n"
1690"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001691"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001693PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001694"fileno() -> integer \"file descriptor\".\n"
1695"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001696"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001698PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001699"seek(offset[, whence]) -> None. Move to new file position.\n"
1700"\n"
1701"Argument offset is a byte count. Optional argument whence defaults to\n"
1702"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1703"(move relative to current position, positive or negative), and 2 (move\n"
1704"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001705"seeking beyond the end of a file). If the file is opened in text mode,\n"
1706"only offsets returned by tell() are legal. Use of other offsets causes\n"
1707"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001708"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001709"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001710
Guido van Rossumd7047b31995-01-02 19:07:15 +00001711#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001712PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001713"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1714"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001715"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001716#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001718PyDoc_STRVAR(tell_doc,
1719"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001720
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001721PyDoc_STRVAR(readinto_doc,
1722"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001724PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001725"readlines([size]) -> list of strings, each a line from the file.\n"
1726"\n"
1727"Call readline() repeatedly and return a list of the lines so read.\n"
1728"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001729"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001731PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001732"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001733"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001734"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001737PyDoc_STRVAR(flush_doc,
1738"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001740PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001741"close() -> None or (perhaps) an integer. Close the file.\n"
1742"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001743"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001744"further I/O operations. close() may be called more than once without\n"
1745"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001746"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001747
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001748PyDoc_STRVAR(isatty_doc,
1749"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001750
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001751PyDoc_STRVAR(enter_doc,
1752 "__enter__() -> self.");
1753
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001754PyDoc_STRVAR(exit_doc,
1755 "__exit__(*excinfo) -> None. Closes the file.");
1756
Tim Petersefc3a3a2001-09-20 07:55:22 +00001757static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001758 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1759 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1760 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1761 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1762 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001763#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001764 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001765#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001766 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1767 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1768 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001769 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1770 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1771 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1772 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001773 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001774 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001775 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001776};
1777
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001778#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001779
Guido van Rossum6f799372001-09-20 20:46:19 +00001780static PyMemberDef file_memberlist[] = {
Guido van Rossum6f799372001-09-20 20:46:19 +00001781 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001782 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001783 {"name", T_OBJECT, OFF(f_name), RO,
1784 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001785 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1786 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001787 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001788 {NULL} /* Sentinel */
1789};
1790
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001791static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001793{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001794 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001795}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001796static PyObject *
1797get_newlines(PyFileObject *f, void *closure)
1798{
1799 switch (f->f_newlinetypes) {
1800 case NEWLINE_UNKNOWN:
1801 Py_INCREF(Py_None);
1802 return Py_None;
1803 case NEWLINE_CR:
1804 return PyString_FromString("\r");
1805 case NEWLINE_LF:
1806 return PyString_FromString("\n");
1807 case NEWLINE_CR|NEWLINE_LF:
1808 return Py_BuildValue("(ss)", "\r", "\n");
1809 case NEWLINE_CRLF:
1810 return PyString_FromString("\r\n");
1811 case NEWLINE_CR|NEWLINE_CRLF:
1812 return Py_BuildValue("(ss)", "\r", "\r\n");
1813 case NEWLINE_LF|NEWLINE_CRLF:
1814 return Py_BuildValue("(ss)", "\n", "\r\n");
1815 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1816 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1817 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001818 PyErr_Format(PyExc_SystemError,
1819 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001820 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001821 return NULL;
1822 }
1823}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001824
Guido van Rossum32d34c82001-09-20 21:45:26 +00001825static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001826 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001827 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001828 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 {0},
1830};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001831
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001832static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001833drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001834{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001835 if (f->f_buf != NULL) {
1836 PyMem_Free(f->f_buf);
1837 f->f_buf = NULL;
1838 }
Guido van Rossum65967252001-04-21 13:20:18 +00001839}
1840
Tim Petersf1827cf2003-09-07 03:30:18 +00001841/* Make sure that file has a readahead buffer with at least one byte
1842 (unless at EOF) and no more than bufsize. Returns negative value on
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001843 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001844static int
1845readahead(PyFileObject *f, int bufsize)
1846{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001847 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001848
1849 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001850 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001851 return 0;
1852 else
1853 drop_readahead(f);
1854 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001855 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
1856 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001857 return -1;
1858 }
1859 Py_BEGIN_ALLOW_THREADS
1860 errno = 0;
1861 chunksize = Py_UniversalNewlineFread(
1862 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1863 Py_END_ALLOW_THREADS
1864 if (chunksize == 0) {
1865 if (ferror(f->f_fp)) {
1866 PyErr_SetFromErrno(PyExc_IOError);
1867 clearerr(f->f_fp);
1868 drop_readahead(f);
1869 return -1;
1870 }
1871 }
1872 f->f_bufptr = f->f_buf;
1873 f->f_bufend = f->f_buf + chunksize;
1874 return 0;
1875}
1876
1877/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001878 uninitialized bytes followed by the remainder of the line. Don't be
1879 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001880 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1881
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001882static PyStringObject *
1883readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1884{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001885 PyStringObject* s;
1886 char *bufptr;
1887 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001888 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001889
1890 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001891 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001892 return NULL;
1893
1894 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001895 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001896 return (PyStringObject *)
1897 PyString_FromStringAndSize(NULL, skip);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001898 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001899 if (bufptr != NULL) {
1900 bufptr++; /* Count the '\n' */
1901 len = bufptr - f->f_bufptr;
1902 s = (PyStringObject *)
1903 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001904 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001905 return NULL;
1906 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1907 f->f_bufptr = bufptr;
1908 if (bufptr == f->f_bufend)
1909 drop_readahead(f);
1910 } else {
1911 bufptr = f->f_bufptr;
1912 buf = f->f_buf;
1913 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001914 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001915 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001916 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001917 if (s == NULL) {
1918 PyMem_Free(buf);
1919 return NULL;
1920 }
1921 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1922 PyMem_Free(buf);
1923 }
1924 return s;
1925}
1926
1927/* A larger buffer size may actually decrease performance. */
1928#define READAHEAD_BUFSIZE 8192
1929
1930static PyObject *
1931file_iternext(PyFileObject *f)
1932{
1933 PyStringObject* l;
1934
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001935 if (f->f_fp == NULL)
1936 return err_closed();
1937
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001938 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1939 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1940 Py_XDECREF(l);
1941 return NULL;
1942 }
1943 return (PyObject *)l;
1944}
1945
1946
Tim Peters59c9a642001-09-13 05:38:56 +00001947static PyObject *
1948file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1949{
Tim Peters44410012001-09-14 03:26:08 +00001950 PyObject *self;
1951 static PyObject *not_yet_string;
1952
1953 assert(type != NULL && type->tp_alloc != NULL);
1954
1955 if (not_yet_string == NULL) {
1956 not_yet_string = PyString_FromString("<uninitialized file>");
1957 if (not_yet_string == NULL)
1958 return NULL;
1959 }
1960
1961 self = type->tp_alloc(type, 0);
1962 if (self != NULL) {
1963 /* Always fill in the name and mode, so that nobody else
1964 needs to special-case NULLs there. */
1965 Py_INCREF(not_yet_string);
1966 ((PyFileObject *)self)->f_name = not_yet_string;
1967 Py_INCREF(not_yet_string);
1968 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001969 Py_INCREF(Py_None);
1970 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001971 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001972 }
1973 return self;
1974}
1975
1976static int
1977file_init(PyObject *self, PyObject *args, PyObject *kwds)
1978{
1979 PyFileObject *foself = (PyFileObject *)self;
1980 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001981 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001982 char *name = NULL;
1983 char *mode = "r";
1984 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001985 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001986
1987 assert(PyFile_Check(self));
1988 if (foself->f_fp != NULL) {
1989 /* Have to close the existing file first. */
1990 PyObject *closeresult = file_close(foself);
1991 if (closeresult == NULL)
1992 return -1;
1993 Py_DECREF(closeresult);
1994 }
Tim Peters59c9a642001-09-13 05:38:56 +00001995
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001996#ifdef Py_WIN_WIDE_FILENAMES
1997 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1998 PyObject *po;
1999 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2000 kwlist, &po, &mode, &bufsize)) {
2001 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002002 if (fill_file_fields(foself, NULL, po, mode,
2003 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002004 goto Error;
2005 } else {
2006 /* Drop the argument parsing error as narrow
2007 strings are also valid. */
2008 PyErr_Clear();
2009 }
2010 }
2011#endif
2012
2013 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002014 PyObject *o_name;
2015
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002016 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2017 Py_FileSystemDefaultEncoding,
2018 &name,
2019 &mode, &bufsize))
2020 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002021
2022 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002023 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2024 kwlist, &o_name, &mode,
2025 &bufsize))
Thomas Wouters89f507f2006-12-13 04:49:30 +00002026 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002027
2028 if (fill_file_fields(foself, NULL, o_name, mode,
2029 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002030 goto Error;
2031 }
Tim Peters44410012001-09-14 03:26:08 +00002032 if (open_the_file(foself, name, mode) == NULL)
2033 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002034 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002035 PyFile_SetBufSize(self, bufsize);
2036 goto Done;
2037
2038Error:
2039 ret = -1;
2040 /* fall through */
2041Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002042 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002043 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002044}
2045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002046PyDoc_VAR(file_doc) =
2047PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002048"file(name[, mode[, buffering]]) -> file object\n"
2049"\n"
2050"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2051"writing or appending. The file will be created if it doesn't exist\n"
2052"when opened for writing or appending; it will be truncated when\n"
2053"opened for writing. Add a 'b' to the mode for binary files.\n"
2054"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2055"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002056"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002057)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002058PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002059"Add a 'U' to mode to open the file for input with universal newline\n"
2060"support. Any line ending in the input file will be seen as a '\\n'\n"
2061"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2062"the value for this attribute is one of None (no newline read yet),\n"
2063"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2064"\n"
2065"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002066);
Tim Peters59c9a642001-09-13 05:38:56 +00002067
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068PyTypeObject PyFile_Type = {
2069 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002070 0,
2071 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002072 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002073 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002074 (destructor)file_dealloc, /* tp_dealloc */
2075 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002076 0, /* tp_getattr */
2077 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002078 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002080 0, /* tp_as_number */
2081 0, /* tp_as_sequence */
2082 0, /* tp_as_mapping */
2083 0, /* tp_hash */
2084 0, /* tp_call */
2085 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum79139b22007-02-09 23:20:19 +00002087 0, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002088 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002089 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002090 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091 0, /* tp_traverse */
2092 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002093 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002094 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002095 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002096 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 file_methods, /* tp_methods */
2098 file_memberlist, /* tp_members */
2099 file_getsetlist, /* tp_getset */
2100 0, /* tp_base */
2101 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002102 0, /* tp_descr_get */
2103 0, /* tp_descr_set */
2104 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002105 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002106 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002107 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002108 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002109};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002110
Guido van Rossum3165fe61992-09-25 21:59:05 +00002111/* Interfaces to write objects/strings to file-like objects */
2112
2113int
Fred Drakefd99de62000-07-09 05:02:18 +00002114PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002115{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002116 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002117 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002119 return -1;
2120 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002121 else if (PyFile_Check(f)) {
2122 FILE *fp = PyFile_AsFile(f);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002123 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2124 int result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002125 if (fp == NULL) {
2126 err_closed();
2127 return -1;
2128 }
Tim Petersf1827cf2003-09-07 03:30:18 +00002129 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002130 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002131 char *cenc = PyString_AS_STRING(enc);
2132 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2133 if (value == NULL)
2134 return -1;
2135 } else {
2136 value = v;
2137 Py_INCREF(value);
2138 }
2139 result = PyObject_Print(value, fp, flags);
2140 Py_DECREF(value);
2141 return result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002142 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002143 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002144 if (writer == NULL)
2145 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002146 if (flags & Py_PRINT_RAW) {
2147 if (PyUnicode_Check(v)) {
2148 value = v;
2149 Py_INCREF(value);
2150 } else
2151 value = PyObject_Str(v);
2152 }
2153 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002154 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002155 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002156 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002157 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002158 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002159 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002160 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 Py_DECREF(value);
2162 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002163 return -1;
2164 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002165 result = PyEval_CallObject(writer, args);
2166 Py_DECREF(args);
2167 Py_DECREF(value);
2168 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002169 if (result == NULL)
2170 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002171 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002172 return 0;
2173}
2174
Guido van Rossum27a60b11997-05-22 22:25:11 +00002175int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002176PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002177{
2178 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002179 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002180 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002181 PyErr_SetString(PyExc_SystemError,
2182 "null file for PyFile_WriteString");
2183 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002184 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002185 else if (PyFile_Check(f)) {
2186 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002187 if (fp == NULL) {
2188 err_closed();
2189 return -1;
2190 }
2191 fputs(s, fp);
2192 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002193 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002194 else if (!PyErr_Occurred()) {
2195 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002196 int err;
2197 if (v == NULL)
2198 return -1;
2199 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2200 Py_DECREF(v);
2201 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002202 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002203 else
2204 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002205}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002206
2207/* Try to get a file-descriptor from a Python object. If the object
2208 is an integer or long integer, its value is returned. If not, the
2209 object's fileno() method is called if it exists; the method must return
2210 an integer or long integer, which is returned as the file descriptor value.
2211 -1 is returned on failure.
2212*/
2213
2214int PyObject_AsFileDescriptor(PyObject *o)
2215{
2216 int fd;
2217 PyObject *meth;
2218
2219 if (PyInt_Check(o)) {
2220 fd = PyInt_AsLong(o);
2221 }
2222 else if (PyLong_Check(o)) {
2223 fd = PyLong_AsLong(o);
2224 }
2225 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2226 {
2227 PyObject *fno = PyEval_CallObject(meth, NULL);
2228 Py_DECREF(meth);
2229 if (fno == NULL)
2230 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002231
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002232 if (PyInt_Check(fno)) {
2233 fd = PyInt_AsLong(fno);
2234 Py_DECREF(fno);
2235 }
2236 else if (PyLong_Check(fno)) {
2237 fd = PyLong_AsLong(fno);
2238 Py_DECREF(fno);
2239 }
2240 else {
2241 PyErr_SetString(PyExc_TypeError,
2242 "fileno() returned a non-integer");
2243 Py_DECREF(fno);
2244 return -1;
2245 }
2246 }
2247 else {
2248 PyErr_SetString(PyExc_TypeError,
2249 "argument must be an int, or have a fileno() method.");
2250 return -1;
2251 }
2252
Guido van Rossumddefaf32007-01-14 03:31:43 +00002253 if (fd == -1 && PyErr_Occurred())
2254 return -1;
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002255 if (fd < 0) {
2256 PyErr_Format(PyExc_ValueError,
2257 "file descriptor cannot be a negative integer (%i)",
2258 fd);
2259 return -1;
2260 }
2261 return fd;
2262}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002263
Jack Jansen7b8c7542002-04-14 20:12:41 +00002264/* From here on we need access to the real fgets and fread */
2265#undef fgets
2266#undef fread
2267
2268/*
2269** Py_UniversalNewlineFgets is an fgets variation that understands
2270** all of \r, \n and \r\n conventions.
2271** The stream should be opened in binary mode.
2272** If fobj is NULL the routine always does newline conversion, and
2273** it may peek one char ahead to gobble the second char in \r\n.
2274** If fobj is non-NULL it must be a PyFileObject. In this case there
2275** is no readahead but in stead a flag is used to skip a following
2276** \n on the next read. Also, if the file is open in binary mode
2277** the whole conversion is skipped. Finally, the routine keeps track of
2278** the different types of newlines seen.
2279** Note that we need no error handling: fgets() treats error and eof
2280** identically.
2281*/
2282char *
2283Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2284{
2285 char *p = buf;
2286 int c;
2287 int newlinetypes = 0;
2288 int skipnextlf = 0;
2289 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002290
Jack Jansen7b8c7542002-04-14 20:12:41 +00002291 if (fobj) {
2292 if (!PyFile_Check(fobj)) {
2293 errno = ENXIO; /* What can you do... */
2294 return NULL;
2295 }
2296 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2297 if ( !univ_newline )
2298 return fgets(buf, n, stream);
2299 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2300 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2301 }
2302 FLOCKFILE(stream);
2303 c = 'x'; /* Shut up gcc warning */
2304 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2305 if (skipnextlf ) {
2306 skipnextlf = 0;
2307 if (c == '\n') {
2308 /* Seeing a \n here with skipnextlf true
2309 ** means we saw a \r before.
2310 */
2311 newlinetypes |= NEWLINE_CRLF;
2312 c = GETC(stream);
2313 if (c == EOF) break;
2314 } else {
2315 /*
2316 ** Note that c == EOF also brings us here,
2317 ** so we're okay if the last char in the file
2318 ** is a CR.
2319 */
2320 newlinetypes |= NEWLINE_CR;
2321 }
2322 }
2323 if (c == '\r') {
2324 /* A \r is translated into a \n, and we skip
2325 ** an adjacent \n, if any. We don't set the
2326 ** newlinetypes flag until we've seen the next char.
2327 */
2328 skipnextlf = 1;
2329 c = '\n';
2330 } else if ( c == '\n') {
2331 newlinetypes |= NEWLINE_LF;
2332 }
2333 *p++ = c;
2334 if (c == '\n') break;
2335 }
2336 if ( c == EOF && skipnextlf )
2337 newlinetypes |= NEWLINE_CR;
2338 FUNLOCKFILE(stream);
2339 *p = '\0';
2340 if (fobj) {
2341 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2342 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2343 } else if ( skipnextlf ) {
2344 /* If we have no file object we cannot save the
2345 ** skipnextlf flag. We have to readahead, which
2346 ** will cause a pause if we're reading from an
2347 ** interactive stream, but that is very unlikely
2348 ** unless we're doing something silly like
2349 ** execfile("/dev/tty").
2350 */
2351 c = GETC(stream);
2352 if ( c != '\n' )
2353 ungetc(c, stream);
2354 }
2355 if (p == buf)
2356 return NULL;
2357 return buf;
2358}
2359
2360/*
2361** Py_UniversalNewlineFread is an fread variation that understands
2362** all of \r, \n and \r\n conventions.
2363** The stream should be opened in binary mode.
2364** fobj must be a PyFileObject. In this case there
2365** is no readahead but in stead a flag is used to skip a following
2366** \n on the next read. Also, if the file is open in binary mode
2367** the whole conversion is skipped. Finally, the routine keeps track of
2368** the different types of newlines seen.
2369*/
2370size_t
Tim Peters058b1412002-04-21 07:29:14 +00002371Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002372 FILE *stream, PyObject *fobj)
2373{
Tim Peters058b1412002-04-21 07:29:14 +00002374 char *dst = buf;
2375 PyFileObject *f = (PyFileObject *)fobj;
2376 int newlinetypes, skipnextlf;
2377
2378 assert(buf != NULL);
2379 assert(stream != NULL);
2380
Jack Jansen7b8c7542002-04-14 20:12:41 +00002381 if (!fobj || !PyFile_Check(fobj)) {
2382 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002383 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002384 }
Tim Peters058b1412002-04-21 07:29:14 +00002385 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002386 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002387 newlinetypes = f->f_newlinetypes;
2388 skipnextlf = f->f_skipnextlf;
2389 /* Invariant: n is the number of bytes remaining to be filled
2390 * in the buffer.
2391 */
2392 while (n) {
2393 size_t nread;
2394 int shortread;
2395 char *src = dst;
2396
2397 nread = fread(dst, 1, n, stream);
2398 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002399 if (nread == 0)
2400 break;
2401
Tim Peterse1682a82002-04-21 18:15:20 +00002402 n -= nread; /* assuming 1 byte out for each in; will adjust */
2403 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002404 while (nread--) {
2405 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002406 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002407 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002408 *dst++ = '\n';
2409 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002410 }
2411 else if (skipnextlf && c == '\n') {
2412 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002413 skipnextlf = 0;
2414 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002415 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002416 }
2417 else {
2418 /* Normal char to be stored in buffer. Also
2419 * update the newlinetypes flag if either this
2420 * is an LF or the previous char was a CR.
2421 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002422 if (c == '\n')
2423 newlinetypes |= NEWLINE_LF;
2424 else if (skipnextlf)
2425 newlinetypes |= NEWLINE_CR;
2426 *dst++ = c;
2427 skipnextlf = 0;
2428 }
2429 }
Tim Peters058b1412002-04-21 07:29:14 +00002430 if (shortread) {
2431 /* If this is EOF, update type flags. */
2432 if (skipnextlf && feof(stream))
2433 newlinetypes |= NEWLINE_CR;
2434 break;
2435 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002436 }
Tim Peters058b1412002-04-21 07:29:14 +00002437 f->f_newlinetypes = newlinetypes;
2438 f->f_skipnextlf = skipnextlf;
2439 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002440}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002441
2442#ifdef __cplusplus
2443}
2444#endif