blob: 1de520b1629baeb3ef9e33fc724a79333fb422ef [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossumff7e83d1999-08-27 20:39:37 +00006#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00007#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00008#endif /* DONT_HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +00009
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000010#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000011#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000012/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000013#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000014#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000015#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000016#endif
17
Mark Hammondc2e85bd2002-10-03 05:10:39 +000018#ifdef _MSC_VER
19/* Need GetVersion to see if on NT so safe to use _wfopen */
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22#endif /* _MSC_VER */
23
Andrew MacIntyrec4874392002-02-26 11:36:35 +000024#if defined(PYOS_OS2) && defined(PYCC_GCC)
25#include <io.h>
26#endif
27
Guido van Rossumc0b618a1997-05-02 03:12:38 +000028#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000029
Guido van Rossumff7e83d1999-08-27 20:39:37 +000030#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000031#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000032#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000033
Jack Jansen7b8c7542002-04-14 20:12:41 +000034#ifdef HAVE_GETC_UNLOCKED
35#define GETC(f) getc_unlocked(f)
36#define FLOCKFILE(f) flockfile(f)
37#define FUNLOCKFILE(f) funlockfile(f)
38#else
39#define GETC(f) getc(f)
40#define FLOCKFILE(f)
41#define FUNLOCKFILE(f)
42#endif
43
Jack Jansen7b8c7542002-04-14 20:12:41 +000044/* Bits in f_newlinetypes */
45#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
46#define NEWLINE_CR 1 /* \r newline seen */
47#define NEWLINE_LF 2 /* \n newline seen */
48#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000049
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000050FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000051PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000053 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000055 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000056 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057}
58
Guido van Rossumc0b618a1997-05-02 03:12:38 +000059PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000060PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000063 return NULL;
64 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066}
67
Neil Schemenauered19b882002-03-23 02:06:50 +000068/* On Unix, fopen will succeed for directories.
69 In Python, there should be no file objects referring to
70 directories, so we need a check. */
71
72static PyFileObject*
73dircheck(PyFileObject* f)
74{
75#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
76 struct stat buf;
77 if (f->f_fp == NULL)
78 return f;
79 if (fstat(fileno(f->f_fp), &buf) == 0 &&
80 S_ISDIR(buf.st_mode)) {
81#ifdef HAVE_STRERROR
82 char *msg = strerror(EISDIR);
83#else
84 char *msg = "Is a directory";
85#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000086 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000087 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000088 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000089 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000090 return NULL;
91 }
92#endif
93 return f;
94}
95
Tim Peters59c9a642001-09-13 05:38:56 +000096
97static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +000098fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
99 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100{
Tim Peters59c9a642001-09-13 05:38:56 +0000101 assert(f != NULL);
102 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000103 assert(f->f_fp == NULL);
104
105 Py_DECREF(f->f_name);
106 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000107 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000108
109 Py_INCREF (name);
110 f->f_name = name;
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000113
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000114 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000115 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000116 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000117 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000118 f->f_univ_newline = (strchr(mode, 'U') != NULL);
119 f->f_newlinetypes = NEWLINE_UNKNOWN;
120 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000121 Py_INCREF(Py_None);
122 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000123
Tim Peters59c9a642001-09-13 05:38:56 +0000124 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000127 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000128 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129}
130
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000131/* check for known incorrect mode strings - problem is, platforms are
132 free to accept any mode characters they like and are supposed to
133 ignore stuff they don't understand... write or append mode with
134 universal newline support is expressly forbidden by PEP 278. */
135/* zero return is kewl - one is un-kewl */
136static int
137check_the_mode(char *mode)
138{
139 unsigned int len = strlen(mode);
140
141 switch (len) {
142 case 0:
143 PyErr_SetString(PyExc_ValueError, "empty mode string");
144 return 1;
145
146 /* reject wU, aU */
147 case 2:
148 switch (mode[0]) {
149 case 'w':
150 case 'a':
151 if (mode[1] == 'U') {
152 PyErr_SetString(PyExc_ValueError,
153 "invalid mode string");
154 return 1;
155 }
156 break;
157 }
158 break;
159
160 /* reject w+U, a+U, wU+, aU+ */
161 case 3:
162 switch (mode[0]) {
163 case 'w':
164 case 'a':
165 if ((mode[1] == '+' && mode[2] == 'U') ||
166 (mode[1] == 'U' && mode[2] == '+')) {
167 PyErr_SetString(PyExc_ValueError,
168 "invalid mode string");
169 return 1;
170 }
171 break;
172 }
173 break;
174 }
175
176 return 0;
177}
178
Tim Peters59c9a642001-09-13 05:38:56 +0000179static PyObject *
180open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181{
Tim Peters59c9a642001-09-13 05:38:56 +0000182 assert(f != NULL);
183 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000184#ifdef MS_WINDOWS
185 /* windows ignores the passed name in order to support Unicode */
186 assert(f->f_name != NULL);
187#else
Tim Peters59c9a642001-09-13 05:38:56 +0000188 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000189#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000190 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000191 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000192
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000193 if (check_the_mode(mode))
194 return NULL;
195
Tim Peters8fa45672001-09-13 21:01:29 +0000196 /* rexec.py can't stop a user from getting the file() constructor --
197 all they have to do is get *any* file object f, and then do
198 type(f). Here we prevent them from doing damage with it. */
199 if (PyEval_GetRestricted()) {
200 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000201 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000202 return NULL;
203 }
Tim Petersa27a1502001-11-09 20:59:14 +0000204 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000205
206 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
207 mode = "rb";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000208#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000209 if (PyUnicode_Check(f->f_name)) {
210 PyObject *wmode;
211 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
212 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000213 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000214 /* PyUnicode_AS_UNICODE OK without thread
215 lock as it is a simple dereference. */
216 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
217 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000218 Py_END_ALLOW_THREADS
219 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000220 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000221 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000222#endif
223 if (NULL == f->f_fp && NULL != name) {
224 Py_BEGIN_ALLOW_THREADS
225 f->f_fp = fopen(name, mode);
226 Py_END_ALLOW_THREADS
227 }
228
Guido van Rossuma08095a1991-02-13 23:25:27 +0000229 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000230#ifdef _MSC_VER
231 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
232 * across all Windows flavors. When it sets EINVAL varies
233 * across Windows flavors, the exact conditions aren't
234 * documented, and the answer lies in the OS's implementation
235 * of Win32's CreateFile function (whose source is secret).
236 * Seems the best we can do is map EINVAL to ENOENT.
237 */
238 if (errno == 0) /* bad mode string */
239 errno = EINVAL;
240 else if (errno == EINVAL) /* unknown, but not a mode string */
241 errno = ENOENT;
242#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000243 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000244 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000245 mode);
246 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000247 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000248 f = NULL;
249 }
Tim Peters2ea91112002-04-08 04:13:12 +0000250 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000251 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000252 return (PyObject *)f;
253}
254
255PyObject *
256PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
257{
Tim Peters44410012001-09-14 03:26:08 +0000258 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
259 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000260 if (f != NULL) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000261 PyObject *o_name = PyString_FromString(name);
262 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000263 Py_DECREF(f);
264 f = NULL;
265 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000266 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000267 }
268 return (PyObject *) f;
269}
270
271PyObject *
272PyFile_FromString(char *name, char *mode)
273{
274 extern int fclose(FILE *);
275 PyFileObject *f;
276
277 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
278 if (f != NULL) {
279 if (open_the_file(f, name, mode) == NULL) {
280 Py_DECREF(f);
281 f = NULL;
282 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000284 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285}
286
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287void
Fred Drakefd99de62000-07-09 05:02:18 +0000288PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000289{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000290 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000291 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292 int type;
293 switch (bufsize) {
294 case 0:
295 type = _IONBF;
296 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000297#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000298 case 1:
299 type = _IOLBF;
300 bufsize = BUFSIZ;
301 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000302#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303 default:
304 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000305#ifndef HAVE_SETVBUF
306 bufsize = BUFSIZ;
307#endif
308 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000309 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000310 fflush(file->f_fp);
311 if (type == _IONBF) {
312 PyMem_Free(file->f_setbuf);
313 file->f_setbuf = NULL;
314 } else {
315 file->f_setbuf = PyMem_Realloc(file->f_setbuf, bufsize);
316 }
317#ifdef HAVE_SETVBUF
318 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000319#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000320 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000321#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000322 }
323}
324
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000325/* Set the encoding used to output Unicode strings.
326 Returh 1 on success, 0 on failure. */
327
328int
329PyFile_SetEncoding(PyObject *f, const char *enc)
330{
331 PyFileObject *file = (PyFileObject*)f;
332 PyObject *str = PyString_FromString(enc);
333 if (!str)
334 return 0;
335 Py_DECREF(file->f_encoding);
336 file->f_encoding = str;
337 return 1;
338}
339
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000341err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000342{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000344 return NULL;
345}
346
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000347static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000348
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349/* Methods */
350
351static void
Fred Drakefd99de62000-07-09 05:02:18 +0000352file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000354 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000355 if (f->weakreflist != NULL)
356 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000357 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000359 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000361 if (sts == EOF)
362#ifdef HAVE_STRERROR
363 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
364#else
365 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
366#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000367 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000368 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000369 Py_XDECREF(f->f_name);
370 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000371 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000372 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000373 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374}
375
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000376static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000377file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000379 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000380#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000381 PyObject *ret = NULL;
382 PyObject *name;
383 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
384 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
385 f->f_fp == NULL ? "closed" : "open",
386 PyString_AsString(name),
387 PyString_AsString(f->f_mode),
388 f);
389 Py_XDECREF(name);
390 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000391#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000392 } else {
393 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394 f->f_fp == NULL ? "closed" : "open",
395 PyString_AsString(f->f_name),
396 PyString_AsString(f->f_mode),
397 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000398 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000401static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000402file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000404 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000405 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000406 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000408 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000409 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000411 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412 f->f_fp = NULL;
413 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000414 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000415 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000416 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000417 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000418 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419 return PyInt_FromLong((long)sts);
420 Py_INCREF(Py_None);
421 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422}
423
Trent Mickf29f47b2000-08-11 19:02:59 +0000424
Guido van Rossumb8552162001-09-05 14:58:11 +0000425/* Our very own off_t-like type, 64-bit if possible */
426#if !defined(HAVE_LARGEFILE_SUPPORT)
427typedef off_t Py_off_t;
428#elif SIZEOF_OFF_T >= 8
429typedef off_t Py_off_t;
430#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000431typedef fpos_t Py_off_t;
432#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000433#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000434#endif
435
436
Trent Mickf29f47b2000-08-11 19:02:59 +0000437/* a portable fseek() function
438 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000439static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000440_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000441{
Guido van Rossumb8552162001-09-05 14:58:11 +0000442#if !defined(HAVE_LARGEFILE_SUPPORT)
443 return fseek(fp, offset, whence);
444#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000445 return fseeko(fp, offset, whence);
446#elif defined(HAVE_FSEEK64)
447 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000448#elif defined(__BEOS__)
449 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000450#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000451 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
452 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000453 fpos_t pos;
454 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000455 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000456#ifdef MS_WINDOWS
457 fflush(fp);
458 if (_lseeki64(fileno(fp), 0, 2) == -1)
459 return -1;
460#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000461 if (fseek(fp, 0, SEEK_END) != 0)
462 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000463#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000464 /* fall through */
465 case SEEK_CUR:
466 if (fgetpos(fp, &pos) != 0)
467 return -1;
468 offset += pos;
469 break;
470 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000471 }
472 return fsetpos(fp, &offset);
473#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000474#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000475#endif
476}
477
478
479/* a portable ftell() function
480 Return -1 on failure with errno set appropriately, current file
481 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000482static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000483_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000484{
Hye-Shik Change237d502005-12-13 16:44:02 +0000485#ifdef HAVE_BROKEN_FTELL
486 /* ftell doesn't fail for tty fds on FreeBSD and some others */
487 if (isatty(fileno(fp))) {
488 errno = ESPIPE;
489 return -1;
490 }
491#endif
Guido van Rossumb8552162001-09-05 14:58:11 +0000492#if !defined(HAVE_LARGEFILE_SUPPORT)
493 return ftell(fp);
494#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
495 return ftello(fp);
496#elif defined(HAVE_FTELL64)
497 return ftell64(fp);
498#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000499 fpos_t pos;
500 if (fgetpos(fp, &pos) != 0)
501 return -1;
502 return pos;
503#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000504#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000505#endif
506}
507
508
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000510file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000511{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000512 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000513 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000514 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000515 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000516
Guido van Rossumd7297e61992-07-06 14:19:26 +0000517 if (f->f_fp == NULL)
518 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000519 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000520 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000521 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000522 return NULL;
523#if !defined(HAVE_LARGEFILE_SUPPORT)
524 offset = PyInt_AsLong(offobj);
525#else
526 offset = PyLong_Check(offobj) ?
527 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
528#endif
529 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000530 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000531
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000533 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000534 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000536
Guido van Rossumff4949e1992-08-05 19:58:53 +0000537 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000539 clearerr(f->f_fp);
540 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000541 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000542 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 Py_INCREF(Py_None);
544 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000545}
546
Trent Mickf29f47b2000-08-11 19:02:59 +0000547
Guido van Rossumd7047b31995-01-02 19:07:15 +0000548#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000550file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000551{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000552 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000553 PyObject *newsizeobj = NULL;
554 Py_off_t initialpos;
555 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000556
Guido van Rossumd7047b31995-01-02 19:07:15 +0000557 if (f->f_fp == NULL)
558 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000559 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000560 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000561
Tim Petersf1827cf2003-09-07 03:30:18 +0000562 /* Get current file position. If the file happens to be open for
563 * update and the last operation was an input operation, C doesn't
564 * define what the later fflush() will do, but we promise truncate()
565 * won't change the current position (and fflush() *does* change it
566 * then at least on Windows). The easiest thing is to capture
567 * current pos now and seek back to it at the end.
568 */
569 Py_BEGIN_ALLOW_THREADS
570 errno = 0;
571 initialpos = _portable_ftell(f->f_fp);
572 Py_END_ALLOW_THREADS
573 if (initialpos == -1)
574 goto onioerror;
575
Tim Petersfb05db22002-03-11 00:24:00 +0000576 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000577 * specified value.
578 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000579 if (newsizeobj != NULL) {
580#if !defined(HAVE_LARGEFILE_SUPPORT)
581 newsize = PyInt_AsLong(newsizeobj);
582#else
583 newsize = PyLong_Check(newsizeobj) ?
584 PyLong_AsLongLong(newsizeobj) :
585 PyInt_AsLong(newsizeobj);
586#endif
587 if (PyErr_Occurred())
588 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000589 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000590 else /* default to current position */
591 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000592
Tim Petersf1827cf2003-09-07 03:30:18 +0000593 /* Flush the stream. We're mixing stream-level I/O with lower-level
594 * I/O, and a flush may be necessary to synch both platform views
595 * of the current file state.
596 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000597 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000598 errno = 0;
599 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000600 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000601 if (ret != 0)
602 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000603
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000604#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000605 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000606 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000607 {
Tim Petersfb05db22002-03-11 00:24:00 +0000608 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000609
Tim Petersf1827cf2003-09-07 03:30:18 +0000610 /* Have to move current pos to desired endpoint on Windows. */
611 Py_BEGIN_ALLOW_THREADS
612 errno = 0;
613 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
614 Py_END_ALLOW_THREADS
615 if (ret)
616 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000617
Tim Peters8f01b682002-03-12 03:04:44 +0000618 /* Truncate. Note that this may grow the file! */
619 Py_BEGIN_ALLOW_THREADS
620 errno = 0;
621 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000622 ret = hFile == (HANDLE)-1;
623 if (ret == 0) {
624 ret = SetEndOfFile(hFile) == 0;
625 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000626 errno = EACCES;
627 }
628 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000629 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000630 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000631 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000632#else
633 Py_BEGIN_ALLOW_THREADS
634 errno = 0;
635 ret = ftruncate(fileno(f->f_fp), newsize);
636 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000637 if (ret != 0)
638 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000639#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000640
Tim Petersf1827cf2003-09-07 03:30:18 +0000641 /* Restore original file position. */
642 Py_BEGIN_ALLOW_THREADS
643 errno = 0;
644 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
645 Py_END_ALLOW_THREADS
646 if (ret)
647 goto onioerror;
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649 Py_INCREF(Py_None);
650 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000651
652onioerror:
653 PyErr_SetFromErrno(PyExc_IOError);
654 clearerr(f->f_fp);
655 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000656}
657#endif /* HAVE_FTRUNCATE */
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000660file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000661{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000662 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000663
Guido van Rossumd7297e61992-07-06 14:19:26 +0000664 if (f->f_fp == NULL)
665 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000667 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000668 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000670 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000672 clearerr(f->f_fp);
673 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000674 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000675 if (f->f_skipnextlf) {
676 int c;
677 c = GETC(f->f_fp);
678 if (c == '\n') {
679 pos++;
680 f->f_skipnextlf = 0;
681 } else if (c != EOF) ungetc(c, f->f_fp);
682 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000683#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000684 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000685#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000686 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000687#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000688}
689
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000690static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000691file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000692{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000693 if (f->f_fp == NULL)
694 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000695 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000696}
697
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000698static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000699file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000700{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000701 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000702
Guido van Rossumd7297e61992-07-06 14:19:26 +0000703 if (f->f_fp == NULL)
704 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000706 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000707 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000709 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000710 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000711 clearerr(f->f_fp);
712 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000713 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 Py_INCREF(Py_None);
715 return Py_None;
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_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000720{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000721 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000722 if (f->f_fp == NULL)
723 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000725 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000726 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000727 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000728}
729
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000730
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000731#if BUFSIZ < 8192
732#define SMALLCHUNK 8192
733#else
734#define SMALLCHUNK BUFSIZ
735#endif
736
Guido van Rossum3c259041999-01-14 19:00:14 +0000737#if SIZEOF_INT < 4
738#define BIGCHUNK (512 * 32)
739#else
740#define BIGCHUNK (512 * 1024)
741#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000742
743static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000744new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000745{
746#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000747 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000748 struct stat st;
749 if (fstat(fileno(f->f_fp), &st) == 0) {
750 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000751 /* The following is not a bug: we really need to call lseek()
752 *and* ftell(). The reason is that some stdio libraries
753 mistakenly flush their buffer when ftell() is called and
754 the lseek() call it makes fails, thereby throwing away
755 data that cannot be recovered in any way. To avoid this,
756 we first test lseek(), and only call ftell() if lseek()
757 works. We can't use the lseek() value either, because we
758 need to take the amount of buffered data into account.
759 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000760 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000761 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000762 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000763 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000764 if (pos < 0)
765 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000766 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000767 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000768 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000769 }
770#endif
771 if (currentsize > SMALLCHUNK) {
772 /* Keep doubling until we reach BIGCHUNK;
773 then keep adding BIGCHUNK. */
774 if (currentsize <= BIGCHUNK)
775 return currentsize + currentsize;
776 else
777 return currentsize + BIGCHUNK;
778 }
779 return currentsize + SMALLCHUNK;
780}
781
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000782#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
783#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
784#else
785#ifdef EWOULDBLOCK
786#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
787#else
788#ifdef EAGAIN
789#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
790#else
791#define BLOCKED_ERRNO(x) 0
792#endif
793#endif
794#endif
795
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000796static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000797file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000798{
Guido van Rossum789a1611997-05-10 22:33:55 +0000799 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000800 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000801 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000802
Guido van Rossumd7297e61992-07-06 14:19:26 +0000803 if (f->f_fp == NULL)
804 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000805 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000806 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000807 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000808 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000809 else
810 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000811 if (buffersize > INT_MAX) {
812 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000813 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000814 return NULL;
815 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000816 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000817 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000818 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000819 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000820 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000821 Py_BEGIN_ALLOW_THREADS
822 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000823 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000824 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000825 Py_END_ALLOW_THREADS
826 if (chunksize == 0) {
827 if (!ferror(f->f_fp))
828 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000829 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000830 /* When in non-blocking mode, data shouldn't
831 * be discarded if a blocking signal was
832 * received. That will also happen if
833 * chunksize != 0, but bytesread < buffersize. */
834 if (bytesread > 0 && BLOCKED_ERRNO(errno))
835 break;
836 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000837 Py_DECREF(v);
838 return NULL;
839 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000840 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000841 if (bytesread < buffersize) {
842 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000843 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000844 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000845 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000846 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000847 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000848 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000849 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000850 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000851 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000852 }
853 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000854 if (bytesread != buffersize)
855 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000856 return v;
857}
858
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000859static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000860file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000861{
862 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000863 int ntodo;
864 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000865
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000866 if (f->f_fp == NULL)
867 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000868 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000869 return NULL;
870 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000871 while (ntodo > 0) {
872 Py_BEGIN_ALLOW_THREADS
873 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000874 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000875 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000876 Py_END_ALLOW_THREADS
877 if (nnow == 0) {
878 if (!ferror(f->f_fp))
879 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000880 PyErr_SetFromErrno(PyExc_IOError);
881 clearerr(f->f_fp);
882 return NULL;
883 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000884 ndone += nnow;
885 ntodo -= nnow;
886 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000887 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000888}
889
Tim Peters86821b22001-01-07 21:19:34 +0000890/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000891Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000892
893Under MSVC 6:
894
Tim Peters1c733232001-01-08 04:02:07 +0000895+ MS threadsafe getc is very slow (multiple layers of function calls before+
896 after each character, to lock+unlock the stream).
897+ The stream-locking functions are MS-internal -- can't access them from user
898 code.
899+ There's nothing Tim could find in the MS C or platform SDK libraries that
900 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000901+ MS fgets locks/unlocks only once per line; it's the only hook we have.
902
903So we use fgets for speed(!), despite that it's painful.
904
905MS realloc is also slow.
906
Tim Petersf29b64d2001-01-15 06:33:19 +0000907Reports from other platforms on this method vs getc_unlocked (which MS doesn't
908have):
909 Linux a wash
910 Solaris a wash
911 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000912
Tim Petersf29b64d2001-01-15 06:33:19 +0000913CAUTION: The C std isn't clear about this: in those cases where fgets
914writes something into the buffer, can it write into any position beyond the
915required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
916known on which it does; and it would be a strange way to code fgets. Still,
917getline_via_fgets may not work correctly if it does. The std test
918test_bufio.py should fail if platform fgets() routinely writes beyond the
919trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000920**************************************************************************/
921
Tim Petersf29b64d2001-01-15 06:33:19 +0000922/* Use this routine if told to, or by default on non-get_unlocked()
923 * platforms unless told not to. Yikes! Let's spell that out:
924 * On a platform with getc_unlocked():
925 * By default, use getc_unlocked().
926 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
927 * On a platform without getc_unlocked():
928 * By default, use fgets().
929 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
930 */
931#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
932#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000933#endif
934
Tim Petersf29b64d2001-01-15 06:33:19 +0000935#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
936#undef USE_FGETS_IN_GETLINE
937#endif
938
939#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000940static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000941getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000942{
Tim Peters15b83852001-01-08 00:53:12 +0000943/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000944 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
945 * to fill this much of the buffer with a known value in order to figure out
946 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
947 * than "most" lines, we waste time filling unused buffer slots. 100 is
948 * surely adequate for most peoples' email archives, chewing over source code,
949 * etc -- "regular old text files".
950 * MAXBUFSIZE is the maximum line length that lets us get away with the less
951 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
952 * cautions about boosting that. 300 was chosen because the worst real-life
953 * text-crunching job reported on Python-Dev was a mail-log crawler where over
954 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000955 */
Tim Peters142297a2001-01-15 10:36:56 +0000956#define INITBUFSIZE 100
957#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000958 char* p; /* temp */
959 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000960 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000961 char* pvfree; /* address of next free slot */
962 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000963 size_t nfree; /* # of free buffer slots; pvend-pvfree */
964 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000965 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000966
Tim Peters15b83852001-01-08 00:53:12 +0000967 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000968 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000969 */
Tim Peters142297a2001-01-15 10:36:56 +0000970 total_v_size = INITBUFSIZE; /* start small and pray */
971 pvfree = buf;
972 for (;;) {
973 Py_BEGIN_ALLOW_THREADS
974 pvend = buf + total_v_size;
975 nfree = pvend - pvfree;
976 memset(pvfree, '\n', nfree);
977 p = fgets(pvfree, nfree, fp);
978 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000979
Tim Peters142297a2001-01-15 10:36:56 +0000980 if (p == NULL) {
981 clearerr(fp);
982 if (PyErr_CheckSignals())
983 return NULL;
984 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000985 return v;
986 }
Tim Peters142297a2001-01-15 10:36:56 +0000987 /* fgets read *something* */
988 p = memchr(pvfree, '\n', nfree);
989 if (p != NULL) {
990 /* Did the \n come from fgets or from us?
991 * Since fgets stops at the first \n, and then writes
992 * \0, if it's from fgets a \0 must be next. But if
993 * that's so, it could not have come from us, since
994 * the \n's we filled the buffer with have only more
995 * \n's to the right.
996 */
997 if (p+1 < pvend && *(p+1) == '\0') {
998 /* It's from fgets: we win! In particular,
999 * we haven't done any mallocs yet, and can
1000 * build the final result on the first try.
1001 */
1002 ++p; /* include \n from fgets */
1003 }
1004 else {
1005 /* Must be from us: fgets didn't fill the
1006 * buffer and didn't find a newline, so it
1007 * must be the last and newline-free line of
1008 * the file.
1009 */
1010 assert(p > pvfree && *(p-1) == '\0');
1011 --p; /* don't include \0 from fgets */
1012 }
1013 v = PyString_FromStringAndSize(buf, p - buf);
1014 return v;
1015 }
1016 /* yuck: fgets overwrote all the newlines, i.e. the entire
1017 * buffer. So this line isn't over yet, or maybe it is but
1018 * we're exactly at EOF. If we haven't already, try using the
1019 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001020 */
Tim Peters142297a2001-01-15 10:36:56 +00001021 assert(*(pvend-1) == '\0');
1022 if (pvfree == buf) {
1023 pvfree = pvend - 1; /* overwrite trailing null */
1024 total_v_size = MAXBUFSIZE;
1025 }
1026 else
1027 break;
Tim Peters86821b22001-01-07 21:19:34 +00001028 }
Tim Peters142297a2001-01-15 10:36:56 +00001029
1030 /* The stack buffer isn't big enough; malloc a string object and read
1031 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001032 */
Tim Petersddea2082002-03-23 10:03:50 +00001033 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001034 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001035 if (v == NULL)
1036 return v;
1037 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001038 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1039 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001040
1041 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001042 * after setting p one beyond the end of the line. The code here is
1043 * very much like the code above, except reads into v's buffer; see
1044 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001045 */
1046 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001047 Py_BEGIN_ALLOW_THREADS
1048 pvend = BUF(v) + total_v_size;
1049 nfree = pvend - pvfree;
1050 memset(pvfree, '\n', nfree);
1051 p = fgets(pvfree, nfree, fp);
1052 Py_END_ALLOW_THREADS
1053
1054 if (p == NULL) {
1055 clearerr(fp);
1056 if (PyErr_CheckSignals()) {
1057 Py_DECREF(v);
1058 return NULL;
1059 }
1060 p = pvfree;
1061 break;
1062 }
Tim Peters86821b22001-01-07 21:19:34 +00001063 p = memchr(pvfree, '\n', nfree);
1064 if (p != NULL) {
1065 if (p+1 < pvend && *(p+1) == '\0') {
1066 /* \n came from fgets */
1067 ++p;
1068 break;
1069 }
1070 /* \n came from us; last line of file, no newline */
1071 assert(p > pvfree && *(p-1) == '\0');
1072 --p;
1073 break;
1074 }
1075 /* expand buffer and try again */
1076 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001077 increment = total_v_size >> 2; /* mild exponential growth */
1078 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001079 if (total_v_size > INT_MAX) {
1080 PyErr_SetString(PyExc_OverflowError,
1081 "line is longer than a Python string can hold");
1082 Py_DECREF(v);
1083 return NULL;
1084 }
1085 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1086 return NULL;
1087 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001088 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001089 }
1090 if (BUF(v) + total_v_size != p)
1091 _PyString_Resize(&v, p - BUF(v));
1092 return v;
1093#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001094#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001095}
Tim Petersf29b64d2001-01-15 06:33:19 +00001096#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001097
Guido van Rossum0bd24411991-04-04 15:21:57 +00001098/* Internal routine to get a line.
1099 Size argument interpretation:
1100 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001101 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001102*/
1103
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001104static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001105get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001106{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001107 FILE *fp = f->f_fp;
1108 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001109 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001110 size_t total_v_size; /* total # of slots in buffer */
1111 size_t used_v_size; /* # used slots in buffer */
1112 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001113 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001114 int newlinetypes = f->f_newlinetypes;
1115 int skipnextlf = f->f_skipnextlf;
1116 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001117
Jack Jansen7b8c7542002-04-14 20:12:41 +00001118#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001119 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001120 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001121#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001122 total_v_size = n > 0 ? n : 100;
1123 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001124 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001125 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001126 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001127 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001128
Guido van Rossumce5ba841991-03-06 13:06:18 +00001129 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001130 Py_BEGIN_ALLOW_THREADS
1131 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001132 if (univ_newline) {
1133 c = 'x'; /* Shut up gcc warning */
1134 while ( buf != end && (c = GETC(fp)) != EOF ) {
1135 if (skipnextlf ) {
1136 skipnextlf = 0;
1137 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001138 /* Seeing a \n here with
1139 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001140 * saw a \r before.
1141 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001142 newlinetypes |= NEWLINE_CRLF;
1143 c = GETC(fp);
1144 if (c == EOF) break;
1145 } else {
1146 newlinetypes |= NEWLINE_CR;
1147 }
1148 }
1149 if (c == '\r') {
1150 skipnextlf = 1;
1151 c = '\n';
1152 } else if ( c == '\n')
1153 newlinetypes |= NEWLINE_LF;
1154 *buf++ = c;
1155 if (c == '\n') break;
1156 }
1157 if ( c == EOF && skipnextlf )
1158 newlinetypes |= NEWLINE_CR;
1159 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001160 while ((c = GETC(fp)) != EOF &&
1161 (*buf++ = c) != '\n' &&
1162 buf != end)
1163 ;
1164 FUNLOCKFILE(fp);
1165 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001166 f->f_newlinetypes = newlinetypes;
1167 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001168 if (c == '\n')
1169 break;
1170 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001171 if (ferror(fp)) {
1172 PyErr_SetFromErrno(PyExc_IOError);
1173 clearerr(fp);
1174 Py_DECREF(v);
1175 return NULL;
1176 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001177 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001178 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001179 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001180 return NULL;
1181 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001182 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001183 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001184 /* Must be because buf == end */
1185 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001186 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001187 used_v_size = total_v_size;
1188 increment = total_v_size >> 2; /* mild exponential growth */
1189 total_v_size += increment;
1190 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001191 PyErr_SetString(PyExc_OverflowError,
1192 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001193 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001194 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001195 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001196 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001197 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001198 buf = BUF(v) + used_v_size;
1199 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001200 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001201
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001202 used_v_size = buf - BUF(v);
1203 if (used_v_size != total_v_size)
1204 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001205 return v;
1206}
1207
Guido van Rossum0bd24411991-04-04 15:21:57 +00001208/* External C interface */
1209
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001210PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001211PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001212{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001213 PyObject *result;
1214
Guido van Rossum3165fe61992-09-25 21:59:05 +00001215 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001216 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001217 return NULL;
1218 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001219
1220 if (PyFile_Check(f)) {
1221 if (((PyFileObject*)f)->f_fp == NULL)
1222 return err_closed();
1223 result = get_line((PyFileObject *)f, n);
1224 }
1225 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001226 PyObject *reader;
1227 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001228
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001229 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001230 if (reader == NULL)
1231 return NULL;
1232 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001233 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001234 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001235 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001236 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001237 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001238 return NULL;
1239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001240 result = PyEval_CallObject(reader, args);
1241 Py_DECREF(reader);
1242 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001243 if (result != NULL && !PyString_Check(result) &&
1244 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001245 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001246 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001247 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001248 "object.readline() returned non-string");
1249 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001250 }
1251
1252 if (n < 0 && result != NULL && PyString_Check(result)) {
1253 char *s = PyString_AS_STRING(result);
1254 int len = PyString_GET_SIZE(result);
1255 if (len == 0) {
1256 Py_DECREF(result);
1257 result = NULL;
1258 PyErr_SetString(PyExc_EOFError,
1259 "EOF when reading a line");
1260 }
1261 else if (s[len-1] == '\n') {
1262 if (result->ob_refcnt == 1)
1263 _PyString_Resize(&result, len-1);
1264 else {
1265 PyObject *v;
1266 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001267 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001268 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001269 }
1270 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001271 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001272#ifdef Py_USING_UNICODE
1273 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1274 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1275 int len = PyUnicode_GET_SIZE(result);
1276 if (len == 0) {
1277 Py_DECREF(result);
1278 result = NULL;
1279 PyErr_SetString(PyExc_EOFError,
1280 "EOF when reading a line");
1281 }
1282 else if (s[len-1] == '\n') {
1283 if (result->ob_refcnt == 1)
1284 PyUnicode_Resize(&result, len-1);
1285 else {
1286 PyObject *v;
1287 v = PyUnicode_FromUnicode(s, len-1);
1288 Py_DECREF(result);
1289 result = v;
1290 }
1291 }
1292 }
1293#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001294 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001295}
1296
1297/* Python method */
1298
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001299static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001300file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001301{
Guido van Rossum789a1611997-05-10 22:33:55 +00001302 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001303
Guido van Rossumd7297e61992-07-06 14:19:26 +00001304 if (f->f_fp == NULL)
1305 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001306 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001307 return NULL;
1308 if (n == 0)
1309 return PyString_FromString("");
1310 if (n < 0)
1311 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001312 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001313}
1314
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001315static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001316file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001317{
Guido van Rossum789a1611997-05-10 22:33:55 +00001318 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001319 PyObject *list;
1320 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001321 char small_buffer[SMALLCHUNK];
1322 char *buffer = small_buffer;
1323 size_t buffersize = SMALLCHUNK;
1324 PyObject *big_buffer = NULL;
1325 size_t nfilled = 0;
1326 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001327 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001328 char *p, *q, *end;
1329 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001330 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001331
Guido van Rossumd7297e61992-07-06 14:19:26 +00001332 if (f->f_fp == NULL)
1333 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001334 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001335 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001336 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001337 return NULL;
1338 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001339 if (shortread)
1340 nread = 0;
1341 else {
1342 Py_BEGIN_ALLOW_THREADS
1343 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001344 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001345 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001346 Py_END_ALLOW_THREADS
1347 shortread = (nread < buffersize-nfilled);
1348 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001349 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001350 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001351 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001352 break;
1353 PyErr_SetFromErrno(PyExc_IOError);
1354 clearerr(f->f_fp);
1355 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001356 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001357 list = NULL;
1358 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001359 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001360 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001361 p = memchr(buffer+nfilled, '\n', nread);
1362 if (p == NULL) {
1363 /* Need a larger buffer to fit this line */
1364 nfilled += nread;
1365 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001366 if (buffersize > INT_MAX) {
1367 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001368 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001369 goto error;
1370 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001371 if (big_buffer == NULL) {
1372 /* Create the big buffer */
1373 big_buffer = PyString_FromStringAndSize(
1374 NULL, buffersize);
1375 if (big_buffer == NULL)
1376 goto error;
1377 buffer = PyString_AS_STRING(big_buffer);
1378 memcpy(buffer, small_buffer, nfilled);
1379 }
1380 else {
1381 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001382 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1383 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001384 buffer = PyString_AS_STRING(big_buffer);
1385 }
1386 continue;
1387 }
1388 end = buffer+nfilled+nread;
1389 q = buffer;
1390 do {
1391 /* Process complete lines */
1392 p++;
1393 line = PyString_FromStringAndSize(q, p-q);
1394 if (line == NULL)
1395 goto error;
1396 err = PyList_Append(list, line);
1397 Py_DECREF(line);
1398 if (err != 0)
1399 goto error;
1400 q = p;
1401 p = memchr(q, '\n', end-q);
1402 } while (p != NULL);
1403 /* Move the remaining incomplete line to the start */
1404 nfilled = end-q;
1405 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001406 if (sizehint > 0)
1407 if (totalread >= (size_t)sizehint)
1408 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001409 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001410 if (nfilled != 0) {
1411 /* Partial last line */
1412 line = PyString_FromStringAndSize(buffer, nfilled);
1413 if (line == NULL)
1414 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001415 if (sizehint > 0) {
1416 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001417 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001418 if (rest == NULL) {
1419 Py_DECREF(line);
1420 goto error;
1421 }
1422 PyString_Concat(&line, rest);
1423 Py_DECREF(rest);
1424 if (line == NULL)
1425 goto error;
1426 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001427 err = PyList_Append(list, line);
1428 Py_DECREF(line);
1429 if (err != 0)
1430 goto error;
1431 }
1432 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001433 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001434 return list;
1435}
1436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001437static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001438file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001439{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001440 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001441 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001442 if (f->f_fp == NULL)
1443 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001444 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001445 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001446 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001447 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001448 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001449 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001450 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001451 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001452 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001453 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001454 return NULL;
1455 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001456 Py_INCREF(Py_None);
1457 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001458}
1459
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001460static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001461file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001462{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001463#define CHUNKSIZE 1000
1464 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001465 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001466 PyObject *result;
1467 int i, j, index, len, nwritten, islist;
1468
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001469 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001470 if (f->f_fp == NULL)
1471 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001472
1473 result = NULL;
1474 list = NULL;
1475 islist = PyList_Check(seq);
1476 if (islist)
1477 it = NULL;
1478 else {
1479 it = PyObject_GetIter(seq);
1480 if (it == NULL) {
1481 PyErr_SetString(PyExc_TypeError,
1482 "writelines() requires an iterable argument");
1483 return NULL;
1484 }
1485 /* From here on, fail by going to error, to reclaim "it". */
1486 list = PyList_New(CHUNKSIZE);
1487 if (list == NULL)
1488 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001489 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001490
1491 /* Strategy: slurp CHUNKSIZE lines into a private list,
1492 checking that they are all strings, then write that list
1493 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001494 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001495 if (islist) {
1496 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001497 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001498 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001499 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001500 j = PyList_GET_SIZE(list);
1501 }
1502 else {
1503 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001504 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001505 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001506 if (PyErr_Occurred())
1507 goto error;
1508 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001509 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001510 PyList_SetItem(list, j, line);
1511 }
1512 }
1513 if (j == 0)
1514 break;
1515
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001516 /* Check that all entries are indeed strings. If not,
1517 apply the same rules as for file.write() and
1518 convert the results to strings. This is slow, but
1519 seems to be the only way since all conversion APIs
1520 could potentially execute Python code. */
1521 for (i = 0; i < j; i++) {
1522 PyObject *v = PyList_GET_ITEM(list, i);
1523 if (!PyString_Check(v)) {
1524 const char *buffer;
1525 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001526 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001527 PyObject_AsReadBuffer(v,
1528 (const void**)&buffer,
1529 &len)) ||
1530 PyObject_AsCharBuffer(v,
1531 &buffer,
1532 &len))) {
1533 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001534 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001535 goto error;
1536 }
1537 line = PyString_FromStringAndSize(buffer,
1538 len);
1539 if (line == NULL)
1540 goto error;
1541 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001542 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001543 }
1544 }
1545
1546 /* Since we are releasing the global lock, the
1547 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001548 Py_BEGIN_ALLOW_THREADS
1549 f->f_softspace = 0;
1550 errno = 0;
1551 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001552 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001553 len = PyString_GET_SIZE(line);
1554 nwritten = fwrite(PyString_AS_STRING(line),
1555 1, len, f->f_fp);
1556 if (nwritten != len) {
1557 Py_BLOCK_THREADS
1558 PyErr_SetFromErrno(PyExc_IOError);
1559 clearerr(f->f_fp);
1560 goto error;
1561 }
1562 }
1563 Py_END_ALLOW_THREADS
1564
1565 if (j < CHUNKSIZE)
1566 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001567 }
1568
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001569 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001570 result = Py_None;
1571 error:
1572 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001573 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001574 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001575#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001576}
1577
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001578static PyObject *
1579file_getiter(PyFileObject *f)
1580{
1581 if (f->f_fp == NULL)
1582 return err_closed();
1583 Py_INCREF(f);
1584 return (PyObject *)f;
1585}
1586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001587PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001588"readline([size]) -> next line from the file, as a string.\n"
1589"\n"
1590"Retain newline. A non-negative size argument limits the maximum\n"
1591"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001592"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001594PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001595"read([size]) -> read at most size bytes, returned as a string.\n"
1596"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001597"If the size argument is negative or omitted, read until EOF is reached.\n"
1598"Notice that when in non-blocking mode, less data than what was requested\n"
1599"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001601PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001602"write(str) -> None. Write string str to file.\n"
1603"\n"
1604"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001605"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001607PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001608"fileno() -> integer \"file descriptor\".\n"
1609"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001610"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001612PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001613"seek(offset[, whence]) -> None. Move to new file position.\n"
1614"\n"
1615"Argument offset is a byte count. Optional argument whence defaults to\n"
1616"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1617"(move relative to current position, positive or negative), and 2 (move\n"
1618"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001619"seeking beyond the end of a file). If the file is opened in text mode,\n"
1620"only offsets returned by tell() are legal. Use of other offsets causes\n"
1621"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001622"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001623"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001624
Guido van Rossumd7047b31995-01-02 19:07:15 +00001625#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001626PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001627"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1628"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001629"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001630#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001632PyDoc_STRVAR(tell_doc,
1633"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635PyDoc_STRVAR(readinto_doc,
1636"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001638PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001639"readlines([size]) -> list of strings, each a line from the file.\n"
1640"\n"
1641"Call readline() repeatedly and return a list of the lines so read.\n"
1642"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001643"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001646"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001647"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001648"For backward compatibility. File objects now include the performance\n"
1649"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001651PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001652"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001653"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001654"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001655"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001657PyDoc_STRVAR(flush_doc,
1658"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001660PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001661"close() -> None or (perhaps) an integer. Close the file.\n"
1662"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001663"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001664"further I/O operations. close() may be called more than once without\n"
1665"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001666"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001668PyDoc_STRVAR(isatty_doc,
1669"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001670
1671static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001672 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1673 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1674 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1675 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1676 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001677#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001678 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001679#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001680 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1681 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1682 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1683 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1684 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1685 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1686 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1687 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1688 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001689};
1690
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001691#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001692
Guido van Rossum6f799372001-09-20 20:46:19 +00001693static PyMemberDef file_memberlist[] = {
1694 {"softspace", T_INT, OFF(f_softspace), 0,
1695 "flag indicating that a space needs to be printed; used by print"},
1696 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001697 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001698 {"name", T_OBJECT, OFF(f_name), RO,
1699 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001700 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1701 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001702 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001703 {NULL} /* Sentinel */
1704};
1705
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001706static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001708{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001709 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001710}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001711static PyObject *
1712get_newlines(PyFileObject *f, void *closure)
1713{
1714 switch (f->f_newlinetypes) {
1715 case NEWLINE_UNKNOWN:
1716 Py_INCREF(Py_None);
1717 return Py_None;
1718 case NEWLINE_CR:
1719 return PyString_FromString("\r");
1720 case NEWLINE_LF:
1721 return PyString_FromString("\n");
1722 case NEWLINE_CR|NEWLINE_LF:
1723 return Py_BuildValue("(ss)", "\r", "\n");
1724 case NEWLINE_CRLF:
1725 return PyString_FromString("\r\n");
1726 case NEWLINE_CR|NEWLINE_CRLF:
1727 return Py_BuildValue("(ss)", "\r", "\r\n");
1728 case NEWLINE_LF|NEWLINE_CRLF:
1729 return Py_BuildValue("(ss)", "\n", "\r\n");
1730 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1731 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1732 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001733 PyErr_Format(PyExc_SystemError,
1734 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001735 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001736 return NULL;
1737 }
1738}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001739
Guido van Rossum32d34c82001-09-20 21:45:26 +00001740static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001741 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001742 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001743 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001744 {0},
1745};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001746
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001747static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001748drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001749{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001750 if (f->f_buf != NULL) {
1751 PyMem_Free(f->f_buf);
1752 f->f_buf = NULL;
1753 }
Guido van Rossum65967252001-04-21 13:20:18 +00001754}
1755
Tim Petersf1827cf2003-09-07 03:30:18 +00001756/* Make sure that file has a readahead buffer with at least one byte
1757 (unless at EOF) and no more than bufsize. Returns negative value on
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001758 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001759static int
1760readahead(PyFileObject *f, int bufsize)
1761{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001762 int chunksize;
1763
1764 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001765 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001766 return 0;
1767 else
1768 drop_readahead(f);
1769 }
1770 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1771 return -1;
1772 }
1773 Py_BEGIN_ALLOW_THREADS
1774 errno = 0;
1775 chunksize = Py_UniversalNewlineFread(
1776 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1777 Py_END_ALLOW_THREADS
1778 if (chunksize == 0) {
1779 if (ferror(f->f_fp)) {
1780 PyErr_SetFromErrno(PyExc_IOError);
1781 clearerr(f->f_fp);
1782 drop_readahead(f);
1783 return -1;
1784 }
1785 }
1786 f->f_bufptr = f->f_buf;
1787 f->f_bufend = f->f_buf + chunksize;
1788 return 0;
1789}
1790
1791/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001792 uninitialized bytes followed by the remainder of the line. Don't be
1793 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001794 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1795
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001796static PyStringObject *
1797readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1798{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001799 PyStringObject* s;
1800 char *bufptr;
1801 char *buf;
1802 int len;
1803
1804 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001805 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001806 return NULL;
1807
1808 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001809 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001810 return (PyStringObject *)
1811 PyString_FromStringAndSize(NULL, skip);
1812 bufptr = memchr(f->f_bufptr, '\n', len);
1813 if (bufptr != NULL) {
1814 bufptr++; /* Count the '\n' */
1815 len = bufptr - f->f_bufptr;
1816 s = (PyStringObject *)
1817 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001818 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001819 return NULL;
1820 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1821 f->f_bufptr = bufptr;
1822 if (bufptr == f->f_bufend)
1823 drop_readahead(f);
1824 } else {
1825 bufptr = f->f_bufptr;
1826 buf = f->f_buf;
1827 f->f_buf = NULL; /* Force new readahead buffer */
1828 s = readahead_get_line_skip(
1829 f, skip+len, bufsize + (bufsize>>2) );
1830 if (s == NULL) {
1831 PyMem_Free(buf);
1832 return NULL;
1833 }
1834 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1835 PyMem_Free(buf);
1836 }
1837 return s;
1838}
1839
1840/* A larger buffer size may actually decrease performance. */
1841#define READAHEAD_BUFSIZE 8192
1842
1843static PyObject *
1844file_iternext(PyFileObject *f)
1845{
1846 PyStringObject* l;
1847
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001848 if (f->f_fp == NULL)
1849 return err_closed();
1850
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001851 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1852 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1853 Py_XDECREF(l);
1854 return NULL;
1855 }
1856 return (PyObject *)l;
1857}
1858
1859
Tim Peters59c9a642001-09-13 05:38:56 +00001860static PyObject *
1861file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1862{
Tim Peters44410012001-09-14 03:26:08 +00001863 PyObject *self;
1864 static PyObject *not_yet_string;
1865
1866 assert(type != NULL && type->tp_alloc != NULL);
1867
1868 if (not_yet_string == NULL) {
1869 not_yet_string = PyString_FromString("<uninitialized file>");
1870 if (not_yet_string == NULL)
1871 return NULL;
1872 }
1873
1874 self = type->tp_alloc(type, 0);
1875 if (self != NULL) {
1876 /* Always fill in the name and mode, so that nobody else
1877 needs to special-case NULLs there. */
1878 Py_INCREF(not_yet_string);
1879 ((PyFileObject *)self)->f_name = not_yet_string;
1880 Py_INCREF(not_yet_string);
1881 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001882 Py_INCREF(Py_None);
1883 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001884 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001885 }
1886 return self;
1887}
1888
1889static int
1890file_init(PyObject *self, PyObject *args, PyObject *kwds)
1891{
1892 PyFileObject *foself = (PyFileObject *)self;
1893 int ret = 0;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001894 static const char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001895 char *name = NULL;
1896 char *mode = "r";
1897 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001898 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001899
1900 assert(PyFile_Check(self));
1901 if (foself->f_fp != NULL) {
1902 /* Have to close the existing file first. */
1903 PyObject *closeresult = file_close(foself);
1904 if (closeresult == NULL)
1905 return -1;
1906 Py_DECREF(closeresult);
1907 }
Tim Peters59c9a642001-09-13 05:38:56 +00001908
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001909#ifdef Py_WIN_WIDE_FILENAMES
1910 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1911 PyObject *po;
1912 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1913 kwlist, &po, &mode, &bufsize)) {
1914 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001915 if (fill_file_fields(foself, NULL, po, mode,
1916 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001917 goto Error;
1918 } else {
1919 /* Drop the argument parsing error as narrow
1920 strings are also valid. */
1921 PyErr_Clear();
1922 }
1923 }
1924#endif
1925
1926 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001927 PyObject *o_name;
1928
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001929 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1930 Py_FileSystemDefaultEncoding,
1931 &name,
1932 &mode, &bufsize))
1933 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001934
1935 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001936 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
1937 kwlist, &o_name, &mode,
1938 &bufsize))
Nicholas Bastinabce8a62004-03-21 20:24:07 +00001939 return -1;
1940
1941 if (fill_file_fields(foself, NULL, o_name, mode,
1942 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001943 goto Error;
1944 }
Tim Peters44410012001-09-14 03:26:08 +00001945 if (open_the_file(foself, name, mode) == NULL)
1946 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001947 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001948 PyFile_SetBufSize(self, bufsize);
1949 goto Done;
1950
1951Error:
1952 ret = -1;
1953 /* fall through */
1954Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001955 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001956 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001957}
1958
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001959PyDoc_VAR(file_doc) =
1960PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001961"file(name[, mode[, buffering]]) -> file object\n"
1962"\n"
1963"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1964"writing or appending. The file will be created if it doesn't exist\n"
1965"when opened for writing or appending; it will be truncated when\n"
1966"opened for writing. Add a 'b' to the mode for binary files.\n"
1967"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1968"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001969"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001970)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001972"Add a 'U' to mode to open the file for input with universal newline\n"
1973"support. Any line ending in the input file will be seen as a '\\n'\n"
1974"in Python. Also, a file so opened gains the attribute 'newlines';\n"
1975"the value for this attribute is one of None (no newline read yet),\n"
1976"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
1977"\n"
1978"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001979)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001980PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001981"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001982"Note: open() is an alias for file()."
1983);
Tim Peters59c9a642001-09-13 05:38:56 +00001984
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001985PyTypeObject PyFile_Type = {
1986 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001987 0,
1988 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001989 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001990 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001991 (destructor)file_dealloc, /* tp_dealloc */
1992 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993 0, /* tp_getattr */
1994 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001995 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001997 0, /* tp_as_number */
1998 0, /* tp_as_sequence */
1999 0, /* tp_as_mapping */
2000 0, /* tp_hash */
2001 0, /* tp_call */
2002 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002004 /* softspace is writable: we must supply tp_setattro */
2005 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002006 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002007 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002008 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009 0, /* tp_traverse */
2010 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002011 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002012 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002013 (getiterfunc)file_getiter, /* tp_iter */
2014 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015 file_methods, /* tp_methods */
2016 file_memberlist, /* tp_members */
2017 file_getsetlist, /* tp_getset */
2018 0, /* tp_base */
2019 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002020 0, /* tp_descr_get */
2021 0, /* tp_descr_set */
2022 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00002023 (initproc)file_init, /* tp_init */
2024 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002025 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002026 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002027};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002028
2029/* Interface for the 'soft space' between print items. */
2030
2031int
Fred Drakefd99de62000-07-09 05:02:18 +00002032PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002033{
2034 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002035 if (f == NULL) {
2036 /* Do nothing */
2037 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002038 else if (PyFile_Check(f)) {
2039 oldflag = ((PyFileObject *)f)->f_softspace;
2040 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002041 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002042 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043 PyObject *v;
2044 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002045 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002046 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002047 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002048 if (PyInt_Check(v))
2049 oldflag = PyInt_AsLong(v);
2050 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002051 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002053 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002055 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002056 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2057 PyErr_Clear();
2058 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002059 }
2060 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00002061 return oldflag;
2062}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002063
2064/* Interfaces to write objects/strings to file-like objects */
2065
2066int
Fred Drakefd99de62000-07-09 05:02:18 +00002067PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002068{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002069 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002070 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002071 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002072 return -1;
2073 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074 else if (PyFile_Check(f)) {
2075 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002076#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002077 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2078 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002079#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002080 if (fp == NULL) {
2081 err_closed();
2082 return -1;
2083 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002084#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002085 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002086 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002087 char *cenc = PyString_AS_STRING(enc);
2088 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2089 if (value == NULL)
2090 return -1;
2091 } else {
2092 value = v;
2093 Py_INCREF(value);
2094 }
2095 result = PyObject_Print(value, fp, flags);
2096 Py_DECREF(value);
2097 return result;
2098#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002100#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002101 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002103 if (writer == NULL)
2104 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002105 if (flags & Py_PRINT_RAW) {
2106 if (PyUnicode_Check(v)) {
2107 value = v;
2108 Py_INCREF(value);
2109 } else
2110 value = PyObject_Str(v);
2111 }
2112 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002114 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002116 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002117 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002118 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002119 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002120 Py_DECREF(value);
2121 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002122 return -1;
2123 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002124 result = PyEval_CallObject(writer, args);
2125 Py_DECREF(args);
2126 Py_DECREF(value);
2127 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002128 if (result == NULL)
2129 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002130 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002131 return 0;
2132}
2133
Guido van Rossum27a60b11997-05-22 22:25:11 +00002134int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002135PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002136{
2137 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002138 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002139 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002140 PyErr_SetString(PyExc_SystemError,
2141 "null file for PyFile_WriteString");
2142 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002143 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144 else if (PyFile_Check(f)) {
2145 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002146 if (fp == NULL) {
2147 err_closed();
2148 return -1;
2149 }
2150 fputs(s, fp);
2151 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002152 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002153 else if (!PyErr_Occurred()) {
2154 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002155 int err;
2156 if (v == NULL)
2157 return -1;
2158 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2159 Py_DECREF(v);
2160 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002161 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002162 else
2163 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002164}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002165
2166/* Try to get a file-descriptor from a Python object. If the object
2167 is an integer or long integer, its value is returned. If not, the
2168 object's fileno() method is called if it exists; the method must return
2169 an integer or long integer, which is returned as the file descriptor value.
2170 -1 is returned on failure.
2171*/
2172
2173int PyObject_AsFileDescriptor(PyObject *o)
2174{
2175 int fd;
2176 PyObject *meth;
2177
2178 if (PyInt_Check(o)) {
2179 fd = PyInt_AsLong(o);
2180 }
2181 else if (PyLong_Check(o)) {
2182 fd = PyLong_AsLong(o);
2183 }
2184 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2185 {
2186 PyObject *fno = PyEval_CallObject(meth, NULL);
2187 Py_DECREF(meth);
2188 if (fno == NULL)
2189 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002190
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002191 if (PyInt_Check(fno)) {
2192 fd = PyInt_AsLong(fno);
2193 Py_DECREF(fno);
2194 }
2195 else if (PyLong_Check(fno)) {
2196 fd = PyLong_AsLong(fno);
2197 Py_DECREF(fno);
2198 }
2199 else {
2200 PyErr_SetString(PyExc_TypeError,
2201 "fileno() returned a non-integer");
2202 Py_DECREF(fno);
2203 return -1;
2204 }
2205 }
2206 else {
2207 PyErr_SetString(PyExc_TypeError,
2208 "argument must be an int, or have a fileno() method.");
2209 return -1;
2210 }
2211
2212 if (fd < 0) {
2213 PyErr_Format(PyExc_ValueError,
2214 "file descriptor cannot be a negative integer (%i)",
2215 fd);
2216 return -1;
2217 }
2218 return fd;
2219}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002220
Jack Jansen7b8c7542002-04-14 20:12:41 +00002221/* From here on we need access to the real fgets and fread */
2222#undef fgets
2223#undef fread
2224
2225/*
2226** Py_UniversalNewlineFgets is an fgets variation that understands
2227** all of \r, \n and \r\n conventions.
2228** The stream should be opened in binary mode.
2229** If fobj is NULL the routine always does newline conversion, and
2230** it may peek one char ahead to gobble the second char in \r\n.
2231** If fobj is non-NULL it must be a PyFileObject. In this case there
2232** is no readahead but in stead a flag is used to skip a following
2233** \n on the next read. Also, if the file is open in binary mode
2234** the whole conversion is skipped. Finally, the routine keeps track of
2235** the different types of newlines seen.
2236** Note that we need no error handling: fgets() treats error and eof
2237** identically.
2238*/
2239char *
2240Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2241{
2242 char *p = buf;
2243 int c;
2244 int newlinetypes = 0;
2245 int skipnextlf = 0;
2246 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002247
Jack Jansen7b8c7542002-04-14 20:12:41 +00002248 if (fobj) {
2249 if (!PyFile_Check(fobj)) {
2250 errno = ENXIO; /* What can you do... */
2251 return NULL;
2252 }
2253 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2254 if ( !univ_newline )
2255 return fgets(buf, n, stream);
2256 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2257 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2258 }
2259 FLOCKFILE(stream);
2260 c = 'x'; /* Shut up gcc warning */
2261 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2262 if (skipnextlf ) {
2263 skipnextlf = 0;
2264 if (c == '\n') {
2265 /* Seeing a \n here with skipnextlf true
2266 ** means we saw a \r before.
2267 */
2268 newlinetypes |= NEWLINE_CRLF;
2269 c = GETC(stream);
2270 if (c == EOF) break;
2271 } else {
2272 /*
2273 ** Note that c == EOF also brings us here,
2274 ** so we're okay if the last char in the file
2275 ** is a CR.
2276 */
2277 newlinetypes |= NEWLINE_CR;
2278 }
2279 }
2280 if (c == '\r') {
2281 /* A \r is translated into a \n, and we skip
2282 ** an adjacent \n, if any. We don't set the
2283 ** newlinetypes flag until we've seen the next char.
2284 */
2285 skipnextlf = 1;
2286 c = '\n';
2287 } else if ( c == '\n') {
2288 newlinetypes |= NEWLINE_LF;
2289 }
2290 *p++ = c;
2291 if (c == '\n') break;
2292 }
2293 if ( c == EOF && skipnextlf )
2294 newlinetypes |= NEWLINE_CR;
2295 FUNLOCKFILE(stream);
2296 *p = '\0';
2297 if (fobj) {
2298 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2299 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2300 } else if ( skipnextlf ) {
2301 /* If we have no file object we cannot save the
2302 ** skipnextlf flag. We have to readahead, which
2303 ** will cause a pause if we're reading from an
2304 ** interactive stream, but that is very unlikely
2305 ** unless we're doing something silly like
2306 ** execfile("/dev/tty").
2307 */
2308 c = GETC(stream);
2309 if ( c != '\n' )
2310 ungetc(c, stream);
2311 }
2312 if (p == buf)
2313 return NULL;
2314 return buf;
2315}
2316
2317/*
2318** Py_UniversalNewlineFread is an fread variation that understands
2319** all of \r, \n and \r\n conventions.
2320** The stream should be opened in binary mode.
2321** fobj must be a PyFileObject. In this case there
2322** is no readahead but in stead a flag is used to skip a following
2323** \n on the next read. Also, if the file is open in binary mode
2324** the whole conversion is skipped. Finally, the routine keeps track of
2325** the different types of newlines seen.
2326*/
2327size_t
Tim Peters058b1412002-04-21 07:29:14 +00002328Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002329 FILE *stream, PyObject *fobj)
2330{
Tim Peters058b1412002-04-21 07:29:14 +00002331 char *dst = buf;
2332 PyFileObject *f = (PyFileObject *)fobj;
2333 int newlinetypes, skipnextlf;
2334
2335 assert(buf != NULL);
2336 assert(stream != NULL);
2337
Jack Jansen7b8c7542002-04-14 20:12:41 +00002338 if (!fobj || !PyFile_Check(fobj)) {
2339 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002340 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002341 }
Tim Peters058b1412002-04-21 07:29:14 +00002342 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002343 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002344 newlinetypes = f->f_newlinetypes;
2345 skipnextlf = f->f_skipnextlf;
2346 /* Invariant: n is the number of bytes remaining to be filled
2347 * in the buffer.
2348 */
2349 while (n) {
2350 size_t nread;
2351 int shortread;
2352 char *src = dst;
2353
2354 nread = fread(dst, 1, n, stream);
2355 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002356 if (nread == 0)
2357 break;
2358
Tim Peterse1682a82002-04-21 18:15:20 +00002359 n -= nread; /* assuming 1 byte out for each in; will adjust */
2360 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002361 while (nread--) {
2362 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002363 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002364 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002365 *dst++ = '\n';
2366 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002367 }
2368 else if (skipnextlf && c == '\n') {
2369 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002370 skipnextlf = 0;
2371 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002372 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002373 }
2374 else {
2375 /* Normal char to be stored in buffer. Also
2376 * update the newlinetypes flag if either this
2377 * is an LF or the previous char was a CR.
2378 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002379 if (c == '\n')
2380 newlinetypes |= NEWLINE_LF;
2381 else if (skipnextlf)
2382 newlinetypes |= NEWLINE_CR;
2383 *dst++ = c;
2384 skipnextlf = 0;
2385 }
2386 }
Tim Peters058b1412002-04-21 07:29:14 +00002387 if (shortread) {
2388 /* If this is EOF, update type flags. */
2389 if (skipnextlf && feof(stream))
2390 newlinetypes |= NEWLINE_CR;
2391 break;
2392 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002393 }
Tim Peters058b1412002-04-21 07:29:14 +00002394 f->f_newlinetypes = newlinetypes;
2395 f->f_skipnextlf = skipnextlf;
2396 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002397}