blob: bddd81e93ad23e64a74a5d0d2a9b1f633d9c4e2f [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
Guido van Rossumf2044e11998-04-28 16:05:59 +000024#ifdef macintosh
25#ifdef USE_GUSI
26#define HAVE_FTRUNCATE
27#endif
28#endif
29
Jack Jansene08dea191995-04-23 22:12:47 +000030#ifdef __MWERKS__
31/* Mwerks fopen() doesn't always set errno */
32#define NO_FOPEN_ERRNO
33#endif
Guido van Rossum295d1711995-02-19 15:55:19 +000034
Andrew MacIntyrec4874392002-02-26 11:36:35 +000035#if defined(PYOS_OS2) && defined(PYCC_GCC)
36#include <io.h>
37#endif
38
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000040
Guido van Rossumff7e83d1999-08-27 20:39:37 +000041#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000042#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000043#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
Jack Jansen7b8c7542002-04-14 20:12:41 +000045#ifdef HAVE_GETC_UNLOCKED
46#define GETC(f) getc_unlocked(f)
47#define FLOCKFILE(f) flockfile(f)
48#define FUNLOCKFILE(f) funlockfile(f)
49#else
50#define GETC(f) getc(f)
51#define FLOCKFILE(f)
52#define FUNLOCKFILE(f)
53#endif
54
55#ifdef WITH_UNIVERSAL_NEWLINES
56/* Bits in f_newlinetypes */
57#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
58#define NEWLINE_CR 1 /* \r newline seen */
59#define NEWLINE_LF 2 /* \n newline seen */
60#define NEWLINE_CRLF 4 /* \r\n newline seen */
61#endif
Trent Mickf29f47b2000-08-11 19:02:59 +000062
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000064PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000068 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000069 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070}
71
Guido van Rossumc0b618a1997-05-02 03:12:38 +000072PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000073PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000074{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000076 return NULL;
77 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000078 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000079}
80
Neil Schemenauered19b882002-03-23 02:06:50 +000081/* On Unix, fopen will succeed for directories.
82 In Python, there should be no file objects referring to
83 directories, so we need a check. */
84
85static PyFileObject*
86dircheck(PyFileObject* f)
87{
88#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
89 struct stat buf;
90 if (f->f_fp == NULL)
91 return f;
92 if (fstat(fileno(f->f_fp), &buf) == 0 &&
93 S_ISDIR(buf.st_mode)) {
94#ifdef HAVE_STRERROR
95 char *msg = strerror(EISDIR);
96#else
97 char *msg = "Is a directory";
98#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +000099 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
100 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +0000101 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +0000102 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +0000103 return NULL;
104 }
105#endif
106 return f;
107}
108
Tim Peters59c9a642001-09-13 05:38:56 +0000109
110static PyObject *
111fill_file_fields(PyFileObject *f, FILE *fp, char *name, char *mode,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000112 int (*close)(FILE *), PyObject *wname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000113{
Tim Peters59c9a642001-09-13 05:38:56 +0000114 assert(f != NULL);
115 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000116 assert(f->f_fp == NULL);
117
118 Py_DECREF(f->f_name);
119 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000120 Py_DECREF(f->f_encoding);
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000121#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000122 if (wname)
123 f->f_name = PyUnicode_FromObject(wname);
124 else
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000125#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000126 f->f_name = PyString_FromString(name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000128
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000129 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000130 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000131 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000132 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000133#ifdef WITH_UNIVERSAL_NEWLINES
134 f->f_univ_newline = (strchr(mode, 'U') != NULL);
135 f->f_newlinetypes = NEWLINE_UNKNOWN;
136 f->f_skipnextlf = 0;
137#endif
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000138 Py_INCREF(Py_None);
139 f->f_encoding = Py_None;
140
Tim Peters59c9a642001-09-13 05:38:56 +0000141 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000144 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146}
147
Tim Peters59c9a642001-09-13 05:38:56 +0000148static PyObject *
149open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150{
Tim Peters59c9a642001-09-13 05:38:56 +0000151 assert(f != NULL);
152 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000153#ifdef MS_WINDOWS
154 /* windows ignores the passed name in order to support Unicode */
155 assert(f->f_name != NULL);
156#else
Tim Peters59c9a642001-09-13 05:38:56 +0000157 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000158#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000159 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000160 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000161
Tim Peters8fa45672001-09-13 21:01:29 +0000162 /* rexec.py can't stop a user from getting the file() constructor --
163 all they have to do is get *any* file object f, and then do
164 type(f). Here we prevent them from doing damage with it. */
165 if (PyEval_GetRestricted()) {
166 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000167 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000168 return NULL;
169 }
Tim Petersa27a1502001-11-09 20:59:14 +0000170 errno = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000171#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000172 if (*mode == '*') {
173 FILE *fopenRF();
174 f->f_fp = fopenRF(name, mode+1);
175 }
176 else
177#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000178 {
Jack Jansen7b8c7542002-04-14 20:12:41 +0000179#ifdef WITH_UNIVERSAL_NEWLINES
180 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
181 mode = "rb";
182#else
183 /* Compatibility: specifying U in a Python without universal
184 ** newlines is allowed, and the file is opened as a normal text
185 ** file.
186 */
187 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
188 mode = "r";
189#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000190#ifdef MS_WINDOWS
191 if (PyUnicode_Check(f->f_name)) {
192 PyObject *wmode;
193 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
194 if (f->f_name && wmode) {
195 Py_BEGIN_ALLOW_THREADS
196 /* PyUnicode_AS_UNICODE OK without thread
197 lock as it is a simple dereference. */
198 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
199 PyUnicode_AS_UNICODE(wmode));
200 Py_END_ALLOW_THREADS
201 }
202 Py_XDECREF(wmode);
203 }
204#endif
205 if (NULL == f->f_fp && NULL != name) {
206 Py_BEGIN_ALLOW_THREADS
207 f->f_fp = fopen(name, mode);
208 Py_END_ALLOW_THREADS
209 }
Guido van Rossumff4949e1992-08-05 19:58:53 +0000210 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000211 if (f->f_fp == NULL) {
Jack Jansene08dea191995-04-23 22:12:47 +0000212#ifdef NO_FOPEN_ERRNO
Jack Jansenb3be2162001-11-30 14:16:36 +0000213 /* Metroworks only, wich does not always sets errno */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000214 if (errno == 0) {
Jack Jansenb3be2162001-11-30 14:16:36 +0000215 PyObject *v;
216 v = Py_BuildValue("(is)", 0, "Cannot open file");
217 if (v != NULL) {
218 PyErr_SetObject(PyExc_IOError, v);
219 Py_DECREF(v);
220 }
Jack Jansene08dea191995-04-23 22:12:47 +0000221 return NULL;
222 }
223#endif
Tim Peters2ea91112002-04-08 04:13:12 +0000224#ifdef _MSC_VER
225 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
226 * across all Windows flavors. When it sets EINVAL varies
227 * across Windows flavors, the exact conditions aren't
228 * documented, and the answer lies in the OS's implementation
229 * of Win32's CreateFile function (whose source is secret).
230 * Seems the best we can do is map EINVAL to ENOENT.
231 */
232 if (errno == 0) /* bad mode string */
233 errno = EINVAL;
234 else if (errno == EINVAL) /* unknown, but not a mode string */
235 errno = ENOENT;
236#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000237 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000238 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000239 mode);
240 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000241#ifdef MS_WINDOWS
242 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
243#else
Jeremy Hylton41c83212001-11-09 16:17:24 +0000244 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000245#endif /* MS_WINDOWS */
Tim Peters59c9a642001-09-13 05:38:56 +0000246 f = NULL;
247 }
Tim Peters2ea91112002-04-08 04:13:12 +0000248 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000249 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000250 return (PyObject *)f;
251}
252
253PyObject *
254PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
255{
Tim Peters44410012001-09-14 03:26:08 +0000256 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
257 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000258 if (f != NULL) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000259 if (fill_file_fields(f, fp, name, mode, close, NULL) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000260 Py_DECREF(f);
261 f = NULL;
262 }
263 }
264 return (PyObject *) f;
265}
266
267PyObject *
268PyFile_FromString(char *name, char *mode)
269{
270 extern int fclose(FILE *);
271 PyFileObject *f;
272
273 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
274 if (f != NULL) {
275 if (open_the_file(f, name, mode) == NULL) {
276 Py_DECREF(f);
277 f = NULL;
278 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000280 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281}
282
Guido van Rossumb6775db1994-08-01 11:34:53 +0000283void
Fred Drakefd99de62000-07-09 05:02:18 +0000284PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000285{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000286 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000288 int type;
289 switch (bufsize) {
290 case 0:
291 type = _IONBF;
292 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000293#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000294 case 1:
295 type = _IOLBF;
296 bufsize = BUFSIZ;
297 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000298#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000299 default:
300 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000301#ifndef HAVE_SETVBUF
302 bufsize = BUFSIZ;
303#endif
304 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000306 fflush(file->f_fp);
307 if (type == _IONBF) {
308 PyMem_Free(file->f_setbuf);
309 file->f_setbuf = NULL;
310 } else {
311 file->f_setbuf = PyMem_Realloc(file->f_setbuf, bufsize);
312 }
313#ifdef HAVE_SETVBUF
314 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000315#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000316 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000317#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000318 }
319}
320
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000321/* Set the encoding used to output Unicode strings.
322 Returh 1 on success, 0 on failure. */
323
324int
325PyFile_SetEncoding(PyObject *f, const char *enc)
326{
327 PyFileObject *file = (PyFileObject*)f;
328 PyObject *str = PyString_FromString(enc);
329 if (!str)
330 return 0;
331 Py_DECREF(file->f_encoding);
332 file->f_encoding = str;
333 return 1;
334}
335
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000336static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000337err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000338{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000340 return NULL;
341}
342
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000343static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000344
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345/* Methods */
346
347static void
Fred Drakefd99de62000-07-09 05:02:18 +0000348file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000350 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000352 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000353 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000354 }
Tim Peters44410012001-09-14 03:26:08 +0000355 Py_XDECREF(f->f_name);
356 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000357 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000358 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000359 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360}
361
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000362static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000363file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000365 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000366#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000367 PyObject *ret = NULL;
368 PyObject *name;
369 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
370 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
371 f->f_fp == NULL ? "closed" : "open",
372 PyString_AsString(name),
373 PyString_AsString(f->f_mode),
374 f);
375 Py_XDECREF(name);
376 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000377#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000378 } else {
379 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380 f->f_fp == NULL ? "closed" : "open",
381 PyString_AsString(f->f_name),
382 PyString_AsString(f->f_mode),
383 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000384 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385}
386
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000388file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000390 int sts = 0;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000391 PyMem_Free(f->f_setbuf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000393 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000395 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000396 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000398 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399 f->f_fp = NULL;
400 }
Guido van Rossumfebd5511992-03-04 16:39:24 +0000401 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000402 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000403 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000404 return PyInt_FromLong((long)sts);
405 Py_INCREF(Py_None);
406 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407}
408
Trent Mickf29f47b2000-08-11 19:02:59 +0000409
Guido van Rossumb8552162001-09-05 14:58:11 +0000410/* Our very own off_t-like type, 64-bit if possible */
411#if !defined(HAVE_LARGEFILE_SUPPORT)
412typedef off_t Py_off_t;
413#elif SIZEOF_OFF_T >= 8
414typedef off_t Py_off_t;
415#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000416typedef fpos_t Py_off_t;
417#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000418#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000419#endif
420
421
Trent Mickf29f47b2000-08-11 19:02:59 +0000422/* a portable fseek() function
423 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000424static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000425_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000426{
Guido van Rossumb8552162001-09-05 14:58:11 +0000427#if !defined(HAVE_LARGEFILE_SUPPORT)
428 return fseek(fp, offset, whence);
429#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000430 return fseeko(fp, offset, whence);
431#elif defined(HAVE_FSEEK64)
432 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000433#elif defined(__BEOS__)
434 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000435#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000436 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
437 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000438 fpos_t pos;
439 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000440 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000441#ifdef MS_WINDOWS
442 fflush(fp);
443 if (_lseeki64(fileno(fp), 0, 2) == -1)
444 return -1;
445#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000446 if (fseek(fp, 0, SEEK_END) != 0)
447 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000448#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000449 /* fall through */
450 case SEEK_CUR:
451 if (fgetpos(fp, &pos) != 0)
452 return -1;
453 offset += pos;
454 break;
455 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000456 }
457 return fsetpos(fp, &offset);
458#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000459#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000460#endif
461}
462
463
464/* a portable ftell() function
465 Return -1 on failure with errno set appropriately, current file
466 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000467static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000468_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000469{
Guido van Rossumb8552162001-09-05 14:58:11 +0000470#if !defined(HAVE_LARGEFILE_SUPPORT)
471 return ftell(fp);
472#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
473 return ftello(fp);
474#elif defined(HAVE_FTELL64)
475 return ftell64(fp);
476#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000477 fpos_t pos;
478 if (fgetpos(fp, &pos) != 0)
479 return -1;
480 return pos;
481#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000482#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000483#endif
484}
485
486
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000488file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000489{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000490 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000491 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000492 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000493 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000494
Guido van Rossumd7297e61992-07-06 14:19:26 +0000495 if (f->f_fp == NULL)
496 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000497 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000498 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000499 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000500 return NULL;
501#if !defined(HAVE_LARGEFILE_SUPPORT)
502 offset = PyInt_AsLong(offobj);
503#else
504 offset = PyLong_Check(offobj) ?
505 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
506#endif
507 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000508 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000509
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000511 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000512 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000514
Guido van Rossumff4949e1992-08-05 19:58:53 +0000515 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000517 clearerr(f->f_fp);
518 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000519 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000520#ifdef WITH_UNIVERSAL_NEWLINES
521 f->f_skipnextlf = 0;
522#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523 Py_INCREF(Py_None);
524 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000525}
526
Trent Mickf29f47b2000-08-11 19:02:59 +0000527
Guido van Rossumd7047b31995-01-02 19:07:15 +0000528#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000529static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000530file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000531{
Guido van Rossumd7047b31995-01-02 19:07:15 +0000532 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000533 Py_off_t newsize;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000534 PyObject *newsizeobj;
Tim Peters86821b22001-01-07 21:19:34 +0000535
Guido van Rossumd7047b31995-01-02 19:07:15 +0000536 if (f->f_fp == NULL)
537 return err_closed();
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000538 newsizeobj = NULL;
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000539 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000540 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000541
542 /* Set newsize to current postion if newsizeobj NULL, else to the
543 specified value. */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000544 if (newsizeobj != NULL) {
545#if !defined(HAVE_LARGEFILE_SUPPORT)
546 newsize = PyInt_AsLong(newsizeobj);
547#else
548 newsize = PyLong_Check(newsizeobj) ?
549 PyLong_AsLongLong(newsizeobj) :
550 PyInt_AsLong(newsizeobj);
551#endif
552 if (PyErr_Occurred())
553 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000554 }
555 else {
556 /* Default to current position. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000557 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000558 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000559 newsize = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000561 if (newsize == -1)
562 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000563 }
Tim Petersfb05db22002-03-11 00:24:00 +0000564
565 /* Flush the file. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000566 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000567 errno = 0;
568 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000570 if (ret != 0)
571 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000572
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000573#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000574 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000575 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000576 {
Tim Peters8f01b682002-03-12 03:04:44 +0000577 Py_off_t current; /* current file position */
Tim Petersfb05db22002-03-11 00:24:00 +0000578 HANDLE hFile;
579 int error;
580
Tim Peters8f01b682002-03-12 03:04:44 +0000581 /* current <- current file postion. */
582 if (newsizeobj == NULL)
583 current = newsize;
584 else {
Tim Petersfb05db22002-03-11 00:24:00 +0000585 Py_BEGIN_ALLOW_THREADS
586 errno = 0;
Tim Peters8f01b682002-03-12 03:04:44 +0000587 current = _portable_ftell(f->f_fp);
588 Py_END_ALLOW_THREADS
589 if (current == -1)
590 goto onioerror;
591 }
592
593 /* Move to newsize. */
594 if (current != newsize) {
595 Py_BEGIN_ALLOW_THREADS
596 errno = 0;
597 error = _portable_fseek(f->f_fp, newsize, SEEK_SET)
598 != 0;
Tim Petersfb05db22002-03-11 00:24:00 +0000599 Py_END_ALLOW_THREADS
600 if (error)
601 goto onioerror;
602 }
603
Tim Peters8f01b682002-03-12 03:04:44 +0000604 /* Truncate. Note that this may grow the file! */
605 Py_BEGIN_ALLOW_THREADS
606 errno = 0;
607 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
608 error = hFile == (HANDLE)-1;
609 if (!error) {
610 error = SetEndOfFile(hFile) == 0;
611 if (error)
612 errno = EACCES;
613 }
614 Py_END_ALLOW_THREADS
615 if (error)
616 goto onioerror;
617
618 /* Restore original file position. */
619 if (current != newsize) {
620 Py_BEGIN_ALLOW_THREADS
621 errno = 0;
622 error = _portable_fseek(f->f_fp, current, SEEK_SET)
623 != 0;
624 Py_END_ALLOW_THREADS
625 if (error)
626 goto onioerror;
627 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000628 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000629#else
630 Py_BEGIN_ALLOW_THREADS
631 errno = 0;
632 ret = ftruncate(fileno(f->f_fp), newsize);
633 Py_END_ALLOW_THREADS
634 if (ret != 0) goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000635#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000636
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637 Py_INCREF(Py_None);
638 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000639
640onioerror:
641 PyErr_SetFromErrno(PyExc_IOError);
642 clearerr(f->f_fp);
643 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000644}
645#endif /* HAVE_FTRUNCATE */
646
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000648file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000649{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000650 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000651
Guido van Rossumd7297e61992-07-06 14:19:26 +0000652 if (f->f_fp == NULL)
653 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000654 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000655 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000656 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000658 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000660 clearerr(f->f_fp);
661 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000662 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000663#ifdef WITH_UNIVERSAL_NEWLINES
664 if (f->f_skipnextlf) {
665 int c;
666 c = GETC(f->f_fp);
667 if (c == '\n') {
668 pos++;
669 f->f_skipnextlf = 0;
670 } else if (c != EOF) ungetc(c, f->f_fp);
671 }
672#endif
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000673#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000674 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000675#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000676 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000677#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000678}
679
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000680static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000681file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000682{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000683 if (f->f_fp == NULL)
684 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000686}
687
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000688static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000689file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000690{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000691 int res;
Tim Peters86821b22001-01-07 21:19:34 +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 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000696 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000697 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000698 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000699 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000700 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000701 clearerr(f->f_fp);
702 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000703 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000704 Py_INCREF(Py_None);
705 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000706}
707
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000709file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000710{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000711 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000712 if (f->f_fp == NULL)
713 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000715 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000717 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000718}
719
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000720
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000721#if BUFSIZ < 8192
722#define SMALLCHUNK 8192
723#else
724#define SMALLCHUNK BUFSIZ
725#endif
726
Guido van Rossum3c259041999-01-14 19:00:14 +0000727#if SIZEOF_INT < 4
728#define BIGCHUNK (512 * 32)
729#else
730#define BIGCHUNK (512 * 1024)
731#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000732
733static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000734new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000735{
736#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000737 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000738 struct stat st;
739 if (fstat(fileno(f->f_fp), &st) == 0) {
740 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000741 /* The following is not a bug: we really need to call lseek()
742 *and* ftell(). The reason is that some stdio libraries
743 mistakenly flush their buffer when ftell() is called and
744 the lseek() call it makes fails, thereby throwing away
745 data that cannot be recovered in any way. To avoid this,
746 we first test lseek(), and only call ftell() if lseek()
747 works. We can't use the lseek() value either, because we
748 need to take the amount of buffered data into account.
749 (Yet another reason why stdio stinks. :-) */
Jack Jansen2771b5b2001-10-10 22:03:27 +0000750#ifdef USE_GUSI2
751 pos = lseek(fileno(f->f_fp), 1L, SEEK_CUR);
752 pos = lseek(fileno(f->f_fp), -1L, SEEK_CUR);
753#else
Guido van Rossum91aaa921998-05-05 22:21:35 +0000754 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000755#endif
756 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000757 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000758 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000759 if (pos < 0)
760 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000761 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000762 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000763 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000764 }
765#endif
766 if (currentsize > SMALLCHUNK) {
767 /* Keep doubling until we reach BIGCHUNK;
768 then keep adding BIGCHUNK. */
769 if (currentsize <= BIGCHUNK)
770 return currentsize + currentsize;
771 else
772 return currentsize + BIGCHUNK;
773 }
774 return currentsize + SMALLCHUNK;
775}
776
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000777#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
778#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
779#else
780#ifdef EWOULDBLOCK
781#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
782#else
783#ifdef EAGAIN
784#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
785#else
786#define BLOCKED_ERRNO(x) 0
787#endif
788#endif
789#endif
790
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000791static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000792file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000793{
Guido van Rossum789a1611997-05-10 22:33:55 +0000794 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000795 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000796 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000797
Guido van Rossumd7297e61992-07-06 14:19:26 +0000798 if (f->f_fp == NULL)
799 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000800 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000801 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000802 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000803 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000804 else
805 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000806 if (buffersize > INT_MAX) {
807 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000808 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000809 return NULL;
810 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000811 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000812 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000814 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000815 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000816 Py_BEGIN_ALLOW_THREADS
817 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000818 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000819 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000820 Py_END_ALLOW_THREADS
821 if (chunksize == 0) {
822 if (!ferror(f->f_fp))
823 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000824 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000825 /* When in non-blocking mode, data shouldn't
826 * be discarded if a blocking signal was
827 * received. That will also happen if
828 * chunksize != 0, but bytesread < buffersize. */
829 if (bytesread > 0 && BLOCKED_ERRNO(errno))
830 break;
831 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000832 Py_DECREF(v);
833 return NULL;
834 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000835 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000836 if (bytesread < buffersize) {
837 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000838 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000839 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000840 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000841 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000842 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000843 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000844 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000845 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000846 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000847 }
848 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000849 if (bytesread != buffersize)
850 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000851 return v;
852}
853
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000854static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000855file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000856{
857 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000858 int ntodo;
859 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000860
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000861 if (f->f_fp == NULL)
862 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000863 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000864 return NULL;
865 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000866 while (ntodo > 0) {
867 Py_BEGIN_ALLOW_THREADS
868 errno = 0;
Jeremy Hylton8b735422002-08-14 21:01:41 +0000869 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
870 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000871 Py_END_ALLOW_THREADS
872 if (nnow == 0) {
873 if (!ferror(f->f_fp))
874 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000875 PyErr_SetFromErrno(PyExc_IOError);
876 clearerr(f->f_fp);
877 return NULL;
878 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000879 ndone += nnow;
880 ntodo -= nnow;
881 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000882 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000883}
884
Tim Peters86821b22001-01-07 21:19:34 +0000885/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000886Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000887
888Under MSVC 6:
889
Tim Peters1c733232001-01-08 04:02:07 +0000890+ MS threadsafe getc is very slow (multiple layers of function calls before+
891 after each character, to lock+unlock the stream).
892+ The stream-locking functions are MS-internal -- can't access them from user
893 code.
894+ There's nothing Tim could find in the MS C or platform SDK libraries that
895 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000896+ MS fgets locks/unlocks only once per line; it's the only hook we have.
897
898So we use fgets for speed(!), despite that it's painful.
899
900MS realloc is also slow.
901
Tim Petersf29b64d2001-01-15 06:33:19 +0000902Reports from other platforms on this method vs getc_unlocked (which MS doesn't
903have):
904 Linux a wash
905 Solaris a wash
906 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000907
Tim Petersf29b64d2001-01-15 06:33:19 +0000908CAUTION: The C std isn't clear about this: in those cases where fgets
909writes something into the buffer, can it write into any position beyond the
910required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
911known on which it does; and it would be a strange way to code fgets. Still,
912getline_via_fgets may not work correctly if it does. The std test
913test_bufio.py should fail if platform fgets() routinely writes beyond the
914trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000915**************************************************************************/
916
Tim Petersf29b64d2001-01-15 06:33:19 +0000917/* Use this routine if told to, or by default on non-get_unlocked()
918 * platforms unless told not to. Yikes! Let's spell that out:
919 * On a platform with getc_unlocked():
920 * By default, use getc_unlocked().
921 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
922 * On a platform without getc_unlocked():
923 * By default, use fgets().
924 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
925 */
926#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
927#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000928#endif
929
Tim Petersf29b64d2001-01-15 06:33:19 +0000930#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
931#undef USE_FGETS_IN_GETLINE
932#endif
933
934#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000935static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000936getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000937{
Tim Peters15b83852001-01-08 00:53:12 +0000938/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000939 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
940 * to fill this much of the buffer with a known value in order to figure out
941 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
942 * than "most" lines, we waste time filling unused buffer slots. 100 is
943 * surely adequate for most peoples' email archives, chewing over source code,
944 * etc -- "regular old text files".
945 * MAXBUFSIZE is the maximum line length that lets us get away with the less
946 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
947 * cautions about boosting that. 300 was chosen because the worst real-life
948 * text-crunching job reported on Python-Dev was a mail-log crawler where over
949 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000950 */
Tim Peters142297a2001-01-15 10:36:56 +0000951#define INITBUFSIZE 100
952#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000953 char* p; /* temp */
954 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000955 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000956 char* pvfree; /* address of next free slot */
957 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000958 size_t nfree; /* # of free buffer slots; pvend-pvfree */
959 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000960 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000961
Tim Peters15b83852001-01-08 00:53:12 +0000962 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000963 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000964 */
Tim Peters142297a2001-01-15 10:36:56 +0000965 total_v_size = INITBUFSIZE; /* start small and pray */
966 pvfree = buf;
967 for (;;) {
968 Py_BEGIN_ALLOW_THREADS
969 pvend = buf + total_v_size;
970 nfree = pvend - pvfree;
971 memset(pvfree, '\n', nfree);
972 p = fgets(pvfree, nfree, fp);
973 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000974
Tim Peters142297a2001-01-15 10:36:56 +0000975 if (p == NULL) {
976 clearerr(fp);
977 if (PyErr_CheckSignals())
978 return NULL;
979 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000980 return v;
981 }
Tim Peters142297a2001-01-15 10:36:56 +0000982 /* fgets read *something* */
983 p = memchr(pvfree, '\n', nfree);
984 if (p != NULL) {
985 /* Did the \n come from fgets or from us?
986 * Since fgets stops at the first \n, and then writes
987 * \0, if it's from fgets a \0 must be next. But if
988 * that's so, it could not have come from us, since
989 * the \n's we filled the buffer with have only more
990 * \n's to the right.
991 */
992 if (p+1 < pvend && *(p+1) == '\0') {
993 /* It's from fgets: we win! In particular,
994 * we haven't done any mallocs yet, and can
995 * build the final result on the first try.
996 */
997 ++p; /* include \n from fgets */
998 }
999 else {
1000 /* Must be from us: fgets didn't fill the
1001 * buffer and didn't find a newline, so it
1002 * must be the last and newline-free line of
1003 * the file.
1004 */
1005 assert(p > pvfree && *(p-1) == '\0');
1006 --p; /* don't include \0 from fgets */
1007 }
1008 v = PyString_FromStringAndSize(buf, p - buf);
1009 return v;
1010 }
1011 /* yuck: fgets overwrote all the newlines, i.e. the entire
1012 * buffer. So this line isn't over yet, or maybe it is but
1013 * we're exactly at EOF. If we haven't already, try using the
1014 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001015 */
Tim Peters142297a2001-01-15 10:36:56 +00001016 assert(*(pvend-1) == '\0');
1017 if (pvfree == buf) {
1018 pvfree = pvend - 1; /* overwrite trailing null */
1019 total_v_size = MAXBUFSIZE;
1020 }
1021 else
1022 break;
Tim Peters86821b22001-01-07 21:19:34 +00001023 }
Tim Peters142297a2001-01-15 10:36:56 +00001024
1025 /* The stack buffer isn't big enough; malloc a string object and read
1026 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001027 */
Tim Petersddea2082002-03-23 10:03:50 +00001028 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001029 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001030 if (v == NULL)
1031 return v;
1032 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001033 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1034 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001035
1036 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001037 * after setting p one beyond the end of the line. The code here is
1038 * very much like the code above, except reads into v's buffer; see
1039 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001040 */
1041 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001042 Py_BEGIN_ALLOW_THREADS
1043 pvend = BUF(v) + total_v_size;
1044 nfree = pvend - pvfree;
1045 memset(pvfree, '\n', nfree);
1046 p = fgets(pvfree, nfree, fp);
1047 Py_END_ALLOW_THREADS
1048
1049 if (p == NULL) {
1050 clearerr(fp);
1051 if (PyErr_CheckSignals()) {
1052 Py_DECREF(v);
1053 return NULL;
1054 }
1055 p = pvfree;
1056 break;
1057 }
Tim Peters86821b22001-01-07 21:19:34 +00001058 p = memchr(pvfree, '\n', nfree);
1059 if (p != NULL) {
1060 if (p+1 < pvend && *(p+1) == '\0') {
1061 /* \n came from fgets */
1062 ++p;
1063 break;
1064 }
1065 /* \n came from us; last line of file, no newline */
1066 assert(p > pvfree && *(p-1) == '\0');
1067 --p;
1068 break;
1069 }
1070 /* expand buffer and try again */
1071 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001072 increment = total_v_size >> 2; /* mild exponential growth */
1073 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001074 if (total_v_size > INT_MAX) {
1075 PyErr_SetString(PyExc_OverflowError,
1076 "line is longer than a Python string can hold");
1077 Py_DECREF(v);
1078 return NULL;
1079 }
1080 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1081 return NULL;
1082 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001083 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001084 }
1085 if (BUF(v) + total_v_size != p)
1086 _PyString_Resize(&v, p - BUF(v));
1087 return v;
1088#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001089#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001090}
Tim Petersf29b64d2001-01-15 06:33:19 +00001091#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001092
Guido van Rossum0bd24411991-04-04 15:21:57 +00001093/* Internal routine to get a line.
1094 Size argument interpretation:
1095 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001096 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001097*/
1098
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001099static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001100get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001101{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001102 FILE *fp = f->f_fp;
1103 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001104 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001105 size_t total_v_size; /* total # of slots in buffer */
1106 size_t used_v_size; /* # used slots in buffer */
1107 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001108 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001109#ifdef WITH_UNIVERSAL_NEWLINES
1110 int newlinetypes = f->f_newlinetypes;
1111 int skipnextlf = f->f_skipnextlf;
1112 int univ_newline = f->f_univ_newline;
1113#endif
Guido van Rossum0bd24411991-04-04 15:21:57 +00001114
Jack Jansen7b8c7542002-04-14 20:12:41 +00001115#if defined(USE_FGETS_IN_GETLINE)
1116#ifdef WITH_UNIVERSAL_NEWLINES
1117 if (n <= 0 && !univ_newline )
1118#else
Guido van Rossum86282062001-01-08 01:26:47 +00001119 if (n <= 0)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001120#endif
Tim Petersf29b64d2001-01-15 06:33:19 +00001121 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001122#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001123 total_v_size = n > 0 ? n : 100;
1124 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001125 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001126 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001127 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001128 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001129
Guido van Rossumce5ba841991-03-06 13:06:18 +00001130 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001131 Py_BEGIN_ALLOW_THREADS
1132 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001133#ifdef WITH_UNIVERSAL_NEWLINES
1134 if (univ_newline) {
1135 c = 'x'; /* Shut up gcc warning */
1136 while ( buf != end && (c = GETC(fp)) != EOF ) {
1137 if (skipnextlf ) {
1138 skipnextlf = 0;
1139 if (c == '\n') {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001140 /* Seeing a \n here with
1141 * skipnextlf true means we
1142 * saw a \r before.
1143 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001144 newlinetypes |= NEWLINE_CRLF;
1145 c = GETC(fp);
1146 if (c == EOF) break;
1147 } else {
1148 newlinetypes |= NEWLINE_CR;
1149 }
1150 }
1151 if (c == '\r') {
1152 skipnextlf = 1;
1153 c = '\n';
1154 } else if ( c == '\n')
1155 newlinetypes |= NEWLINE_LF;
1156 *buf++ = c;
1157 if (c == '\n') break;
1158 }
1159 if ( c == EOF && skipnextlf )
1160 newlinetypes |= NEWLINE_CR;
1161 } else /* If not universal newlines use the normal loop */
1162#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001163 while ((c = GETC(fp)) != EOF &&
1164 (*buf++ = c) != '\n' &&
1165 buf != end)
1166 ;
1167 FUNLOCKFILE(fp);
1168 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001169#ifdef WITH_UNIVERSAL_NEWLINES
1170 f->f_newlinetypes = newlinetypes;
1171 f->f_skipnextlf = skipnextlf;
1172#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001173 if (c == '\n')
1174 break;
1175 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001176 if (ferror(fp)) {
1177 PyErr_SetFromErrno(PyExc_IOError);
1178 clearerr(fp);
1179 Py_DECREF(v);
1180 return NULL;
1181 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001182 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001183 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001184 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001185 return NULL;
1186 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001187 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001188 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001189 /* Must be because buf == end */
1190 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001191 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001192 used_v_size = total_v_size;
1193 increment = total_v_size >> 2; /* mild exponential growth */
1194 total_v_size += increment;
1195 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001196 PyErr_SetString(PyExc_OverflowError,
1197 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001198 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001199 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001200 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001201 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001202 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001203 buf = BUF(v) + used_v_size;
1204 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001205 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001206
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001207 used_v_size = buf - BUF(v);
1208 if (used_v_size != total_v_size)
1209 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001210 return v;
1211}
1212
Guido van Rossum0bd24411991-04-04 15:21:57 +00001213/* External C interface */
1214
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001215PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001216PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001217{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001218 PyObject *result;
1219
Guido van Rossum3165fe61992-09-25 21:59:05 +00001220 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001221 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001222 return NULL;
1223 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001224
1225 if (PyFile_Check(f)) {
1226 if (((PyFileObject*)f)->f_fp == NULL)
1227 return err_closed();
1228 result = get_line((PyFileObject *)f, n);
1229 }
1230 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001231 PyObject *reader;
1232 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001233
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001234 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001235 if (reader == NULL)
1236 return NULL;
1237 if (n <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001238 args = Py_BuildValue("()");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001239 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001240 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001241 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001242 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001243 return NULL;
1244 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001245 result = PyEval_CallObject(reader, args);
1246 Py_DECREF(reader);
1247 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001248 if (result != NULL && !PyString_Check(result) &&
1249 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001250 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001251 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001252 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001253 "object.readline() returned non-string");
1254 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001255 }
1256
1257 if (n < 0 && result != NULL && PyString_Check(result)) {
1258 char *s = PyString_AS_STRING(result);
1259 int len = PyString_GET_SIZE(result);
1260 if (len == 0) {
1261 Py_DECREF(result);
1262 result = NULL;
1263 PyErr_SetString(PyExc_EOFError,
1264 "EOF when reading a line");
1265 }
1266 else if (s[len-1] == '\n') {
1267 if (result->ob_refcnt == 1)
1268 _PyString_Resize(&result, len-1);
1269 else {
1270 PyObject *v;
1271 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001272 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001273 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001274 }
1275 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001276 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001277#ifdef Py_USING_UNICODE
1278 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1279 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1280 int len = PyUnicode_GET_SIZE(result);
1281 if (len == 0) {
1282 Py_DECREF(result);
1283 result = NULL;
1284 PyErr_SetString(PyExc_EOFError,
1285 "EOF when reading a line");
1286 }
1287 else if (s[len-1] == '\n') {
1288 if (result->ob_refcnt == 1)
1289 PyUnicode_Resize(&result, len-1);
1290 else {
1291 PyObject *v;
1292 v = PyUnicode_FromUnicode(s, len-1);
1293 Py_DECREF(result);
1294 result = v;
1295 }
1296 }
1297 }
1298#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001299 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001300}
1301
1302/* Python method */
1303
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001304static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001305file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001306{
Guido van Rossum789a1611997-05-10 22:33:55 +00001307 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001308
Guido van Rossumd7297e61992-07-06 14:19:26 +00001309 if (f->f_fp == NULL)
1310 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001311 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001312 return NULL;
1313 if (n == 0)
1314 return PyString_FromString("");
1315 if (n < 0)
1316 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001317 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001318}
1319
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001320static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001321file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001322{
Guido van Rossum789a1611997-05-10 22:33:55 +00001323 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001324 PyObject *list;
1325 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001326 char small_buffer[SMALLCHUNK];
1327 char *buffer = small_buffer;
1328 size_t buffersize = SMALLCHUNK;
1329 PyObject *big_buffer = NULL;
1330 size_t nfilled = 0;
1331 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001332 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001333 char *p, *q, *end;
1334 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001335 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001336
Guido van Rossumd7297e61992-07-06 14:19:26 +00001337 if (f->f_fp == NULL)
1338 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001339 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001340 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001341 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001342 return NULL;
1343 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001344 if (shortread)
1345 nread = 0;
1346 else {
1347 Py_BEGIN_ALLOW_THREADS
1348 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001349 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001350 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001351 Py_END_ALLOW_THREADS
1352 shortread = (nread < buffersize-nfilled);
1353 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001354 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001355 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001356 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001357 break;
1358 PyErr_SetFromErrno(PyExc_IOError);
1359 clearerr(f->f_fp);
1360 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001361 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001362 list = NULL;
1363 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001364 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001365 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001366 p = memchr(buffer+nfilled, '\n', nread);
1367 if (p == NULL) {
1368 /* Need a larger buffer to fit this line */
1369 nfilled += nread;
1370 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001371 if (buffersize > INT_MAX) {
1372 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001373 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001374 goto error;
1375 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001376 if (big_buffer == NULL) {
1377 /* Create the big buffer */
1378 big_buffer = PyString_FromStringAndSize(
1379 NULL, buffersize);
1380 if (big_buffer == NULL)
1381 goto error;
1382 buffer = PyString_AS_STRING(big_buffer);
1383 memcpy(buffer, small_buffer, nfilled);
1384 }
1385 else {
1386 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001387 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1388 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001389 buffer = PyString_AS_STRING(big_buffer);
1390 }
1391 continue;
1392 }
1393 end = buffer+nfilled+nread;
1394 q = buffer;
1395 do {
1396 /* Process complete lines */
1397 p++;
1398 line = PyString_FromStringAndSize(q, p-q);
1399 if (line == NULL)
1400 goto error;
1401 err = PyList_Append(list, line);
1402 Py_DECREF(line);
1403 if (err != 0)
1404 goto error;
1405 q = p;
1406 p = memchr(q, '\n', end-q);
1407 } while (p != NULL);
1408 /* Move the remaining incomplete line to the start */
1409 nfilled = end-q;
1410 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001411 if (sizehint > 0)
1412 if (totalread >= (size_t)sizehint)
1413 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001414 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001415 if (nfilled != 0) {
1416 /* Partial last line */
1417 line = PyString_FromStringAndSize(buffer, nfilled);
1418 if (line == NULL)
1419 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001420 if (sizehint > 0) {
1421 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001422 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001423 if (rest == NULL) {
1424 Py_DECREF(line);
1425 goto error;
1426 }
1427 PyString_Concat(&line, rest);
1428 Py_DECREF(rest);
1429 if (line == NULL)
1430 goto error;
1431 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001432 err = PyList_Append(list, line);
1433 Py_DECREF(line);
1434 if (err != 0)
1435 goto error;
1436 }
1437 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001438 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001439 return list;
1440}
1441
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001442static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001443file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001444{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001445 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001446 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001447 if (f->f_fp == NULL)
1448 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001449 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001450 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001451 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001452 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001453 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001454 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001455 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001456 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001457 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001458 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001459 return NULL;
1460 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001461 Py_INCREF(Py_None);
1462 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001463}
1464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001465static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001466file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001467{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001468#define CHUNKSIZE 1000
1469 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001470 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001471 PyObject *result;
1472 int i, j, index, len, nwritten, islist;
1473
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001474 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001475 if (f->f_fp == NULL)
1476 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001477
1478 result = NULL;
1479 list = NULL;
1480 islist = PyList_Check(seq);
1481 if (islist)
1482 it = NULL;
1483 else {
1484 it = PyObject_GetIter(seq);
1485 if (it == NULL) {
1486 PyErr_SetString(PyExc_TypeError,
1487 "writelines() requires an iterable argument");
1488 return NULL;
1489 }
1490 /* From here on, fail by going to error, to reclaim "it". */
1491 list = PyList_New(CHUNKSIZE);
1492 if (list == NULL)
1493 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001494 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001495
1496 /* Strategy: slurp CHUNKSIZE lines into a private list,
1497 checking that they are all strings, then write that list
1498 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001499 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001500 if (islist) {
1501 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001502 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001503 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001504 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001505 j = PyList_GET_SIZE(list);
1506 }
1507 else {
1508 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001509 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001510 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001511 if (PyErr_Occurred())
1512 goto error;
1513 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001514 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001515 PyList_SetItem(list, j, line);
1516 }
1517 }
1518 if (j == 0)
1519 break;
1520
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001521 /* Check that all entries are indeed strings. If not,
1522 apply the same rules as for file.write() and
1523 convert the results to strings. This is slow, but
1524 seems to be the only way since all conversion APIs
1525 could potentially execute Python code. */
1526 for (i = 0; i < j; i++) {
1527 PyObject *v = PyList_GET_ITEM(list, i);
1528 if (!PyString_Check(v)) {
1529 const char *buffer;
1530 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001531 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001532 PyObject_AsReadBuffer(v,
1533 (const void**)&buffer,
1534 &len)) ||
1535 PyObject_AsCharBuffer(v,
1536 &buffer,
1537 &len))) {
1538 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001539 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001540 goto error;
1541 }
1542 line = PyString_FromStringAndSize(buffer,
1543 len);
1544 if (line == NULL)
1545 goto error;
1546 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001547 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001548 }
1549 }
1550
1551 /* Since we are releasing the global lock, the
1552 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001553 Py_BEGIN_ALLOW_THREADS
1554 f->f_softspace = 0;
1555 errno = 0;
1556 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001557 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001558 len = PyString_GET_SIZE(line);
1559 nwritten = fwrite(PyString_AS_STRING(line),
1560 1, len, f->f_fp);
1561 if (nwritten != len) {
1562 Py_BLOCK_THREADS
1563 PyErr_SetFromErrno(PyExc_IOError);
1564 clearerr(f->f_fp);
1565 goto error;
1566 }
1567 }
1568 Py_END_ALLOW_THREADS
1569
1570 if (j < CHUNKSIZE)
1571 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001572 }
1573
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001574 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001575 result = Py_None;
1576 error:
1577 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001578 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001579 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001580#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001581}
1582
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001583static PyObject *
1584file_getiter(PyFileObject *f)
1585{
1586 if (f->f_fp == NULL)
1587 return err_closed();
1588 Py_INCREF(f);
1589 return (PyObject *)f;
1590}
1591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001592PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001593"readline([size]) -> next line from the file, as a string.\n"
1594"\n"
1595"Retain newline. A non-negative size argument limits the maximum\n"
1596"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001597"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001598
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001599PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001600"read([size]) -> read at most size bytes, returned as a string.\n"
1601"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001602"If the size argument is negative or omitted, read until EOF is reached.\n"
1603"Notice that when in non-blocking mode, less data than what was requested\n"
1604"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001606PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001607"write(str) -> None. Write string str to file.\n"
1608"\n"
1609"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001610"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001612PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001613"fileno() -> integer \"file descriptor\".\n"
1614"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001615"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001617PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001618"seek(offset[, whence]) -> None. Move to new file position.\n"
1619"\n"
1620"Argument offset is a byte count. Optional argument whence defaults to\n"
1621"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1622"(move relative to current position, positive or negative), and 2 (move\n"
1623"relative to end of file, usually negative, although many platforms allow\n"
1624"seeking beyond the end of a file).\n"
1625"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001626"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001627
Guido van Rossumd7047b31995-01-02 19:07:15 +00001628#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001629PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001630"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1631"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001632"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001633#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635PyDoc_STRVAR(tell_doc,
1636"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001638PyDoc_STRVAR(readinto_doc,
1639"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001641PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001642"readlines([size]) -> list of strings, each a line from the file.\n"
1643"\n"
1644"Call readline() repeatedly and return a list of the lines so read.\n"
1645"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001646"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001648PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001649"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001650"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001651"For backward compatibility. File objects now include the performance\n"
1652"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001653
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001654PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001655"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001656"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001657"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001658"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001660PyDoc_STRVAR(flush_doc,
1661"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001663PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001664"close() -> None or (perhaps) an integer. Close the file.\n"
1665"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001666"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001667"further I/O operations. close() may be called more than once without\n"
1668"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001669"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001671PyDoc_STRVAR(isatty_doc,
1672"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001673
1674static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001675 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1676 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1677 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1678 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1679 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001680#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001681 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001682#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001683 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1684 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1685 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1686 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1687 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1688 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1689 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1690 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1691 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001692};
1693
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001694#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001695
Guido van Rossum6f799372001-09-20 20:46:19 +00001696static PyMemberDef file_memberlist[] = {
1697 {"softspace", T_INT, OFF(f_softspace), 0,
1698 "flag indicating that a space needs to be printed; used by print"},
1699 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001700 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001701 {"name", T_OBJECT, OFF(f_name), RO,
1702 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001703 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1704 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001705 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001706 {NULL} /* Sentinel */
1707};
1708
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001709static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001711{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001712 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001713}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001714#ifdef WITH_UNIVERSAL_NEWLINES
1715static PyObject *
1716get_newlines(PyFileObject *f, void *closure)
1717{
1718 switch (f->f_newlinetypes) {
1719 case NEWLINE_UNKNOWN:
1720 Py_INCREF(Py_None);
1721 return Py_None;
1722 case NEWLINE_CR:
1723 return PyString_FromString("\r");
1724 case NEWLINE_LF:
1725 return PyString_FromString("\n");
1726 case NEWLINE_CR|NEWLINE_LF:
1727 return Py_BuildValue("(ss)", "\r", "\n");
1728 case NEWLINE_CRLF:
1729 return PyString_FromString("\r\n");
1730 case NEWLINE_CR|NEWLINE_CRLF:
1731 return Py_BuildValue("(ss)", "\r", "\r\n");
1732 case NEWLINE_LF|NEWLINE_CRLF:
1733 return Py_BuildValue("(ss)", "\n", "\r\n");
1734 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1735 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1736 default:
Jeremy Hylton8b735422002-08-14 21:01:41 +00001737 PyErr_Format(PyExc_SystemError,
1738 "Unknown newlines value 0x%x\n",
1739 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001740 return NULL;
1741 }
1742}
1743#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +00001744
Guido van Rossum32d34c82001-09-20 21:45:26 +00001745static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001746 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001747#ifdef WITH_UNIVERSAL_NEWLINES
Jeremy Hylton8b735422002-08-14 21:01:41 +00001748 {"newlines", (getter)get_newlines, NULL,
1749 "end-of-line convention used in this file"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001750#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751 {0},
1752};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001753
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001754static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001755drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001756{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001757 if (f->f_buf != NULL) {
1758 PyMem_Free(f->f_buf);
1759 f->f_buf = NULL;
1760 }
Guido van Rossum65967252001-04-21 13:20:18 +00001761}
1762
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001763/* Make sure that file has a readahead buffer with at least one byte
1764 (unless at EOF) and no more than bufsize. Returns negative value on
1765 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001766static int
1767readahead(PyFileObject *f, int bufsize)
1768{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001769 int chunksize;
1770
1771 if (f->f_buf != NULL) {
1772 if( (f->f_bufend - f->f_bufptr) >= 1)
1773 return 0;
1774 else
1775 drop_readahead(f);
1776 }
1777 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1778 return -1;
1779 }
1780 Py_BEGIN_ALLOW_THREADS
1781 errno = 0;
1782 chunksize = Py_UniversalNewlineFread(
1783 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1784 Py_END_ALLOW_THREADS
1785 if (chunksize == 0) {
1786 if (ferror(f->f_fp)) {
1787 PyErr_SetFromErrno(PyExc_IOError);
1788 clearerr(f->f_fp);
1789 drop_readahead(f);
1790 return -1;
1791 }
1792 }
1793 f->f_bufptr = f->f_buf;
1794 f->f_bufend = f->f_buf + chunksize;
1795 return 0;
1796}
1797
1798/* Used by file_iternext. The returned string will start with 'skip'
1799 uninitialized bytes followed by the remainder of the line. Don't be
1800 horrified by the recursive call: maximum recursion depth is limited by
1801 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1802
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001803static PyStringObject *
1804readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1805{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001806 PyStringObject* s;
1807 char *bufptr;
1808 char *buf;
1809 int len;
1810
1811 if (f->f_buf == NULL)
1812 if (readahead(f, bufsize) < 0)
1813 return NULL;
1814
1815 len = f->f_bufend - f->f_bufptr;
1816 if (len == 0)
1817 return (PyStringObject *)
1818 PyString_FromStringAndSize(NULL, skip);
1819 bufptr = memchr(f->f_bufptr, '\n', len);
1820 if (bufptr != NULL) {
1821 bufptr++; /* Count the '\n' */
1822 len = bufptr - f->f_bufptr;
1823 s = (PyStringObject *)
1824 PyString_FromStringAndSize(NULL, skip+len);
1825 if (s == NULL)
1826 return NULL;
1827 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1828 f->f_bufptr = bufptr;
1829 if (bufptr == f->f_bufend)
1830 drop_readahead(f);
1831 } else {
1832 bufptr = f->f_bufptr;
1833 buf = f->f_buf;
1834 f->f_buf = NULL; /* Force new readahead buffer */
1835 s = readahead_get_line_skip(
1836 f, skip+len, bufsize + (bufsize>>2) );
1837 if (s == NULL) {
1838 PyMem_Free(buf);
1839 return NULL;
1840 }
1841 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1842 PyMem_Free(buf);
1843 }
1844 return s;
1845}
1846
1847/* A larger buffer size may actually decrease performance. */
1848#define READAHEAD_BUFSIZE 8192
1849
1850static PyObject *
1851file_iternext(PyFileObject *f)
1852{
1853 PyStringObject* l;
1854
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001855 if (f->f_fp == NULL)
1856 return err_closed();
1857
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001858 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1859 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1860 Py_XDECREF(l);
1861 return NULL;
1862 }
1863 return (PyObject *)l;
1864}
1865
1866
Tim Peters59c9a642001-09-13 05:38:56 +00001867static PyObject *
1868file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1869{
Tim Peters44410012001-09-14 03:26:08 +00001870 PyObject *self;
1871 static PyObject *not_yet_string;
1872
1873 assert(type != NULL && type->tp_alloc != NULL);
1874
1875 if (not_yet_string == NULL) {
1876 not_yet_string = PyString_FromString("<uninitialized file>");
1877 if (not_yet_string == NULL)
1878 return NULL;
1879 }
1880
1881 self = type->tp_alloc(type, 0);
1882 if (self != NULL) {
1883 /* Always fill in the name and mode, so that nobody else
1884 needs to special-case NULLs there. */
1885 Py_INCREF(not_yet_string);
1886 ((PyFileObject *)self)->f_name = not_yet_string;
1887 Py_INCREF(not_yet_string);
1888 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001889 Py_INCREF(Py_None);
1890 ((PyFileObject *)self)->f_encoding = Py_None;
Tim Peters44410012001-09-14 03:26:08 +00001891 }
1892 return self;
1893}
1894
1895static int
1896file_init(PyObject *self, PyObject *args, PyObject *kwds)
1897{
1898 PyFileObject *foself = (PyFileObject *)self;
1899 int ret = 0;
Tim Peters59c9a642001-09-13 05:38:56 +00001900 static char *kwlist[] = {"name", "mode", "buffering", 0};
1901 char *name = NULL;
1902 char *mode = "r";
1903 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001904 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001905
1906 assert(PyFile_Check(self));
1907 if (foself->f_fp != NULL) {
1908 /* Have to close the existing file first. */
1909 PyObject *closeresult = file_close(foself);
1910 if (closeresult == NULL)
1911 return -1;
1912 Py_DECREF(closeresult);
1913 }
Tim Peters59c9a642001-09-13 05:38:56 +00001914
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001915#ifdef Py_WIN_WIDE_FILENAMES
1916 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1917 PyObject *po;
1918 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1919 kwlist, &po, &mode, &bufsize)) {
1920 wideargument = 1;
1921 if (fill_file_fields(foself, NULL, name, mode,
1922 fclose, po) == NULL)
1923 goto Error;
1924 } else {
1925 /* Drop the argument parsing error as narrow
1926 strings are also valid. */
1927 PyErr_Clear();
1928 }
1929 }
1930#endif
1931
1932 if (!wideargument) {
1933 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1934 Py_FileSystemDefaultEncoding,
1935 &name,
1936 &mode, &bufsize))
1937 return -1;
1938 if (fill_file_fields(foself, NULL, name, mode,
1939 fclose, NULL) == NULL)
1940 goto Error;
1941 }
Tim Peters44410012001-09-14 03:26:08 +00001942 if (open_the_file(foself, name, mode) == NULL)
1943 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001944 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001945 PyFile_SetBufSize(self, bufsize);
1946 goto Done;
1947
1948Error:
1949 ret = -1;
1950 /* fall through */
1951Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001952 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001953 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001954}
1955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001956PyDoc_VAR(file_doc) =
1957PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001958"file(name[, mode[, buffering]]) -> file object\n"
1959"\n"
1960"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1961"writing or appending. The file will be created if it doesn't exist\n"
1962"when opened for writing or appending; it will be truncated when\n"
1963"opened for writing. Add a 'b' to the mode for binary files.\n"
1964"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1965"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001966"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001968#ifdef WITH_UNIVERSAL_NEWLINES
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001969PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001970"Add a 'U' to mode to open the file for input with universal newline\n"
1971"support. Any line ending in the input file will be seen as a '\\n'\n"
1972"in Python. Also, a file so opened gains the attribute 'newlines';\n"
1973"the value for this attribute is one of None (no newline read yet),\n"
1974"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
1975"\n"
1976"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001977)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001978#endif /* WITH_UNIVERSAL_NEWLINES */
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001979PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001980"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001981"Note: open() is an alias for file()."
1982);
Tim Peters59c9a642001-09-13 05:38:56 +00001983
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001984PyTypeObject PyFile_Type = {
1985 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001986 0,
1987 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001988 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001989 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001990 (destructor)file_dealloc, /* tp_dealloc */
1991 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 0, /* tp_getattr */
1993 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001994 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001996 0, /* tp_as_number */
1997 0, /* tp_as_sequence */
1998 0, /* tp_as_mapping */
1999 0, /* tp_hash */
2000 0, /* tp_call */
2001 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002003 /* softspace is writable: we must supply tp_setattro */
2004 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002005 0, /* tp_as_buffer */
Guido van Rossum9475a232001-10-05 20:51:39 +00002006 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002007 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008 0, /* tp_traverse */
2009 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002010 0, /* tp_richcompare */
2011 0, /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002012 (getiterfunc)file_getiter, /* tp_iter */
2013 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 file_methods, /* tp_methods */
2015 file_memberlist, /* tp_members */
2016 file_getsetlist, /* tp_getset */
2017 0, /* tp_base */
2018 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002019 0, /* tp_descr_get */
2020 0, /* tp_descr_set */
2021 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00002022 (initproc)file_init, /* tp_init */
2023 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002024 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002025 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002026};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002027
2028/* Interface for the 'soft space' between print items. */
2029
2030int
Fred Drakefd99de62000-07-09 05:02:18 +00002031PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002032{
2033 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002034 if (f == NULL) {
2035 /* Do nothing */
2036 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037 else if (PyFile_Check(f)) {
2038 oldflag = ((PyFileObject *)f)->f_softspace;
2039 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002040 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002041 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002042 PyObject *v;
2043 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002044 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002045 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002046 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002047 if (PyInt_Check(v))
2048 oldflag = PyInt_AsLong(v);
2049 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002050 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002051 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002052 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002053 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002054 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002055 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2056 PyErr_Clear();
2057 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002058 }
2059 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00002060 return oldflag;
2061}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002062
2063/* Interfaces to write objects/strings to file-like objects */
2064
2065int
Fred Drakefd99de62000-07-09 05:02:18 +00002066PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002067{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002069 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002070 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002071 return -1;
2072 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073 else if (PyFile_Check(f)) {
2074 FILE *fp = PyFile_AsFile(f);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002075 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2076 int result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002077 if (fp == NULL) {
2078 err_closed();
2079 return -1;
2080 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002081#ifdef Py_USING_UNICODE
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002082 if ((flags & Py_PRINT_RAW) &&
2083 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002084 char *cenc = PyString_AS_STRING(enc);
2085 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2086 if (value == NULL)
2087 return -1;
2088 } else {
2089 value = v;
2090 Py_INCREF(value);
2091 }
2092 result = PyObject_Print(value, fp, flags);
2093 Py_DECREF(value);
2094 return result;
2095#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002097#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002098 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002100 if (writer == NULL)
2101 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002102 if (flags & Py_PRINT_RAW) {
2103 if (PyUnicode_Check(v)) {
2104 value = v;
2105 Py_INCREF(value);
2106 } else
2107 value = PyObject_Str(v);
2108 }
2109 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002110 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002111 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002112 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002113 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002114 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 args = Py_BuildValue("(O)", value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002116 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 Py_DECREF(value);
2118 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002119 return -1;
2120 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002121 result = PyEval_CallObject(writer, args);
2122 Py_DECREF(args);
2123 Py_DECREF(value);
2124 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002125 if (result == NULL)
2126 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002127 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002128 return 0;
2129}
2130
Guido van Rossum27a60b11997-05-22 22:25:11 +00002131int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002132PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002133{
2134 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002135 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002136 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002137 PyErr_SetString(PyExc_SystemError,
2138 "null file for PyFile_WriteString");
2139 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002140 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141 else if (PyFile_Check(f)) {
2142 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002143 if (fp == NULL) {
2144 err_closed();
2145 return -1;
2146 }
2147 fputs(s, fp);
2148 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002149 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150 else if (!PyErr_Occurred()) {
2151 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002152 int err;
2153 if (v == NULL)
2154 return -1;
2155 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2156 Py_DECREF(v);
2157 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002158 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002159 else
2160 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002161}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002162
2163/* Try to get a file-descriptor from a Python object. If the object
2164 is an integer or long integer, its value is returned. If not, the
2165 object's fileno() method is called if it exists; the method must return
2166 an integer or long integer, which is returned as the file descriptor value.
2167 -1 is returned on failure.
2168*/
2169
2170int PyObject_AsFileDescriptor(PyObject *o)
2171{
2172 int fd;
2173 PyObject *meth;
2174
2175 if (PyInt_Check(o)) {
2176 fd = PyInt_AsLong(o);
2177 }
2178 else if (PyLong_Check(o)) {
2179 fd = PyLong_AsLong(o);
2180 }
2181 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2182 {
2183 PyObject *fno = PyEval_CallObject(meth, NULL);
2184 Py_DECREF(meth);
2185 if (fno == NULL)
2186 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002187
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002188 if (PyInt_Check(fno)) {
2189 fd = PyInt_AsLong(fno);
2190 Py_DECREF(fno);
2191 }
2192 else if (PyLong_Check(fno)) {
2193 fd = PyLong_AsLong(fno);
2194 Py_DECREF(fno);
2195 }
2196 else {
2197 PyErr_SetString(PyExc_TypeError,
2198 "fileno() returned a non-integer");
2199 Py_DECREF(fno);
2200 return -1;
2201 }
2202 }
2203 else {
2204 PyErr_SetString(PyExc_TypeError,
2205 "argument must be an int, or have a fileno() method.");
2206 return -1;
2207 }
2208
2209 if (fd < 0) {
2210 PyErr_Format(PyExc_ValueError,
2211 "file descriptor cannot be a negative integer (%i)",
2212 fd);
2213 return -1;
2214 }
2215 return fd;
2216}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002217
2218#ifdef WITH_UNIVERSAL_NEWLINES
2219/* From here on we need access to the real fgets and fread */
2220#undef fgets
2221#undef fread
2222
2223/*
2224** Py_UniversalNewlineFgets is an fgets variation that understands
2225** all of \r, \n and \r\n conventions.
2226** The stream should be opened in binary mode.
2227** If fobj is NULL the routine always does newline conversion, and
2228** it may peek one char ahead to gobble the second char in \r\n.
2229** If fobj is non-NULL it must be a PyFileObject. In this case there
2230** is no readahead but in stead a flag is used to skip a following
2231** \n on the next read. Also, if the file is open in binary mode
2232** the whole conversion is skipped. Finally, the routine keeps track of
2233** the different types of newlines seen.
2234** Note that we need no error handling: fgets() treats error and eof
2235** identically.
2236*/
2237char *
2238Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2239{
2240 char *p = buf;
2241 int c;
2242 int newlinetypes = 0;
2243 int skipnextlf = 0;
2244 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002245
Jack Jansen7b8c7542002-04-14 20:12:41 +00002246 if (fobj) {
2247 if (!PyFile_Check(fobj)) {
2248 errno = ENXIO; /* What can you do... */
2249 return NULL;
2250 }
2251 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2252 if ( !univ_newline )
2253 return fgets(buf, n, stream);
2254 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2255 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2256 }
2257 FLOCKFILE(stream);
2258 c = 'x'; /* Shut up gcc warning */
2259 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2260 if (skipnextlf ) {
2261 skipnextlf = 0;
2262 if (c == '\n') {
2263 /* Seeing a \n here with skipnextlf true
2264 ** means we saw a \r before.
2265 */
2266 newlinetypes |= NEWLINE_CRLF;
2267 c = GETC(stream);
2268 if (c == EOF) break;
2269 } else {
2270 /*
2271 ** Note that c == EOF also brings us here,
2272 ** so we're okay if the last char in the file
2273 ** is a CR.
2274 */
2275 newlinetypes |= NEWLINE_CR;
2276 }
2277 }
2278 if (c == '\r') {
2279 /* A \r is translated into a \n, and we skip
2280 ** an adjacent \n, if any. We don't set the
2281 ** newlinetypes flag until we've seen the next char.
2282 */
2283 skipnextlf = 1;
2284 c = '\n';
2285 } else if ( c == '\n') {
2286 newlinetypes |= NEWLINE_LF;
2287 }
2288 *p++ = c;
2289 if (c == '\n') break;
2290 }
2291 if ( c == EOF && skipnextlf )
2292 newlinetypes |= NEWLINE_CR;
2293 FUNLOCKFILE(stream);
2294 *p = '\0';
2295 if (fobj) {
2296 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2297 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2298 } else if ( skipnextlf ) {
2299 /* If we have no file object we cannot save the
2300 ** skipnextlf flag. We have to readahead, which
2301 ** will cause a pause if we're reading from an
2302 ** interactive stream, but that is very unlikely
2303 ** unless we're doing something silly like
2304 ** execfile("/dev/tty").
2305 */
2306 c = GETC(stream);
2307 if ( c != '\n' )
2308 ungetc(c, stream);
2309 }
2310 if (p == buf)
2311 return NULL;
2312 return buf;
2313}
2314
2315/*
2316** Py_UniversalNewlineFread is an fread variation that understands
2317** all of \r, \n and \r\n conventions.
2318** The stream should be opened in binary mode.
2319** fobj must be a PyFileObject. In this case there
2320** is no readahead but in stead a flag is used to skip a following
2321** \n on the next read. Also, if the file is open in binary mode
2322** the whole conversion is skipped. Finally, the routine keeps track of
2323** the different types of newlines seen.
2324*/
2325size_t
Tim Peters058b1412002-04-21 07:29:14 +00002326Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002327 FILE *stream, PyObject *fobj)
2328{
Tim Peters058b1412002-04-21 07:29:14 +00002329 char *dst = buf;
2330 PyFileObject *f = (PyFileObject *)fobj;
2331 int newlinetypes, skipnextlf;
2332
2333 assert(buf != NULL);
2334 assert(stream != NULL);
2335
Jack Jansen7b8c7542002-04-14 20:12:41 +00002336 if (!fobj || !PyFile_Check(fobj)) {
2337 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002338 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002339 }
Tim Peters058b1412002-04-21 07:29:14 +00002340 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002341 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002342 newlinetypes = f->f_newlinetypes;
2343 skipnextlf = f->f_skipnextlf;
2344 /* Invariant: n is the number of bytes remaining to be filled
2345 * in the buffer.
2346 */
2347 while (n) {
2348 size_t nread;
2349 int shortread;
2350 char *src = dst;
2351
2352 nread = fread(dst, 1, n, stream);
2353 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002354 if (nread == 0)
2355 break;
2356
Tim Peterse1682a82002-04-21 18:15:20 +00002357 n -= nread; /* assuming 1 byte out for each in; will adjust */
2358 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002359 while (nread--) {
2360 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002361 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002362 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002363 *dst++ = '\n';
2364 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002365 }
2366 else if (skipnextlf && c == '\n') {
2367 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002368 skipnextlf = 0;
2369 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002370 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002371 }
2372 else {
2373 /* Normal char to be stored in buffer. Also
2374 * update the newlinetypes flag if either this
2375 * is an LF or the previous char was a CR.
2376 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002377 if (c == '\n')
2378 newlinetypes |= NEWLINE_LF;
2379 else if (skipnextlf)
2380 newlinetypes |= NEWLINE_CR;
2381 *dst++ = c;
2382 skipnextlf = 0;
2383 }
2384 }
Tim Peters058b1412002-04-21 07:29:14 +00002385 if (shortread) {
2386 /* If this is EOF, update type flags. */
2387 if (skipnextlf && feof(stream))
2388 newlinetypes |= NEWLINE_CR;
2389 break;
2390 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002391 }
Tim Peters058b1412002-04-21 07:29:14 +00002392 f->f_newlinetypes = newlinetypes;
2393 f->f_skipnextlf = skipnextlf;
2394 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002395}
2396#endif