blob: fb8a542d44296900d6449b9642f237f43b592732 [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;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000121 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000122 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000123 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000124 f->f_univ_newline = (strchr(mode, 'U') != NULL);
125 f->f_newlinetypes = NEWLINE_UNKNOWN;
126 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000127 Py_INCREF(Py_None);
128 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000129
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000133 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135}
136
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000137/* check for known incorrect mode strings - problem is, platforms are
138 free to accept any mode characters they like and are supposed to
139 ignore stuff they don't understand... write or append mode with
Thomas Wouters477c8d52006-05-27 19:21:47 +0000140 universal newline support is expressly forbidden by PEP 278.
141 Additionally, remove the 'U' from the mode string as platforms
142 won't know what it is. */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000143/* zero return is kewl - one is un-kewl */
144static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145sanitize_the_mode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000146{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000147 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000148 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000149
Thomas Wouters477c8d52006-05-27 19:21:47 +0000150 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000151 PyErr_SetString(PyExc_ValueError, "empty mode string");
152 return 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000153 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000154
Thomas Wouters477c8d52006-05-27 19:21:47 +0000155 upos = strchr(mode, 'U');
156 if (upos) {
157 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000158
Thomas Wouters477c8d52006-05-27 19:21:47 +0000159 if (mode[0] == 'w' || mode[0] == 'a') {
160 PyErr_Format(PyExc_ValueError, "universal newline "
161 "mode can only be used with modes "
162 "starting with 'r'");
163 return 1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000164 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000165
166 if (mode[0] != 'r') {
167 memmove(mode+1, mode, strlen(mode)+1);
168 mode[0] = 'r';
169 }
170
171 if (!strchr(mode, 'b')) {
172 memmove(mode+2, mode+1, strlen(mode));
173 mode[1] = 'b';
174 }
175 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
176 PyErr_Format(PyExc_ValueError, "mode string must begin with "
177 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
178 return 1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000179 }
180
181 return 0;
182}
183
Tim Peters59c9a642001-09-13 05:38:56 +0000184static PyObject *
185open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000187 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000188 assert(f != NULL);
189 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000190#ifdef MS_WINDOWS
191 /* windows ignores the passed name in order to support Unicode */
192 assert(f->f_name != NULL);
193#else
Tim Peters59c9a642001-09-13 05:38:56 +0000194 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000195#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000196 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000197 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000198
Thomas Wouters477c8d52006-05-27 19:21:47 +0000199 /* probably need to replace 'U' by 'rb' */
200 newmode = PyMem_MALLOC(strlen(mode) + 3);
201 if (!newmode) {
202 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000203 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000204 }
205 strcpy(newmode, mode);
206
207 if (sanitize_the_mode(newmode)) {
208 f = NULL;
209 goto cleanup;
210 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000211
Tim Peters8fa45672001-09-13 21:01:29 +0000212 /* rexec.py can't stop a user from getting the file() constructor --
213 all they have to do is get *any* file object f, and then do
214 type(f). Here we prevent them from doing damage with it. */
215 if (PyEval_GetRestricted()) {
216 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000217 "file() constructor not accessible in restricted mode");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000218 f = NULL;
219 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000220 }
Tim Petersa27a1502001-11-09 20:59:14 +0000221 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000222
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000223#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000224 if (PyUnicode_Check(f->f_name)) {
225 PyObject *wmode;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000226 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000227 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000228 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000229 /* PyUnicode_AS_UNICODE OK without thread
230 lock as it is a simple dereference. */
231 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
232 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000233 Py_END_ALLOW_THREADS
234 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000235 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000236 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000237#endif
238 if (NULL == f->f_fp && NULL != name) {
239 Py_BEGIN_ALLOW_THREADS
Thomas Wouters477c8d52006-05-27 19:21:47 +0000240 f->f_fp = fopen(name, newmode);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000241 Py_END_ALLOW_THREADS
242 }
243
Guido van Rossuma08095a1991-02-13 23:25:27 +0000244 if (f->f_fp == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000245#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000246 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
247 * across all Windows flavors. When it sets EINVAL varies
248 * across Windows flavors, the exact conditions aren't
249 * documented, and the answer lies in the OS's implementation
250 * of Win32's CreateFile function (whose source is secret).
251 * Seems the best we can do is map EINVAL to ENOENT.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252 * Starting with Visual Studio .NET 2005, EINVAL is correctly
253 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000254 */
255 if (errno == 0) /* bad mode string */
256 errno = EINVAL;
257 else if (errno == EINVAL) /* unknown, but not a mode string */
258 errno = ENOENT;
259#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000260 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000261 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000262 mode);
263 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000264 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000265 f = NULL;
266 }
Tim Peters2ea91112002-04-08 04:13:12 +0000267 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000268 f = dircheck(f);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000269
270cleanup:
271 PyMem_FREE(newmode);
272
Tim Peters59c9a642001-09-13 05:38:56 +0000273 return (PyObject *)f;
274}
275
276PyObject *
277PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
278{
Tim Peters44410012001-09-14 03:26:08 +0000279 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
280 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000281 if (f != NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000282 PyObject *o_name = PyString_FromString(name);
283 if (o_name == NULL)
284 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000285 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000286 Py_DECREF(f);
287 f = NULL;
288 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000289 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000290 }
291 return (PyObject *) f;
292}
293
294PyObject *
295PyFile_FromString(char *name, char *mode)
296{
297 extern int fclose(FILE *);
298 PyFileObject *f;
299
300 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
301 if (f != NULL) {
302 if (open_the_file(f, name, mode) == NULL) {
303 Py_DECREF(f);
304 f = NULL;
305 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308}
309
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310void
Fred Drakefd99de62000-07-09 05:02:18 +0000311PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000312{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000313 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000315 int type;
316 switch (bufsize) {
317 case 0:
318 type = _IONBF;
319 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000320#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000321 case 1:
322 type = _IOLBF;
323 bufsize = BUFSIZ;
324 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000325#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000326 default:
327 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000328#ifndef HAVE_SETVBUF
329 bufsize = BUFSIZ;
330#endif
331 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000332 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000333 fflush(file->f_fp);
334 if (type == _IONBF) {
335 PyMem_Free(file->f_setbuf);
336 file->f_setbuf = NULL;
337 } else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
339 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000340 }
341#ifdef HAVE_SETVBUF
342 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000343#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000344 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000345#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000346 }
347}
348
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000349/* Set the encoding used to output Unicode strings.
350 Returh 1 on success, 0 on failure. */
351
352int
353PyFile_SetEncoding(PyObject *f, const char *enc)
354{
355 PyFileObject *file = (PyFileObject*)f;
356 PyObject *str = PyString_FromString(enc);
357 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)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000415#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000416 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
418 const char *name_str = name ? PyString_AsString(name) : "?";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000419 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
420 f->f_fp == NULL ? "closed" : "open",
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000421 name_str,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000422 PyString_AsString(f->f_mode),
423 f);
424 Py_XDECREF(name);
425 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000426#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000427 } else {
428 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000429 f->f_fp == NULL ? "closed" : "open",
430 PyString_AsString(f->f_name),
431 PyString_AsString(f->f_mode),
432 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000433 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434}
435
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000437file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000439 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000441 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000442 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000443 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000444 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000446 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447 f->f_fp = NULL;
448 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000449 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000450 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000451 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000453 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454 return PyInt_FromLong((long)sts);
455 Py_INCREF(Py_None);
456 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457}
458
Trent Mickf29f47b2000-08-11 19:02:59 +0000459
Guido van Rossumb8552162001-09-05 14:58:11 +0000460/* Our very own off_t-like type, 64-bit if possible */
461#if !defined(HAVE_LARGEFILE_SUPPORT)
462typedef off_t Py_off_t;
463#elif SIZEOF_OFF_T >= 8
464typedef off_t Py_off_t;
465#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000466typedef fpos_t Py_off_t;
467#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000468#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000469#endif
470
471
Trent Mickf29f47b2000-08-11 19:02:59 +0000472/* a portable fseek() function
473 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000474static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000475_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000476{
Guido van Rossumb8552162001-09-05 14:58:11 +0000477#if !defined(HAVE_LARGEFILE_SUPPORT)
478 return fseek(fp, offset, whence);
479#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000480 return fseeko(fp, offset, whence);
481#elif defined(HAVE_FSEEK64)
482 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000483#elif defined(__BEOS__)
484 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000485#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000486 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
487 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000488 fpos_t pos;
489 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000490 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000491#ifdef MS_WINDOWS
492 fflush(fp);
493 if (_lseeki64(fileno(fp), 0, 2) == -1)
494 return -1;
495#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000496 if (fseek(fp, 0, SEEK_END) != 0)
497 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000498#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000499 /* fall through */
500 case SEEK_CUR:
501 if (fgetpos(fp, &pos) != 0)
502 return -1;
503 offset += pos;
504 break;
505 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000506 }
507 return fsetpos(fp, &offset);
508#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000509#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000510#endif
511}
512
513
514/* a portable ftell() function
515 Return -1 on failure with errno set appropriately, current file
516 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000517static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000518_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000519{
Guido van Rossumb8552162001-09-05 14:58:11 +0000520#if !defined(HAVE_LARGEFILE_SUPPORT)
521 return ftell(fp);
522#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
523 return ftello(fp);
524#elif defined(HAVE_FTELL64)
525 return ftell64(fp);
526#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000527 fpos_t pos;
528 if (fgetpos(fp, &pos) != 0)
529 return -1;
530 return pos;
531#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000532#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000533#endif
534}
535
536
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000538file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000539{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000540 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000541 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000542 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000543 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000544
Guido van Rossumd7297e61992-07-06 14:19:26 +0000545 if (f->f_fp == NULL)
546 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000547 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000548 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000549 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000550 return NULL;
551#if !defined(HAVE_LARGEFILE_SUPPORT)
552 offset = PyInt_AsLong(offobj);
553#else
554 offset = PyLong_Check(offobj) ?
555 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
556#endif
557 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000558 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000561 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000562 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000563 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000564
Guido van Rossumff4949e1992-08-05 19:58:53 +0000565 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000566 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000567 clearerr(f->f_fp);
568 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000569 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000570 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571 Py_INCREF(Py_None);
572 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000573}
574
Trent Mickf29f47b2000-08-11 19:02:59 +0000575
Guido van Rossumd7047b31995-01-02 19:07:15 +0000576#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000578file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000579{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000580 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000581 PyObject *newsizeobj = NULL;
582 Py_off_t initialpos;
583 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000584
Guido van Rossumd7047b31995-01-02 19:07:15 +0000585 if (f->f_fp == NULL)
586 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000587 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000588 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000589
Tim Petersf1827cf2003-09-07 03:30:18 +0000590 /* Get current file position. If the file happens to be open for
591 * update and the last operation was an input operation, C doesn't
592 * define what the later fflush() will do, but we promise truncate()
593 * won't change the current position (and fflush() *does* change it
594 * then at least on Windows). The easiest thing is to capture
595 * current pos now and seek back to it at the end.
596 */
597 Py_BEGIN_ALLOW_THREADS
598 errno = 0;
599 initialpos = _portable_ftell(f->f_fp);
600 Py_END_ALLOW_THREADS
601 if (initialpos == -1)
602 goto onioerror;
603
Tim Petersfb05db22002-03-11 00:24:00 +0000604 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000605 * specified value.
606 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000607 if (newsizeobj != NULL) {
608#if !defined(HAVE_LARGEFILE_SUPPORT)
609 newsize = PyInt_AsLong(newsizeobj);
610#else
611 newsize = PyLong_Check(newsizeobj) ?
612 PyLong_AsLongLong(newsizeobj) :
613 PyInt_AsLong(newsizeobj);
614#endif
615 if (PyErr_Occurred())
616 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000617 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000618 else /* default to current position */
619 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000620
Tim Petersf1827cf2003-09-07 03:30:18 +0000621 /* Flush the stream. We're mixing stream-level I/O with lower-level
622 * I/O, and a flush may be necessary to synch both platform views
623 * of the current file state.
624 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000625 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000626 errno = 0;
627 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000628 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000629 if (ret != 0)
630 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000631
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000632#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000633 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000634 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000635 {
Tim Petersfb05db22002-03-11 00:24:00 +0000636 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000637
Tim Petersf1827cf2003-09-07 03:30:18 +0000638 /* Have to move current pos to desired endpoint on Windows. */
639 Py_BEGIN_ALLOW_THREADS
640 errno = 0;
641 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
642 Py_END_ALLOW_THREADS
643 if (ret)
644 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000645
Tim Peters8f01b682002-03-12 03:04:44 +0000646 /* Truncate. Note that this may grow the file! */
647 Py_BEGIN_ALLOW_THREADS
648 errno = 0;
649 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000650 ret = hFile == (HANDLE)-1;
651 if (ret == 0) {
652 ret = SetEndOfFile(hFile) == 0;
653 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000654 errno = EACCES;
655 }
656 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000657 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000658 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000659 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000660#else
661 Py_BEGIN_ALLOW_THREADS
662 errno = 0;
663 ret = ftruncate(fileno(f->f_fp), newsize);
664 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000665 if (ret != 0)
666 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000667#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000668
Tim Petersf1827cf2003-09-07 03:30:18 +0000669 /* Restore original file position. */
670 Py_BEGIN_ALLOW_THREADS
671 errno = 0;
672 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
673 Py_END_ALLOW_THREADS
674 if (ret)
675 goto onioerror;
676
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677 Py_INCREF(Py_None);
678 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000679
680onioerror:
681 PyErr_SetFromErrno(PyExc_IOError);
682 clearerr(f->f_fp);
683 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000684}
685#endif /* HAVE_FTRUNCATE */
686
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000688file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000689{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000690 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000691
Guido van Rossumd7297e61992-07-06 14:19:26 +0000692 if (f->f_fp == NULL)
693 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000695 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000696 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000698 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000699 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000700 clearerr(f->f_fp);
701 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000702 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000703 if (f->f_skipnextlf) {
704 int c;
705 c = GETC(f->f_fp);
706 if (c == '\n') {
707 pos++;
708 f->f_skipnextlf = 0;
709 } else if (c != EOF) ungetc(c, f->f_fp);
710 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000711#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000712 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000713#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000714 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000715#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000716}
717
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000719file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000720{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000721 if (f->f_fp == NULL)
722 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000723 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000724}
725
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000726static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000727file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000728{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000729 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000730
Guido van Rossumd7297e61992-07-06 14:19:26 +0000731 if (f->f_fp == NULL)
732 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000733 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000734 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000735 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000737 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000739 clearerr(f->f_fp);
740 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000741 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742 Py_INCREF(Py_None);
743 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000744}
745
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000746static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000747file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000748{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000749 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000750 if (f->f_fp == NULL)
751 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000753 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000755 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000756}
757
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000758
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000759#if BUFSIZ < 8192
760#define SMALLCHUNK 8192
761#else
762#define SMALLCHUNK BUFSIZ
763#endif
764
Guido van Rossum3c259041999-01-14 19:00:14 +0000765#if SIZEOF_INT < 4
766#define BIGCHUNK (512 * 32)
767#else
768#define BIGCHUNK (512 * 1024)
769#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000770
771static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000772new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000773{
774#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000775 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000776 struct stat st;
777 if (fstat(fileno(f->f_fp), &st) == 0) {
778 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000779 /* The following is not a bug: we really need to call lseek()
780 *and* ftell(). The reason is that some stdio libraries
781 mistakenly flush their buffer when ftell() is called and
782 the lseek() call it makes fails, thereby throwing away
783 data that cannot be recovered in any way. To avoid this,
784 we first test lseek(), and only call ftell() if lseek()
785 works. We can't use the lseek() value either, because we
786 need to take the amount of buffered data into account.
787 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000788 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000789 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000790 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000791 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000792 if (pos < 0)
793 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000794 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000795 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000796 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000797 }
798#endif
799 if (currentsize > SMALLCHUNK) {
800 /* Keep doubling until we reach BIGCHUNK;
801 then keep adding BIGCHUNK. */
802 if (currentsize <= BIGCHUNK)
803 return currentsize + currentsize;
804 else
805 return currentsize + BIGCHUNK;
806 }
807 return currentsize + SMALLCHUNK;
808}
809
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000810#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
811#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
812#else
813#ifdef EWOULDBLOCK
814#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
815#else
816#ifdef EAGAIN
817#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
818#else
819#define BLOCKED_ERRNO(x) 0
820#endif
821#endif
822#endif
823
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000825file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000826{
Guido van Rossum789a1611997-05-10 22:33:55 +0000827 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000828 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000829 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000830
Guido van Rossumd7297e61992-07-06 14:19:26 +0000831 if (f->f_fp == NULL)
832 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000833 /* refuse to mix with f.next() */
834 if (f->f_buf != NULL &&
835 (f->f_bufend - f->f_bufptr) > 0 &&
836 f->f_buf[0] != '\0')
837 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000838 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000839 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000840 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000841 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000842 else
843 buffersize = bytesrequested;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000845 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000846 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000847 return NULL;
848 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000849 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000850 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000851 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000852 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000853 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000854 Py_BEGIN_ALLOW_THREADS
855 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000856 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000857 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000858 Py_END_ALLOW_THREADS
859 if (chunksize == 0) {
860 if (!ferror(f->f_fp))
861 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000862 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000863 /* When in non-blocking mode, data shouldn't
864 * be discarded if a blocking signal was
865 * received. That will also happen if
866 * chunksize != 0, but bytesread < buffersize. */
867 if (bytesread > 0 && BLOCKED_ERRNO(errno))
868 break;
869 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000870 Py_DECREF(v);
871 return NULL;
872 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000873 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000874 if (bytesread < buffersize) {
875 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000876 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000877 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000878 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000879 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000880 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000881 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000882 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000883 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000884 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000885 }
886 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000887 if (bytesread != buffersize)
888 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889 return v;
890}
891
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000892static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000893file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000894{
895 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000896 Py_ssize_t ntodo;
897 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000898
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000899 if (f->f_fp == NULL)
900 return err_closed();
Guido van Rossumd624f182006-04-24 13:47:05 +0000901 if (!f->f_binary) {
902 PyErr_SetString(PyExc_TypeError,
903 "readinto() requires binary mode");
904 return NULL;
905 }
Thomas Woutersc45251a2006-02-12 11:53:32 +0000906 /* refuse to mix with f.next() */
907 if (f->f_buf != NULL &&
908 (f->f_bufend - f->f_bufptr) > 0 &&
909 f->f_buf[0] != '\0')
910 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000911 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000912 return NULL;
913 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000914 while (ntodo > 0) {
915 Py_BEGIN_ALLOW_THREADS
916 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000917 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000918 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000919 Py_END_ALLOW_THREADS
920 if (nnow == 0) {
921 if (!ferror(f->f_fp))
922 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000923 PyErr_SetFromErrno(PyExc_IOError);
924 clearerr(f->f_fp);
925 return NULL;
926 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000927 ndone += nnow;
928 ntodo -= nnow;
929 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000930 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000931}
932
Tim Peters86821b22001-01-07 21:19:34 +0000933/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000934Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000935
936Under MSVC 6:
937
Tim Peters1c733232001-01-08 04:02:07 +0000938+ MS threadsafe getc is very slow (multiple layers of function calls before+
939 after each character, to lock+unlock the stream).
940+ The stream-locking functions are MS-internal -- can't access them from user
941 code.
942+ There's nothing Tim could find in the MS C or platform SDK libraries that
943 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000944+ MS fgets locks/unlocks only once per line; it's the only hook we have.
945
946So we use fgets for speed(!), despite that it's painful.
947
948MS realloc is also slow.
949
Tim Petersf29b64d2001-01-15 06:33:19 +0000950Reports from other platforms on this method vs getc_unlocked (which MS doesn't
951have):
952 Linux a wash
953 Solaris a wash
954 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000955
Tim Petersf29b64d2001-01-15 06:33:19 +0000956CAUTION: The C std isn't clear about this: in those cases where fgets
957writes something into the buffer, can it write into any position beyond the
958required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
959known on which it does; and it would be a strange way to code fgets. Still,
960getline_via_fgets may not work correctly if it does. The std test
961test_bufio.py should fail if platform fgets() routinely writes beyond the
962trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000963**************************************************************************/
964
Tim Petersf29b64d2001-01-15 06:33:19 +0000965/* Use this routine if told to, or by default on non-get_unlocked()
966 * platforms unless told not to. Yikes! Let's spell that out:
967 * On a platform with getc_unlocked():
968 * By default, use getc_unlocked().
969 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
970 * On a platform without getc_unlocked():
971 * By default, use fgets().
972 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
973 */
974#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
975#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000976#endif
977
Tim Petersf29b64d2001-01-15 06:33:19 +0000978#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
979#undef USE_FGETS_IN_GETLINE
980#endif
981
982#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000983static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000984getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000985{
Tim Peters15b83852001-01-08 00:53:12 +0000986/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000987 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
988 * to fill this much of the buffer with a known value in order to figure out
989 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
990 * than "most" lines, we waste time filling unused buffer slots. 100 is
991 * surely adequate for most peoples' email archives, chewing over source code,
992 * etc -- "regular old text files".
993 * MAXBUFSIZE is the maximum line length that lets us get away with the less
994 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
995 * cautions about boosting that. 300 was chosen because the worst real-life
996 * text-crunching job reported on Python-Dev was a mail-log crawler where over
997 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000998 */
Tim Peters142297a2001-01-15 10:36:56 +0000999#define INITBUFSIZE 100
1000#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001001 char* p; /* temp */
1002 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001003 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001004 char* pvfree; /* address of next free slot */
1005 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001006 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1007 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001008 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +00001009
Tim Peters15b83852001-01-08 00:53:12 +00001010 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001011 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001012 */
Tim Peters142297a2001-01-15 10:36:56 +00001013 total_v_size = INITBUFSIZE; /* start small and pray */
1014 pvfree = buf;
1015 for (;;) {
1016 Py_BEGIN_ALLOW_THREADS
1017 pvend = buf + total_v_size;
1018 nfree = pvend - pvfree;
1019 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001020 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1021 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +00001022 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001023
Tim Peters142297a2001-01-15 10:36:56 +00001024 if (p == NULL) {
1025 clearerr(fp);
1026 if (PyErr_CheckSignals())
1027 return NULL;
1028 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001029 return v;
1030 }
Tim Peters142297a2001-01-15 10:36:56 +00001031 /* fgets read *something* */
1032 p = memchr(pvfree, '\n', nfree);
1033 if (p != NULL) {
1034 /* Did the \n come from fgets or from us?
1035 * Since fgets stops at the first \n, and then writes
1036 * \0, if it's from fgets a \0 must be next. But if
1037 * that's so, it could not have come from us, since
1038 * the \n's we filled the buffer with have only more
1039 * \n's to the right.
1040 */
1041 if (p+1 < pvend && *(p+1) == '\0') {
1042 /* It's from fgets: we win! In particular,
1043 * we haven't done any mallocs yet, and can
1044 * build the final result on the first try.
1045 */
1046 ++p; /* include \n from fgets */
1047 }
1048 else {
1049 /* Must be from us: fgets didn't fill the
1050 * buffer and didn't find a newline, so it
1051 * must be the last and newline-free line of
1052 * the file.
1053 */
1054 assert(p > pvfree && *(p-1) == '\0');
1055 --p; /* don't include \0 from fgets */
1056 }
1057 v = PyString_FromStringAndSize(buf, p - buf);
1058 return v;
1059 }
1060 /* yuck: fgets overwrote all the newlines, i.e. the entire
1061 * buffer. So this line isn't over yet, or maybe it is but
1062 * we're exactly at EOF. If we haven't already, try using the
1063 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001064 */
Tim Peters142297a2001-01-15 10:36:56 +00001065 assert(*(pvend-1) == '\0');
1066 if (pvfree == buf) {
1067 pvfree = pvend - 1; /* overwrite trailing null */
1068 total_v_size = MAXBUFSIZE;
1069 }
1070 else
1071 break;
Tim Peters86821b22001-01-07 21:19:34 +00001072 }
Tim Peters142297a2001-01-15 10:36:56 +00001073
1074 /* The stack buffer isn't big enough; malloc a string object and read
1075 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001076 */
Tim Petersddea2082002-03-23 10:03:50 +00001077 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001078 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001079 if (v == NULL)
1080 return v;
1081 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001082 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1083 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001084
1085 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001086 * after setting p one beyond the end of the line. The code here is
1087 * very much like the code above, except reads into v's buffer; see
1088 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001089 */
1090 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001091 Py_BEGIN_ALLOW_THREADS
1092 pvend = BUF(v) + total_v_size;
1093 nfree = pvend - pvfree;
1094 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095 assert(nfree < INT_MAX);
1096 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001097 Py_END_ALLOW_THREADS
1098
1099 if (p == NULL) {
1100 clearerr(fp);
1101 if (PyErr_CheckSignals()) {
1102 Py_DECREF(v);
1103 return NULL;
1104 }
1105 p = pvfree;
1106 break;
1107 }
Tim Peters86821b22001-01-07 21:19:34 +00001108 p = memchr(pvfree, '\n', nfree);
1109 if (p != NULL) {
1110 if (p+1 < pvend && *(p+1) == '\0') {
1111 /* \n came from fgets */
1112 ++p;
1113 break;
1114 }
1115 /* \n came from us; last line of file, no newline */
1116 assert(p > pvfree && *(p-1) == '\0');
1117 --p;
1118 break;
1119 }
1120 /* expand buffer and try again */
1121 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001122 increment = total_v_size >> 2; /* mild exponential growth */
1123 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001124 if (total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001125 PyErr_SetString(PyExc_OverflowError,
1126 "line is longer than a Python string can hold");
1127 Py_DECREF(v);
1128 return NULL;
1129 }
1130 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1131 return NULL;
1132 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001133 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001134 }
1135 if (BUF(v) + total_v_size != p)
1136 _PyString_Resize(&v, p - BUF(v));
1137 return v;
1138#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001139#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001140}
Tim Petersf29b64d2001-01-15 06:33:19 +00001141#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001142
Guido van Rossum0bd24411991-04-04 15:21:57 +00001143/* Internal routine to get a line.
1144 Size argument interpretation:
1145 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001146 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001147*/
1148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001149static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001150get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001151{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001152 FILE *fp = f->f_fp;
1153 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001154 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001155 size_t total_v_size; /* total # of slots in buffer */
1156 size_t used_v_size; /* # used slots in buffer */
1157 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001158 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001159 int newlinetypes = f->f_newlinetypes;
1160 int skipnextlf = f->f_skipnextlf;
1161 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001162
Jack Jansen7b8c7542002-04-14 20:12:41 +00001163#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001164 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001165 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001166#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001167 total_v_size = n > 0 ? n : 100;
1168 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001169 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001170 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001171 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001172 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001173
Guido van Rossumce5ba841991-03-06 13:06:18 +00001174 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001175 Py_BEGIN_ALLOW_THREADS
1176 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001177 if (univ_newline) {
1178 c = 'x'; /* Shut up gcc warning */
1179 while ( buf != end && (c = GETC(fp)) != EOF ) {
1180 if (skipnextlf ) {
1181 skipnextlf = 0;
1182 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001183 /* Seeing a \n here with
1184 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001185 * saw a \r before.
1186 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001187 newlinetypes |= NEWLINE_CRLF;
1188 c = GETC(fp);
1189 if (c == EOF) break;
1190 } else {
1191 newlinetypes |= NEWLINE_CR;
1192 }
1193 }
1194 if (c == '\r') {
1195 skipnextlf = 1;
1196 c = '\n';
1197 } else if ( c == '\n')
1198 newlinetypes |= NEWLINE_LF;
1199 *buf++ = c;
1200 if (c == '\n') break;
1201 }
1202 if ( c == EOF && skipnextlf )
1203 newlinetypes |= NEWLINE_CR;
1204 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001205 while ((c = GETC(fp)) != EOF &&
1206 (*buf++ = c) != '\n' &&
1207 buf != end)
1208 ;
1209 FUNLOCKFILE(fp);
1210 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001211 f->f_newlinetypes = newlinetypes;
1212 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001213 if (c == '\n')
1214 break;
1215 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001216 if (ferror(fp)) {
1217 PyErr_SetFromErrno(PyExc_IOError);
1218 clearerr(fp);
1219 Py_DECREF(v);
1220 return NULL;
1221 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001222 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001223 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001224 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001225 return NULL;
1226 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001227 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001228 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001229 /* Must be because buf == end */
1230 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001231 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001232 used_v_size = total_v_size;
1233 increment = total_v_size >> 2; /* mild exponential growth */
1234 total_v_size += increment;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001235 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001236 PyErr_SetString(PyExc_OverflowError,
1237 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001238 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001239 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001240 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001241 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001242 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001243 buf = BUF(v) + used_v_size;
1244 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001245 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001246
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001247 used_v_size = buf - BUF(v);
1248 if (used_v_size != total_v_size)
1249 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001250 return v;
1251}
1252
Guido van Rossum0bd24411991-04-04 15:21:57 +00001253/* External C interface */
1254
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001255PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001256PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001257{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001258 PyObject *result;
1259
Guido van Rossum3165fe61992-09-25 21:59:05 +00001260 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001261 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001262 return NULL;
1263 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001264
1265 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001266 PyFileObject *fo = (PyFileObject *)f;
1267 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001268 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001269 /* refuse to mix with f.next() */
1270 if (fo->f_buf != NULL &&
1271 (fo->f_bufend - fo->f_bufptr) > 0 &&
1272 fo->f_buf[0] != '\0')
1273 return err_iterbuffered();
1274 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001275 }
1276 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001277 PyObject *reader;
1278 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001279
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001280 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001281 if (reader == NULL)
1282 return NULL;
1283 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001284 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001285 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001286 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001287 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001288 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001289 return NULL;
1290 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001291 result = PyEval_CallObject(reader, args);
1292 Py_DECREF(reader);
1293 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001294 if (result != NULL && !PyString_Check(result) &&
1295 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001296 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001297 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001298 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001299 "object.readline() returned non-string");
1300 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001301 }
1302
1303 if (n < 0 && result != NULL && PyString_Check(result)) {
1304 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001305 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001306 if (len == 0) {
1307 Py_DECREF(result);
1308 result = NULL;
1309 PyErr_SetString(PyExc_EOFError,
1310 "EOF when reading a line");
1311 }
1312 else if (s[len-1] == '\n') {
1313 if (result->ob_refcnt == 1)
1314 _PyString_Resize(&result, len-1);
1315 else {
1316 PyObject *v;
1317 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001318 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001319 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001320 }
1321 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001322 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001323#ifdef Py_USING_UNICODE
1324 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1325 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001326 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001327 if (len == 0) {
1328 Py_DECREF(result);
1329 result = NULL;
1330 PyErr_SetString(PyExc_EOFError,
1331 "EOF when reading a line");
1332 }
1333 else if (s[len-1] == '\n') {
1334 if (result->ob_refcnt == 1)
1335 PyUnicode_Resize(&result, len-1);
1336 else {
1337 PyObject *v;
1338 v = PyUnicode_FromUnicode(s, len-1);
1339 Py_DECREF(result);
1340 result = v;
1341 }
1342 }
1343 }
1344#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001345 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001346}
1347
1348/* Python method */
1349
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001350static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001351file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001352{
Guido van Rossum789a1611997-05-10 22:33:55 +00001353 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001354
Guido van Rossumd7297e61992-07-06 14:19:26 +00001355 if (f->f_fp == NULL)
1356 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001357 /* refuse to mix with f.next() */
1358 if (f->f_buf != NULL &&
1359 (f->f_bufend - f->f_bufptr) > 0 &&
1360 f->f_buf[0] != '\0')
1361 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001362 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001363 return NULL;
1364 if (n == 0)
1365 return PyString_FromString("");
1366 if (n < 0)
1367 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001368 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001369}
1370
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001371static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001372file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001373{
Guido van Rossum789a1611997-05-10 22:33:55 +00001374 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001375 PyObject *list;
1376 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001377 char small_buffer[SMALLCHUNK];
1378 char *buffer = small_buffer;
1379 size_t buffersize = SMALLCHUNK;
1380 PyObject *big_buffer = NULL;
1381 size_t nfilled = 0;
1382 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001383 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001384 char *p, *q, *end;
1385 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001386 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001387
Guido van Rossumd7297e61992-07-06 14:19:26 +00001388 if (f->f_fp == NULL)
1389 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001390 /* refuse to mix with f.next() */
1391 if (f->f_buf != NULL &&
1392 (f->f_bufend - f->f_bufptr) > 0 &&
1393 f->f_buf[0] != '\0')
1394 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001395 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001396 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001397 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001398 return NULL;
1399 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001400 if (shortread)
1401 nread = 0;
1402 else {
1403 Py_BEGIN_ALLOW_THREADS
1404 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001405 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001406 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001407 Py_END_ALLOW_THREADS
1408 shortread = (nread < buffersize-nfilled);
1409 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001410 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001411 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001412 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001413 break;
1414 PyErr_SetFromErrno(PyExc_IOError);
1415 clearerr(f->f_fp);
1416 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001418 list = NULL;
1419 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001420 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001421 totalread += nread;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001422 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001423 if (p == NULL) {
1424 /* Need a larger buffer to fit this line */
1425 nfilled += nread;
1426 buffersize *= 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001427 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001428 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001429 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001430 goto error;
1431 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001432 if (big_buffer == NULL) {
1433 /* Create the big buffer */
1434 big_buffer = PyString_FromStringAndSize(
1435 NULL, buffersize);
1436 if (big_buffer == NULL)
1437 goto error;
1438 buffer = PyString_AS_STRING(big_buffer);
1439 memcpy(buffer, small_buffer, nfilled);
1440 }
1441 else {
1442 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001443 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1444 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001445 buffer = PyString_AS_STRING(big_buffer);
1446 }
1447 continue;
1448 }
1449 end = buffer+nfilled+nread;
1450 q = buffer;
1451 do {
1452 /* Process complete lines */
1453 p++;
1454 line = PyString_FromStringAndSize(q, p-q);
1455 if (line == NULL)
1456 goto error;
1457 err = PyList_Append(list, line);
1458 Py_DECREF(line);
1459 if (err != 0)
1460 goto error;
1461 q = p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001462 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001463 } while (p != NULL);
1464 /* Move the remaining incomplete line to the start */
1465 nfilled = end-q;
1466 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001467 if (sizehint > 0)
1468 if (totalread >= (size_t)sizehint)
1469 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001470 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001471 if (nfilled != 0) {
1472 /* Partial last line */
1473 line = PyString_FromStringAndSize(buffer, nfilled);
1474 if (line == NULL)
1475 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001476 if (sizehint > 0) {
1477 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001478 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001479 if (rest == NULL) {
1480 Py_DECREF(line);
1481 goto error;
1482 }
1483 PyString_Concat(&line, rest);
1484 Py_DECREF(rest);
1485 if (line == NULL)
1486 goto error;
1487 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001488 err = PyList_Append(list, line);
1489 Py_DECREF(line);
1490 if (err != 0)
1491 goto error;
1492 }
1493 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001494 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001495 return list;
1496}
1497
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001498static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001499file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001500{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001501 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001502 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001503 if (f->f_fp == NULL)
1504 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001505 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001506 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001507 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001508 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001509 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001510 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001511 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001512 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001513 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001514 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001515 return NULL;
1516 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001517 Py_INCREF(Py_None);
1518 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001519}
1520
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001521static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001522file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001523{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001524#define CHUNKSIZE 1000
1525 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001526 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001527 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001528 int index, islist;
1529 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001530
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001531 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001532 if (f->f_fp == NULL)
1533 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001534
1535 result = NULL;
1536 list = NULL;
1537 islist = PyList_Check(seq);
1538 if (islist)
1539 it = NULL;
1540 else {
1541 it = PyObject_GetIter(seq);
1542 if (it == NULL) {
1543 PyErr_SetString(PyExc_TypeError,
1544 "writelines() requires an iterable argument");
1545 return NULL;
1546 }
1547 /* From here on, fail by going to error, to reclaim "it". */
1548 list = PyList_New(CHUNKSIZE);
1549 if (list == NULL)
1550 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001551 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001552
1553 /* Strategy: slurp CHUNKSIZE lines into a private list,
1554 checking that they are all strings, then write that list
1555 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001556 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001557 if (islist) {
1558 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001559 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001560 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001561 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001562 j = PyList_GET_SIZE(list);
1563 }
1564 else {
1565 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001566 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001567 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001568 if (PyErr_Occurred())
1569 goto error;
1570 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001571 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001572 PyList_SetItem(list, j, line);
1573 }
1574 }
1575 if (j == 0)
1576 break;
1577
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001578 /* Check that all entries are indeed strings. If not,
1579 apply the same rules as for file.write() and
1580 convert the results to strings. This is slow, but
1581 seems to be the only way since all conversion APIs
1582 could potentially execute Python code. */
1583 for (i = 0; i < j; i++) {
1584 PyObject *v = PyList_GET_ITEM(list, i);
1585 if (!PyString_Check(v)) {
1586 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001587 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001588 PyObject_AsReadBuffer(v,
1589 (const void**)&buffer,
1590 &len)) ||
1591 PyObject_AsCharBuffer(v,
1592 &buffer,
1593 &len))) {
1594 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001595 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001596 goto error;
1597 }
1598 line = PyString_FromStringAndSize(buffer,
1599 len);
1600 if (line == NULL)
1601 goto error;
1602 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001603 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001604 }
1605 }
1606
1607 /* Since we are releasing the global lock, the
1608 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001609 Py_BEGIN_ALLOW_THREADS
1610 f->f_softspace = 0;
1611 errno = 0;
1612 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001613 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001614 len = PyString_GET_SIZE(line);
1615 nwritten = fwrite(PyString_AS_STRING(line),
1616 1, len, f->f_fp);
1617 if (nwritten != len) {
1618 Py_BLOCK_THREADS
1619 PyErr_SetFromErrno(PyExc_IOError);
1620 clearerr(f->f_fp);
1621 goto error;
1622 }
1623 }
1624 Py_END_ALLOW_THREADS
1625
1626 if (j < CHUNKSIZE)
1627 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001628 }
1629
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001630 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001631 result = Py_None;
1632 error:
1633 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001634 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001635 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001636#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001637}
1638
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001639static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001640file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001641{
1642 if (f->f_fp == NULL)
1643 return err_closed();
1644 Py_INCREF(f);
1645 return (PyObject *)f;
1646}
1647
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001648static PyObject *
1649file_exit(PyFileObject *f, PyObject *args)
1650{
1651 PyObject *ret = file_close(f);
1652 if (!ret)
1653 /* If error occurred, pass through */
1654 return NULL;
1655 Py_DECREF(ret);
1656 /* We cannot return the result of close since a true
1657 * value will be interpreted as "yes, swallow the
1658 * exception if one was raised inside the with block". */
1659 Py_RETURN_NONE;
1660}
1661
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001662PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001663"readline([size]) -> next line from the file, as a string.\n"
1664"\n"
1665"Retain newline. A non-negative size argument limits the maximum\n"
1666"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001667"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001668
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001669PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001670"read([size]) -> read at most size bytes, returned as a string.\n"
1671"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001672"If the size argument is negative or omitted, read until EOF is reached.\n"
1673"Notice that when in non-blocking mode, less data than what was requested\n"
1674"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001675
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001676PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001677"write(str) -> None. Write string str to file.\n"
1678"\n"
1679"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001680"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001681
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001682PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001683"fileno() -> integer \"file descriptor\".\n"
1684"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001685"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001687PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001688"seek(offset[, whence]) -> None. Move to new file position.\n"
1689"\n"
1690"Argument offset is a byte count. Optional argument whence defaults to\n"
1691"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1692"(move relative to current position, positive or negative), and 2 (move\n"
1693"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001694"seeking beyond the end of a file). If the file is opened in text mode,\n"
1695"only offsets returned by tell() are legal. Use of other offsets causes\n"
1696"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001697"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001698"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001699
Guido van Rossumd7047b31995-01-02 19:07:15 +00001700#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001701PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001702"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1703"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001704"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001705#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001707PyDoc_STRVAR(tell_doc,
1708"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001710PyDoc_STRVAR(readinto_doc,
1711"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001713PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001714"readlines([size]) -> list of strings, each a line from the file.\n"
1715"\n"
1716"Call readline() repeatedly and return a list of the lines so read.\n"
1717"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001718"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001720PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001721"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001722"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001723"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001724"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001726PyDoc_STRVAR(flush_doc,
1727"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001729PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001730"close() -> None or (perhaps) an integer. Close the file.\n"
1731"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001732"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001733"further I/O operations. close() may be called more than once without\n"
1734"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001737PyDoc_STRVAR(isatty_doc,
1738"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001739
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001740PyDoc_STRVAR(enter_doc,
1741 "__enter__() -> self.");
1742
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001743PyDoc_STRVAR(exit_doc,
1744 "__exit__(*excinfo) -> None. Closes the file.");
1745
Tim Petersefc3a3a2001-09-20 07:55:22 +00001746static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001747 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1748 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1749 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1750 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1751 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001752#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001753 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001754#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001755 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1756 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1757 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001758 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1759 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1760 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1761 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001762 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001763 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001764 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001765};
1766
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001767#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001768
Guido van Rossum6f799372001-09-20 20:46:19 +00001769static PyMemberDef file_memberlist[] = {
1770 {"softspace", T_INT, OFF(f_softspace), 0,
1771 "flag indicating that a space needs to be printed; used by print"},
1772 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001773 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001774 {"name", T_OBJECT, OFF(f_name), RO,
1775 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001776 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1777 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001778 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001779 {NULL} /* Sentinel */
1780};
1781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001782static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001784{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001785 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001786}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001787static PyObject *
1788get_newlines(PyFileObject *f, void *closure)
1789{
1790 switch (f->f_newlinetypes) {
1791 case NEWLINE_UNKNOWN:
1792 Py_INCREF(Py_None);
1793 return Py_None;
1794 case NEWLINE_CR:
1795 return PyString_FromString("\r");
1796 case NEWLINE_LF:
1797 return PyString_FromString("\n");
1798 case NEWLINE_CR|NEWLINE_LF:
1799 return Py_BuildValue("(ss)", "\r", "\n");
1800 case NEWLINE_CRLF:
1801 return PyString_FromString("\r\n");
1802 case NEWLINE_CR|NEWLINE_CRLF:
1803 return Py_BuildValue("(ss)", "\r", "\r\n");
1804 case NEWLINE_LF|NEWLINE_CRLF:
1805 return Py_BuildValue("(ss)", "\n", "\r\n");
1806 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1807 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1808 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001809 PyErr_Format(PyExc_SystemError,
1810 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001811 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001812 return NULL;
1813 }
1814}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001815
Guido van Rossum32d34c82001-09-20 21:45:26 +00001816static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001817 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001818 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001819 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 {0},
1821};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001822
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001823static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001824drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001825{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001826 if (f->f_buf != NULL) {
1827 PyMem_Free(f->f_buf);
1828 f->f_buf = NULL;
1829 }
Guido van Rossum65967252001-04-21 13:20:18 +00001830}
1831
Tim Petersf1827cf2003-09-07 03:30:18 +00001832/* Make sure that file has a readahead buffer with at least one byte
1833 (unless at EOF) and no more than bufsize. Returns negative value on
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001834 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001835static int
1836readahead(PyFileObject *f, int bufsize)
1837{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001838 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001839
1840 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001841 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001842 return 0;
1843 else
1844 drop_readahead(f);
1845 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001846 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
1847 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001848 return -1;
1849 }
1850 Py_BEGIN_ALLOW_THREADS
1851 errno = 0;
1852 chunksize = Py_UniversalNewlineFread(
1853 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1854 Py_END_ALLOW_THREADS
1855 if (chunksize == 0) {
1856 if (ferror(f->f_fp)) {
1857 PyErr_SetFromErrno(PyExc_IOError);
1858 clearerr(f->f_fp);
1859 drop_readahead(f);
1860 return -1;
1861 }
1862 }
1863 f->f_bufptr = f->f_buf;
1864 f->f_bufend = f->f_buf + chunksize;
1865 return 0;
1866}
1867
1868/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001869 uninitialized bytes followed by the remainder of the line. Don't be
1870 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001871 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1872
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001873static PyStringObject *
1874readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1875{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001876 PyStringObject* s;
1877 char *bufptr;
1878 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001879 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001880
1881 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001882 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001883 return NULL;
1884
1885 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001886 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001887 return (PyStringObject *)
1888 PyString_FromStringAndSize(NULL, skip);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001889 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001890 if (bufptr != NULL) {
1891 bufptr++; /* Count the '\n' */
1892 len = bufptr - f->f_bufptr;
1893 s = (PyStringObject *)
1894 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001895 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001896 return NULL;
1897 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1898 f->f_bufptr = bufptr;
1899 if (bufptr == f->f_bufend)
1900 drop_readahead(f);
1901 } else {
1902 bufptr = f->f_bufptr;
1903 buf = f->f_buf;
1904 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001905 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001906 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001907 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001908 if (s == NULL) {
1909 PyMem_Free(buf);
1910 return NULL;
1911 }
1912 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1913 PyMem_Free(buf);
1914 }
1915 return s;
1916}
1917
1918/* A larger buffer size may actually decrease performance. */
1919#define READAHEAD_BUFSIZE 8192
1920
1921static PyObject *
1922file_iternext(PyFileObject *f)
1923{
1924 PyStringObject* l;
1925
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001926 if (f->f_fp == NULL)
1927 return err_closed();
1928
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001929 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1930 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1931 Py_XDECREF(l);
1932 return NULL;
1933 }
1934 return (PyObject *)l;
1935}
1936
1937
Tim Peters59c9a642001-09-13 05:38:56 +00001938static PyObject *
1939file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1940{
Tim Peters44410012001-09-14 03:26:08 +00001941 PyObject *self;
1942 static PyObject *not_yet_string;
1943
1944 assert(type != NULL && type->tp_alloc != NULL);
1945
1946 if (not_yet_string == NULL) {
1947 not_yet_string = PyString_FromString("<uninitialized file>");
1948 if (not_yet_string == NULL)
1949 return NULL;
1950 }
1951
1952 self = type->tp_alloc(type, 0);
1953 if (self != NULL) {
1954 /* Always fill in the name and mode, so that nobody else
1955 needs to special-case NULLs there. */
1956 Py_INCREF(not_yet_string);
1957 ((PyFileObject *)self)->f_name = not_yet_string;
1958 Py_INCREF(not_yet_string);
1959 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001960 Py_INCREF(Py_None);
1961 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001962 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001963 }
1964 return self;
1965}
1966
1967static int
1968file_init(PyObject *self, PyObject *args, PyObject *kwds)
1969{
1970 PyFileObject *foself = (PyFileObject *)self;
1971 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001972 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001973 char *name = NULL;
1974 char *mode = "r";
1975 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001976 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001977
1978 assert(PyFile_Check(self));
1979 if (foself->f_fp != NULL) {
1980 /* Have to close the existing file first. */
1981 PyObject *closeresult = file_close(foself);
1982 if (closeresult == NULL)
1983 return -1;
1984 Py_DECREF(closeresult);
1985 }
Tim Peters59c9a642001-09-13 05:38:56 +00001986
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001987#ifdef Py_WIN_WIDE_FILENAMES
1988 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1989 PyObject *po;
1990 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1991 kwlist, &po, &mode, &bufsize)) {
1992 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001993 if (fill_file_fields(foself, NULL, po, mode,
1994 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001995 goto Error;
1996 } else {
1997 /* Drop the argument parsing error as narrow
1998 strings are also valid. */
1999 PyErr_Clear();
2000 }
2001 }
2002#endif
2003
2004 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002005 PyObject *o_name;
2006
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002007 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2008 Py_FileSystemDefaultEncoding,
2009 &name,
2010 &mode, &bufsize))
2011 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002012
2013 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002014 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2015 kwlist, &o_name, &mode,
2016 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002017 return -1;
2018
2019 if (fill_file_fields(foself, NULL, o_name, mode,
2020 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002021 goto Error;
2022 }
Tim Peters44410012001-09-14 03:26:08 +00002023 if (open_the_file(foself, name, mode) == NULL)
2024 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002025 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002026 PyFile_SetBufSize(self, bufsize);
2027 goto Done;
2028
2029Error:
2030 ret = -1;
2031 /* fall through */
2032Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002033 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002034 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002035}
2036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002037PyDoc_VAR(file_doc) =
2038PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002039"file(name[, mode[, buffering]]) -> file object\n"
2040"\n"
2041"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2042"writing or appending. The file will be created if it doesn't exist\n"
2043"when opened for writing or appending; it will be truncated when\n"
2044"opened for writing. Add a 'b' to the mode for binary files.\n"
2045"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2046"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00002047"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002048)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002049PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002050"Add a 'U' to mode to open the file for input with universal newline\n"
2051"support. Any line ending in the input file will be seen as a '\\n'\n"
2052"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2053"the value for this attribute is one of None (no newline read yet),\n"
2054"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2055"\n"
2056"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002057);
Tim Peters59c9a642001-09-13 05:38:56 +00002058
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002059PyTypeObject PyFile_Type = {
2060 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002061 0,
2062 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002063 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002064 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002065 (destructor)file_dealloc, /* tp_dealloc */
2066 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 0, /* tp_getattr */
2068 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002069 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002071 0, /* tp_as_number */
2072 0, /* tp_as_sequence */
2073 0, /* tp_as_mapping */
2074 0, /* tp_hash */
2075 0, /* tp_call */
2076 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002078 /* softspace is writable: we must supply tp_setattro */
2079 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002080 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002081 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002082 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 0, /* tp_traverse */
2084 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002085 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002086 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002087 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002088 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 file_methods, /* tp_methods */
2090 file_memberlist, /* tp_members */
2091 file_getsetlist, /* tp_getset */
2092 0, /* tp_base */
2093 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002094 0, /* tp_descr_get */
2095 0, /* tp_descr_set */
2096 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002097 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002098 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002099 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002100 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002101};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002102
2103/* Interface for the 'soft space' between print items. */
2104
2105int
Fred Drakefd99de62000-07-09 05:02:18 +00002106PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002107{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002108 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002109 if (f == NULL) {
2110 /* Do nothing */
2111 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002112 else if (PyFile_Check(f)) {
2113 oldflag = ((PyFileObject *)f)->f_softspace;
2114 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002115 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002116 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 PyObject *v;
2118 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002119 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002120 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002121 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 if (PyInt_Check(v))
2123 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002124 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002125 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002127 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002128 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002129 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002130 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002131 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2132 PyErr_Clear();
2133 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002134 }
2135 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002136 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002137}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002138
2139/* Interfaces to write objects/strings to file-like objects */
2140
2141int
Fred Drakefd99de62000-07-09 05:02:18 +00002142PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002143{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002145 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002147 return -1;
2148 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002149 else if (PyFile_Check(f)) {
2150 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002151#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002152 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2153 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002154#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002155 if (fp == NULL) {
2156 err_closed();
2157 return -1;
2158 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002159#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002160 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002161 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002162 char *cenc = PyString_AS_STRING(enc);
2163 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2164 if (value == NULL)
2165 return -1;
2166 } else {
2167 value = v;
2168 Py_INCREF(value);
2169 }
2170 result = PyObject_Print(value, fp, flags);
2171 Py_DECREF(value);
2172 return result;
2173#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002174 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002175#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002176 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002177 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002178 if (writer == NULL)
2179 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002180 if (flags & Py_PRINT_RAW) {
2181 if (PyUnicode_Check(v)) {
2182 value = v;
2183 Py_INCREF(value);
2184 } else
2185 value = PyObject_Str(v);
2186 }
2187 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002189 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002190 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002191 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002192 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002193 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002194 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 Py_DECREF(value);
2196 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002197 return -1;
2198 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 result = PyEval_CallObject(writer, args);
2200 Py_DECREF(args);
2201 Py_DECREF(value);
2202 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002203 if (result == NULL)
2204 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002205 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002206 return 0;
2207}
2208
Guido van Rossum27a60b11997-05-22 22:25:11 +00002209int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002210PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002211{
2212 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002213 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002214 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002215 PyErr_SetString(PyExc_SystemError,
2216 "null file for PyFile_WriteString");
2217 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002218 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002219 else if (PyFile_Check(f)) {
2220 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002221 if (fp == NULL) {
2222 err_closed();
2223 return -1;
2224 }
2225 fputs(s, fp);
2226 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002227 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002228 else if (!PyErr_Occurred()) {
2229 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002230 int err;
2231 if (v == NULL)
2232 return -1;
2233 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2234 Py_DECREF(v);
2235 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002236 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002237 else
2238 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002239}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002240
2241/* Try to get a file-descriptor from a Python object. If the object
2242 is an integer or long integer, its value is returned. If not, the
2243 object's fileno() method is called if it exists; the method must return
2244 an integer or long integer, which is returned as the file descriptor value.
2245 -1 is returned on failure.
2246*/
2247
2248int PyObject_AsFileDescriptor(PyObject *o)
2249{
2250 int fd;
2251 PyObject *meth;
2252
2253 if (PyInt_Check(o)) {
2254 fd = PyInt_AsLong(o);
2255 }
2256 else if (PyLong_Check(o)) {
2257 fd = PyLong_AsLong(o);
2258 }
2259 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2260 {
2261 PyObject *fno = PyEval_CallObject(meth, NULL);
2262 Py_DECREF(meth);
2263 if (fno == NULL)
2264 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002265
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002266 if (PyInt_Check(fno)) {
2267 fd = PyInt_AsLong(fno);
2268 Py_DECREF(fno);
2269 }
2270 else if (PyLong_Check(fno)) {
2271 fd = PyLong_AsLong(fno);
2272 Py_DECREF(fno);
2273 }
2274 else {
2275 PyErr_SetString(PyExc_TypeError,
2276 "fileno() returned a non-integer");
2277 Py_DECREF(fno);
2278 return -1;
2279 }
2280 }
2281 else {
2282 PyErr_SetString(PyExc_TypeError,
2283 "argument must be an int, or have a fileno() method.");
2284 return -1;
2285 }
2286
2287 if (fd < 0) {
2288 PyErr_Format(PyExc_ValueError,
2289 "file descriptor cannot be a negative integer (%i)",
2290 fd);
2291 return -1;
2292 }
2293 return fd;
2294}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002295
Jack Jansen7b8c7542002-04-14 20:12:41 +00002296/* From here on we need access to the real fgets and fread */
2297#undef fgets
2298#undef fread
2299
2300/*
2301** Py_UniversalNewlineFgets is an fgets variation that understands
2302** all of \r, \n and \r\n conventions.
2303** The stream should be opened in binary mode.
2304** If fobj is NULL the routine always does newline conversion, and
2305** it may peek one char ahead to gobble the second char in \r\n.
2306** If fobj is non-NULL it must be a PyFileObject. In this case there
2307** is no readahead but in stead a flag is used to skip a following
2308** \n on the next read. Also, if the file is open in binary mode
2309** the whole conversion is skipped. Finally, the routine keeps track of
2310** the different types of newlines seen.
2311** Note that we need no error handling: fgets() treats error and eof
2312** identically.
2313*/
2314char *
2315Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2316{
2317 char *p = buf;
2318 int c;
2319 int newlinetypes = 0;
2320 int skipnextlf = 0;
2321 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002322
Jack Jansen7b8c7542002-04-14 20:12:41 +00002323 if (fobj) {
2324 if (!PyFile_Check(fobj)) {
2325 errno = ENXIO; /* What can you do... */
2326 return NULL;
2327 }
2328 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2329 if ( !univ_newline )
2330 return fgets(buf, n, stream);
2331 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2332 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2333 }
2334 FLOCKFILE(stream);
2335 c = 'x'; /* Shut up gcc warning */
2336 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2337 if (skipnextlf ) {
2338 skipnextlf = 0;
2339 if (c == '\n') {
2340 /* Seeing a \n here with skipnextlf true
2341 ** means we saw a \r before.
2342 */
2343 newlinetypes |= NEWLINE_CRLF;
2344 c = GETC(stream);
2345 if (c == EOF) break;
2346 } else {
2347 /*
2348 ** Note that c == EOF also brings us here,
2349 ** so we're okay if the last char in the file
2350 ** is a CR.
2351 */
2352 newlinetypes |= NEWLINE_CR;
2353 }
2354 }
2355 if (c == '\r') {
2356 /* A \r is translated into a \n, and we skip
2357 ** an adjacent \n, if any. We don't set the
2358 ** newlinetypes flag until we've seen the next char.
2359 */
2360 skipnextlf = 1;
2361 c = '\n';
2362 } else if ( c == '\n') {
2363 newlinetypes |= NEWLINE_LF;
2364 }
2365 *p++ = c;
2366 if (c == '\n') break;
2367 }
2368 if ( c == EOF && skipnextlf )
2369 newlinetypes |= NEWLINE_CR;
2370 FUNLOCKFILE(stream);
2371 *p = '\0';
2372 if (fobj) {
2373 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2374 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2375 } else if ( skipnextlf ) {
2376 /* If we have no file object we cannot save the
2377 ** skipnextlf flag. We have to readahead, which
2378 ** will cause a pause if we're reading from an
2379 ** interactive stream, but that is very unlikely
2380 ** unless we're doing something silly like
2381 ** execfile("/dev/tty").
2382 */
2383 c = GETC(stream);
2384 if ( c != '\n' )
2385 ungetc(c, stream);
2386 }
2387 if (p == buf)
2388 return NULL;
2389 return buf;
2390}
2391
2392/*
2393** Py_UniversalNewlineFread is an fread variation that understands
2394** all of \r, \n and \r\n conventions.
2395** The stream should be opened in binary mode.
2396** fobj must be a PyFileObject. In this case there
2397** is no readahead but in stead a flag is used to skip a following
2398** \n on the next read. Also, if the file is open in binary mode
2399** the whole conversion is skipped. Finally, the routine keeps track of
2400** the different types of newlines seen.
2401*/
2402size_t
Tim Peters058b1412002-04-21 07:29:14 +00002403Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002404 FILE *stream, PyObject *fobj)
2405{
Tim Peters058b1412002-04-21 07:29:14 +00002406 char *dst = buf;
2407 PyFileObject *f = (PyFileObject *)fobj;
2408 int newlinetypes, skipnextlf;
2409
2410 assert(buf != NULL);
2411 assert(stream != NULL);
2412
Jack Jansen7b8c7542002-04-14 20:12:41 +00002413 if (!fobj || !PyFile_Check(fobj)) {
2414 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002415 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002416 }
Tim Peters058b1412002-04-21 07:29:14 +00002417 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002418 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002419 newlinetypes = f->f_newlinetypes;
2420 skipnextlf = f->f_skipnextlf;
2421 /* Invariant: n is the number of bytes remaining to be filled
2422 * in the buffer.
2423 */
2424 while (n) {
2425 size_t nread;
2426 int shortread;
2427 char *src = dst;
2428
2429 nread = fread(dst, 1, n, stream);
2430 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002431 if (nread == 0)
2432 break;
2433
Tim Peterse1682a82002-04-21 18:15:20 +00002434 n -= nread; /* assuming 1 byte out for each in; will adjust */
2435 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002436 while (nread--) {
2437 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002438 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002439 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002440 *dst++ = '\n';
2441 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002442 }
2443 else if (skipnextlf && c == '\n') {
2444 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002445 skipnextlf = 0;
2446 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002447 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002448 }
2449 else {
2450 /* Normal char to be stored in buffer. Also
2451 * update the newlinetypes flag if either this
2452 * is an LF or the previous char was a CR.
2453 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002454 if (c == '\n')
2455 newlinetypes |= NEWLINE_LF;
2456 else if (skipnextlf)
2457 newlinetypes |= NEWLINE_CR;
2458 *dst++ = c;
2459 skipnextlf = 0;
2460 }
2461 }
Tim Peters058b1412002-04-21 07:29:14 +00002462 if (shortread) {
2463 /* If this is EOF, update type flags. */
2464 if (skipnextlf && feof(stream))
2465 newlinetypes |= NEWLINE_CR;
2466 break;
2467 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002468 }
Tim Peters058b1412002-04-21 07:29:14 +00002469 f->f_newlinetypes = newlinetypes;
2470 f->f_skipnextlf = skipnextlf;
2471 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002472}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002473
2474#ifdef __cplusplus
2475}
2476#endif