blob: 05c9f4a9b257bc0d68f2daef32475eaf23eb7c61 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossumff7e83d1999-08-27 20:39:37 +00006#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00007#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00008#endif /* DONT_HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +00009
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000010#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000011#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000012/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000013#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000014#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000015#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000016#endif
17
Mark Hammondc2e85bd2002-10-03 05:10:39 +000018#ifdef _MSC_VER
19/* Need GetVersion to see if on NT so safe to use _wfopen */
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22#endif /* _MSC_VER */
23
Andrew MacIntyrec4874392002-02-26 11:36:35 +000024#if defined(PYOS_OS2) && defined(PYCC_GCC)
25#include <io.h>
26#endif
27
Guido van Rossumc0b618a1997-05-02 03:12:38 +000028#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000029
Guido van Rossumff7e83d1999-08-27 20:39:37 +000030#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000031#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000032#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000033
Jack Jansen7b8c7542002-04-14 20:12:41 +000034#ifdef HAVE_GETC_UNLOCKED
35#define GETC(f) getc_unlocked(f)
36#define FLOCKFILE(f) flockfile(f)
37#define FUNLOCKFILE(f) funlockfile(f)
38#else
39#define GETC(f) getc(f)
40#define FLOCKFILE(f)
41#define FUNLOCKFILE(f)
42#endif
43
Jack Jansen7b8c7542002-04-14 20:12:41 +000044/* Bits in f_newlinetypes */
45#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
46#define NEWLINE_CR 1 /* \r newline seen */
47#define NEWLINE_LF 2 /* \n newline seen */
48#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000049
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000050FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000051PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000053 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000055 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000056 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057}
58
Guido van Rossumc0b618a1997-05-02 03:12:38 +000059PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000060PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000063 return NULL;
64 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066}
67
Neil Schemenauered19b882002-03-23 02:06:50 +000068/* On Unix, fopen will succeed for directories.
69 In Python, there should be no file objects referring to
70 directories, so we need a check. */
71
72static PyFileObject*
73dircheck(PyFileObject* f)
74{
75#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
76 struct stat buf;
77 if (f->f_fp == NULL)
78 return f;
79 if (fstat(fileno(f->f_fp), &buf) == 0 &&
80 S_ISDIR(buf.st_mode)) {
81#ifdef HAVE_STRERROR
82 char *msg = strerror(EISDIR);
83#else
84 char *msg = "Is a directory";
85#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000086 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000087 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000088 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000089 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000090 return NULL;
91 }
92#endif
93 return f;
94}
95
Tim Peters59c9a642001-09-13 05:38:56 +000096
97static PyObject *
98fill_file_fields(PyFileObject *f, FILE *fp, char *name, char *mode,
Mark Hammondc2e85bd2002-10-03 05:10:39 +000099 int (*close)(FILE *), PyObject *wname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100{
Tim Peters59c9a642001-09-13 05:38:56 +0000101 assert(f != NULL);
102 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000103 assert(f->f_fp == NULL);
104
105 Py_DECREF(f->f_name);
106 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000107 Py_DECREF(f->f_encoding);
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000108#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000109 if (wname)
110 f->f_name = PyUnicode_FromObject(wname);
111 else
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000112#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000113 f->f_name = PyString_FromString(name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000114 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000115
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000116 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000117 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000118 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000119 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000120 f->f_univ_newline = (strchr(mode, 'U') != NULL);
121 f->f_newlinetypes = NEWLINE_UNKNOWN;
122 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000123 Py_INCREF(Py_None);
124 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000125
Tim Peters59c9a642001-09-13 05:38:56 +0000126 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000129 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131}
132
Tim Peters59c9a642001-09-13 05:38:56 +0000133static PyObject *
134open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135{
Tim Peters59c9a642001-09-13 05:38:56 +0000136 assert(f != NULL);
137 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000138#ifdef MS_WINDOWS
139 /* windows ignores the passed name in order to support Unicode */
140 assert(f->f_name != NULL);
141#else
Tim Peters59c9a642001-09-13 05:38:56 +0000142 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000143#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000144 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000145 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000146
Tim Peters8fa45672001-09-13 21:01:29 +0000147 /* rexec.py can't stop a user from getting the file() constructor --
148 all they have to do is get *any* file object f, and then do
149 type(f). Here we prevent them from doing damage with it. */
150 if (PyEval_GetRestricted()) {
151 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000152 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000153 return NULL;
154 }
Tim Petersa27a1502001-11-09 20:59:14 +0000155 errno = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000156#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000157 if (*mode == '*') {
158 FILE *fopenRF();
159 f->f_fp = fopenRF(name, mode+1);
160 }
161 else
162#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000163 {
Jack Jansen7b8c7542002-04-14 20:12:41 +0000164 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
165 mode = "rb";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000166#ifdef MS_WINDOWS
167 if (PyUnicode_Check(f->f_name)) {
Tim Petersf1827cf2003-09-07 03:30:18 +0000168 PyObject *wmode;
169 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000170 if (f->f_name && wmode) {
171 Py_BEGIN_ALLOW_THREADS
172 /* PyUnicode_AS_UNICODE OK without thread
173 lock as it is a simple dereference. */
174 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
175 PyUnicode_AS_UNICODE(wmode));
176 Py_END_ALLOW_THREADS
177 }
178 Py_XDECREF(wmode);
179 }
180#endif
181 if (NULL == f->f_fp && NULL != name) {
182 Py_BEGIN_ALLOW_THREADS
183 f->f_fp = fopen(name, mode);
184 Py_END_ALLOW_THREADS
185 }
Guido van Rossumff4949e1992-08-05 19:58:53 +0000186 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000187 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000188#ifdef _MSC_VER
189 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
190 * across all Windows flavors. When it sets EINVAL varies
191 * across Windows flavors, the exact conditions aren't
192 * documented, and the answer lies in the OS's implementation
193 * of Win32's CreateFile function (whose source is secret).
194 * Seems the best we can do is map EINVAL to ENOENT.
195 */
196 if (errno == 0) /* bad mode string */
197 errno = EINVAL;
198 else if (errno == EINVAL) /* unknown, but not a mode string */
199 errno = ENOENT;
200#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000201 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000202 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000203 mode);
204 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000205#ifdef MS_WINDOWS
206 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
207#else
Jeremy Hylton41c83212001-11-09 16:17:24 +0000208 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000209#endif /* MS_WINDOWS */
Tim Peters59c9a642001-09-13 05:38:56 +0000210 f = NULL;
211 }
Tim Peters2ea91112002-04-08 04:13:12 +0000212 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000213 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000214 return (PyObject *)f;
215}
216
217PyObject *
218PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
219{
Tim Peters44410012001-09-14 03:26:08 +0000220 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
221 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000222 if (f != NULL) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000223 if (fill_file_fields(f, fp, name, mode, close, NULL) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000224 Py_DECREF(f);
225 f = NULL;
226 }
227 }
228 return (PyObject *) f;
229}
230
231PyObject *
232PyFile_FromString(char *name, char *mode)
233{
234 extern int fclose(FILE *);
235 PyFileObject *f;
236
237 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
238 if (f != NULL) {
239 if (open_the_file(f, name, mode) == NULL) {
240 Py_DECREF(f);
241 f = NULL;
242 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245}
246
Guido van Rossumb6775db1994-08-01 11:34:53 +0000247void
Fred Drakefd99de62000-07-09 05:02:18 +0000248PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000249{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000250 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000251 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000252 int type;
253 switch (bufsize) {
254 case 0:
255 type = _IONBF;
256 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000257#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000258 case 1:
259 type = _IOLBF;
260 bufsize = BUFSIZ;
261 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000262#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000263 default:
264 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000265#ifndef HAVE_SETVBUF
266 bufsize = BUFSIZ;
267#endif
268 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000269 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000270 fflush(file->f_fp);
271 if (type == _IONBF) {
272 PyMem_Free(file->f_setbuf);
273 file->f_setbuf = NULL;
274 } else {
275 file->f_setbuf = PyMem_Realloc(file->f_setbuf, bufsize);
276 }
277#ifdef HAVE_SETVBUF
278 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000279#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000280 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000281#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000282 }
283}
284
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000285/* Set the encoding used to output Unicode strings.
286 Returh 1 on success, 0 on failure. */
287
288int
289PyFile_SetEncoding(PyObject *f, const char *enc)
290{
291 PyFileObject *file = (PyFileObject*)f;
292 PyObject *str = PyString_FromString(enc);
293 if (!str)
294 return 0;
295 Py_DECREF(file->f_encoding);
296 file->f_encoding = str;
297 return 1;
298}
299
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000301err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000302{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000304 return NULL;
305}
306
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000307static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000308
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309/* Methods */
310
311static void
Fred Drakefd99de62000-07-09 05:02:18 +0000312file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000314 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000315 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000316 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000317 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000318 }
Tim Peters44410012001-09-14 03:26:08 +0000319 Py_XDECREF(f->f_name);
320 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000321 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000322 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000323 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324}
325
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000327file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000328{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000329 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000330#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000331 PyObject *ret = NULL;
332 PyObject *name;
333 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
334 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
335 f->f_fp == NULL ? "closed" : "open",
336 PyString_AsString(name),
337 PyString_AsString(f->f_mode),
338 f);
339 Py_XDECREF(name);
340 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000341#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000342 } else {
343 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000344 f->f_fp == NULL ? "closed" : "open",
345 PyString_AsString(f->f_name),
346 PyString_AsString(f->f_mode),
347 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000348 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349}
350
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000352file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000354 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000356 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000357 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000358 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000359 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000361 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362 f->f_fp = NULL;
363 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000364 PyMem_Free(f->f_setbuf);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000365 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000366 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000367 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368 return PyInt_FromLong((long)sts);
369 Py_INCREF(Py_None);
370 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371}
372
Trent Mickf29f47b2000-08-11 19:02:59 +0000373
Guido van Rossumb8552162001-09-05 14:58:11 +0000374/* Our very own off_t-like type, 64-bit if possible */
375#if !defined(HAVE_LARGEFILE_SUPPORT)
376typedef off_t Py_off_t;
377#elif SIZEOF_OFF_T >= 8
378typedef off_t Py_off_t;
379#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000380typedef fpos_t Py_off_t;
381#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000382#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000383#endif
384
385
Trent Mickf29f47b2000-08-11 19:02:59 +0000386/* a portable fseek() function
387 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000388static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000389_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000390{
Guido van Rossumb8552162001-09-05 14:58:11 +0000391#if !defined(HAVE_LARGEFILE_SUPPORT)
392 return fseek(fp, offset, whence);
393#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000394 return fseeko(fp, offset, whence);
395#elif defined(HAVE_FSEEK64)
396 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000397#elif defined(__BEOS__)
398 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000399#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000400 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
401 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000402 fpos_t pos;
403 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000404 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000405#ifdef MS_WINDOWS
406 fflush(fp);
407 if (_lseeki64(fileno(fp), 0, 2) == -1)
408 return -1;
409#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000410 if (fseek(fp, 0, SEEK_END) != 0)
411 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000412#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000413 /* fall through */
414 case SEEK_CUR:
415 if (fgetpos(fp, &pos) != 0)
416 return -1;
417 offset += pos;
418 break;
419 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000420 }
421 return fsetpos(fp, &offset);
422#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000423#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000424#endif
425}
426
427
428/* a portable ftell() function
429 Return -1 on failure with errno set appropriately, current file
430 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000431static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000432_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000433{
Guido van Rossumb8552162001-09-05 14:58:11 +0000434#if !defined(HAVE_LARGEFILE_SUPPORT)
435 return ftell(fp);
436#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
437 return ftello(fp);
438#elif defined(HAVE_FTELL64)
439 return ftell64(fp);
440#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000441 fpos_t pos;
442 if (fgetpos(fp, &pos) != 0)
443 return -1;
444 return pos;
445#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000446#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000447#endif
448}
449
450
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000452file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000454 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000455 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000456 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000457 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000458
Guido van Rossumd7297e61992-07-06 14:19:26 +0000459 if (f->f_fp == NULL)
460 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000461 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000462 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000463 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000464 return NULL;
465#if !defined(HAVE_LARGEFILE_SUPPORT)
466 offset = PyInt_AsLong(offobj);
467#else
468 offset = PyLong_Check(offobj) ?
469 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
470#endif
471 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000472 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000473
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000475 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000476 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000478
Guido van Rossumff4949e1992-08-05 19:58:53 +0000479 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000481 clearerr(f->f_fp);
482 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000483 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000484 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485 Py_INCREF(Py_None);
486 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000487}
488
Trent Mickf29f47b2000-08-11 19:02:59 +0000489
Guido van Rossumd7047b31995-01-02 19:07:15 +0000490#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000491static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000492file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000493{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000494 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000495 PyObject *newsizeobj = NULL;
496 Py_off_t initialpos;
497 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000498
Guido van Rossumd7047b31995-01-02 19:07:15 +0000499 if (f->f_fp == NULL)
500 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000501 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000502 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000503
Tim Petersf1827cf2003-09-07 03:30:18 +0000504 /* Get current file position. If the file happens to be open for
505 * update and the last operation was an input operation, C doesn't
506 * define what the later fflush() will do, but we promise truncate()
507 * won't change the current position (and fflush() *does* change it
508 * then at least on Windows). The easiest thing is to capture
509 * current pos now and seek back to it at the end.
510 */
511 Py_BEGIN_ALLOW_THREADS
512 errno = 0;
513 initialpos = _portable_ftell(f->f_fp);
514 Py_END_ALLOW_THREADS
515 if (initialpos == -1)
516 goto onioerror;
517
Tim Petersfb05db22002-03-11 00:24:00 +0000518 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000519 * specified value.
520 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000521 if (newsizeobj != NULL) {
522#if !defined(HAVE_LARGEFILE_SUPPORT)
523 newsize = PyInt_AsLong(newsizeobj);
524#else
525 newsize = PyLong_Check(newsizeobj) ?
526 PyLong_AsLongLong(newsizeobj) :
527 PyInt_AsLong(newsizeobj);
528#endif
529 if (PyErr_Occurred())
530 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000531 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000532 else /* default to current position */
533 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000534
Tim Petersf1827cf2003-09-07 03:30:18 +0000535 /* Flush the stream. We're mixing stream-level I/O with lower-level
536 * I/O, and a flush may be necessary to synch both platform views
537 * of the current file state.
538 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000539 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000540 errno = 0;
541 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000543 if (ret != 0)
544 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000545
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000546#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000547 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000548 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000549 {
Tim Petersfb05db22002-03-11 00:24:00 +0000550 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000551
Tim Petersf1827cf2003-09-07 03:30:18 +0000552 /* Have to move current pos to desired endpoint on Windows. */
553 Py_BEGIN_ALLOW_THREADS
554 errno = 0;
555 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
556 Py_END_ALLOW_THREADS
557 if (ret)
558 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000559
Tim Peters8f01b682002-03-12 03:04:44 +0000560 /* Truncate. Note that this may grow the file! */
561 Py_BEGIN_ALLOW_THREADS
562 errno = 0;
563 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000564 ret = hFile == (HANDLE)-1;
565 if (ret == 0) {
566 ret = SetEndOfFile(hFile) == 0;
567 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000568 errno = EACCES;
569 }
570 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000571 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000572 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000573 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000574#else
575 Py_BEGIN_ALLOW_THREADS
576 errno = 0;
577 ret = ftruncate(fileno(f->f_fp), newsize);
578 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000579 if (ret != 0)
580 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000581#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000582
Tim Petersf1827cf2003-09-07 03:30:18 +0000583 /* Restore original file position. */
584 Py_BEGIN_ALLOW_THREADS
585 errno = 0;
586 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
587 Py_END_ALLOW_THREADS
588 if (ret)
589 goto onioerror;
590
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000591 Py_INCREF(Py_None);
592 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000593
594onioerror:
595 PyErr_SetFromErrno(PyExc_IOError);
596 clearerr(f->f_fp);
597 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000598}
599#endif /* HAVE_FTRUNCATE */
600
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000601static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000602file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000603{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000604 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000605
Guido van Rossumd7297e61992-07-06 14:19:26 +0000606 if (f->f_fp == NULL)
607 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000609 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000610 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000612 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000614 clearerr(f->f_fp);
615 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000616 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000617 if (f->f_skipnextlf) {
618 int c;
619 c = GETC(f->f_fp);
620 if (c == '\n') {
621 pos++;
622 f->f_skipnextlf = 0;
623 } else if (c != EOF) ungetc(c, f->f_fp);
624 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000625#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000626 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000627#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000628 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000629#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000630}
631
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000632static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000633file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000634{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000635 if (f->f_fp == NULL)
636 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000638}
639
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000641file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000642{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000643 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000644
Guido van Rossumd7297e61992-07-06 14:19:26 +0000645 if (f->f_fp == NULL)
646 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000648 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000649 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000651 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000653 clearerr(f->f_fp);
654 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000655 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000656 Py_INCREF(Py_None);
657 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000658}
659
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000661file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000662{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000663 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000664 if (f->f_fp == NULL)
665 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000667 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000668 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000669 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000670}
671
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000672
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000673#if BUFSIZ < 8192
674#define SMALLCHUNK 8192
675#else
676#define SMALLCHUNK BUFSIZ
677#endif
678
Guido van Rossum3c259041999-01-14 19:00:14 +0000679#if SIZEOF_INT < 4
680#define BIGCHUNK (512 * 32)
681#else
682#define BIGCHUNK (512 * 1024)
683#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000684
685static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000686new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000687{
688#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000689 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000690 struct stat st;
691 if (fstat(fileno(f->f_fp), &st) == 0) {
692 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000693 /* The following is not a bug: we really need to call lseek()
694 *and* ftell(). The reason is that some stdio libraries
695 mistakenly flush their buffer when ftell() is called and
696 the lseek() call it makes fails, thereby throwing away
697 data that cannot be recovered in any way. To avoid this,
698 we first test lseek(), and only call ftell() if lseek()
699 works. We can't use the lseek() value either, because we
700 need to take the amount of buffered data into account.
701 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000702 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000703 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000704 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000705 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000706 if (pos < 0)
707 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000708 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000709 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000710 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000711 }
712#endif
713 if (currentsize > SMALLCHUNK) {
714 /* Keep doubling until we reach BIGCHUNK;
715 then keep adding BIGCHUNK. */
716 if (currentsize <= BIGCHUNK)
717 return currentsize + currentsize;
718 else
719 return currentsize + BIGCHUNK;
720 }
721 return currentsize + SMALLCHUNK;
722}
723
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000724#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
725#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
726#else
727#ifdef EWOULDBLOCK
728#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
729#else
730#ifdef EAGAIN
731#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
732#else
733#define BLOCKED_ERRNO(x) 0
734#endif
735#endif
736#endif
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000739file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000740{
Guido van Rossum789a1611997-05-10 22:33:55 +0000741 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000742 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000744
Guido van Rossumd7297e61992-07-06 14:19:26 +0000745 if (f->f_fp == NULL)
746 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000747 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000748 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000749 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000750 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000751 else
752 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000753 if (buffersize > INT_MAX) {
754 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000755 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000756 return NULL;
757 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000758 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000759 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000761 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000762 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000763 Py_BEGIN_ALLOW_THREADS
764 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000765 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000766 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000767 Py_END_ALLOW_THREADS
768 if (chunksize == 0) {
769 if (!ferror(f->f_fp))
770 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000771 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000772 /* When in non-blocking mode, data shouldn't
773 * be discarded if a blocking signal was
774 * received. That will also happen if
775 * chunksize != 0, but bytesread < buffersize. */
776 if (bytesread > 0 && BLOCKED_ERRNO(errno))
777 break;
778 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000779 Py_DECREF(v);
780 return NULL;
781 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000782 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000783 if (bytesread < buffersize) {
784 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000785 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000786 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000787 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000788 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000789 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000790 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000791 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000792 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000793 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000794 }
795 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000796 if (bytesread != buffersize)
797 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798 return v;
799}
800
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000801static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000802file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000803{
804 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000805 int ntodo;
806 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000807
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000808 if (f->f_fp == NULL)
809 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000810 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000811 return NULL;
812 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000813 while (ntodo > 0) {
814 Py_BEGIN_ALLOW_THREADS
815 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000816 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000817 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000818 Py_END_ALLOW_THREADS
819 if (nnow == 0) {
820 if (!ferror(f->f_fp))
821 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000822 PyErr_SetFromErrno(PyExc_IOError);
823 clearerr(f->f_fp);
824 return NULL;
825 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000826 ndone += nnow;
827 ntodo -= nnow;
828 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000829 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000830}
831
Tim Peters86821b22001-01-07 21:19:34 +0000832/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000833Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000834
835Under MSVC 6:
836
Tim Peters1c733232001-01-08 04:02:07 +0000837+ MS threadsafe getc is very slow (multiple layers of function calls before+
838 after each character, to lock+unlock the stream).
839+ The stream-locking functions are MS-internal -- can't access them from user
840 code.
841+ There's nothing Tim could find in the MS C or platform SDK libraries that
842 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000843+ MS fgets locks/unlocks only once per line; it's the only hook we have.
844
845So we use fgets for speed(!), despite that it's painful.
846
847MS realloc is also slow.
848
Tim Petersf29b64d2001-01-15 06:33:19 +0000849Reports from other platforms on this method vs getc_unlocked (which MS doesn't
850have):
851 Linux a wash
852 Solaris a wash
853 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000854
Tim Petersf29b64d2001-01-15 06:33:19 +0000855CAUTION: The C std isn't clear about this: in those cases where fgets
856writes something into the buffer, can it write into any position beyond the
857required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
858known on which it does; and it would be a strange way to code fgets. Still,
859getline_via_fgets may not work correctly if it does. The std test
860test_bufio.py should fail if platform fgets() routinely writes beyond the
861trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000862**************************************************************************/
863
Tim Petersf29b64d2001-01-15 06:33:19 +0000864/* Use this routine if told to, or by default on non-get_unlocked()
865 * platforms unless told not to. Yikes! Let's spell that out:
866 * On a platform with getc_unlocked():
867 * By default, use getc_unlocked().
868 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
869 * On a platform without getc_unlocked():
870 * By default, use fgets().
871 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
872 */
873#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
874#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000875#endif
876
Tim Petersf29b64d2001-01-15 06:33:19 +0000877#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
878#undef USE_FGETS_IN_GETLINE
879#endif
880
881#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000882static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000883getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000884{
Tim Peters15b83852001-01-08 00:53:12 +0000885/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000886 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
887 * to fill this much of the buffer with a known value in order to figure out
888 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
889 * than "most" lines, we waste time filling unused buffer slots. 100 is
890 * surely adequate for most peoples' email archives, chewing over source code,
891 * etc -- "regular old text files".
892 * MAXBUFSIZE is the maximum line length that lets us get away with the less
893 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
894 * cautions about boosting that. 300 was chosen because the worst real-life
895 * text-crunching job reported on Python-Dev was a mail-log crawler where over
896 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000897 */
Tim Peters142297a2001-01-15 10:36:56 +0000898#define INITBUFSIZE 100
899#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000900 char* p; /* temp */
901 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000902 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000903 char* pvfree; /* address of next free slot */
904 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000905 size_t nfree; /* # of free buffer slots; pvend-pvfree */
906 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000907 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000908
Tim Peters15b83852001-01-08 00:53:12 +0000909 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000910 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000911 */
Tim Peters142297a2001-01-15 10:36:56 +0000912 total_v_size = INITBUFSIZE; /* start small and pray */
913 pvfree = buf;
914 for (;;) {
915 Py_BEGIN_ALLOW_THREADS
916 pvend = buf + total_v_size;
917 nfree = pvend - pvfree;
918 memset(pvfree, '\n', nfree);
919 p = fgets(pvfree, nfree, fp);
920 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000921
Tim Peters142297a2001-01-15 10:36:56 +0000922 if (p == NULL) {
923 clearerr(fp);
924 if (PyErr_CheckSignals())
925 return NULL;
926 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000927 return v;
928 }
Tim Peters142297a2001-01-15 10:36:56 +0000929 /* fgets read *something* */
930 p = memchr(pvfree, '\n', nfree);
931 if (p != NULL) {
932 /* Did the \n come from fgets or from us?
933 * Since fgets stops at the first \n, and then writes
934 * \0, if it's from fgets a \0 must be next. But if
935 * that's so, it could not have come from us, since
936 * the \n's we filled the buffer with have only more
937 * \n's to the right.
938 */
939 if (p+1 < pvend && *(p+1) == '\0') {
940 /* It's from fgets: we win! In particular,
941 * we haven't done any mallocs yet, and can
942 * build the final result on the first try.
943 */
944 ++p; /* include \n from fgets */
945 }
946 else {
947 /* Must be from us: fgets didn't fill the
948 * buffer and didn't find a newline, so it
949 * must be the last and newline-free line of
950 * the file.
951 */
952 assert(p > pvfree && *(p-1) == '\0');
953 --p; /* don't include \0 from fgets */
954 }
955 v = PyString_FromStringAndSize(buf, p - buf);
956 return v;
957 }
958 /* yuck: fgets overwrote all the newlines, i.e. the entire
959 * buffer. So this line isn't over yet, or maybe it is but
960 * we're exactly at EOF. If we haven't already, try using the
961 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +0000962 */
Tim Peters142297a2001-01-15 10:36:56 +0000963 assert(*(pvend-1) == '\0');
964 if (pvfree == buf) {
965 pvfree = pvend - 1; /* overwrite trailing null */
966 total_v_size = MAXBUFSIZE;
967 }
968 else
969 break;
Tim Peters86821b22001-01-07 21:19:34 +0000970 }
Tim Peters142297a2001-01-15 10:36:56 +0000971
972 /* The stack buffer isn't big enough; malloc a string object and read
973 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +0000974 */
Tim Petersddea2082002-03-23 10:03:50 +0000975 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +0000976 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +0000977 if (v == NULL)
978 return v;
979 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +0000980 memcpy(BUF(v), buf, MAXBUFSIZE-1);
981 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +0000982
983 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +0000984 * after setting p one beyond the end of the line. The code here is
985 * very much like the code above, except reads into v's buffer; see
986 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +0000987 */
988 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +0000989 Py_BEGIN_ALLOW_THREADS
990 pvend = BUF(v) + total_v_size;
991 nfree = pvend - pvfree;
992 memset(pvfree, '\n', nfree);
993 p = fgets(pvfree, nfree, fp);
994 Py_END_ALLOW_THREADS
995
996 if (p == NULL) {
997 clearerr(fp);
998 if (PyErr_CheckSignals()) {
999 Py_DECREF(v);
1000 return NULL;
1001 }
1002 p = pvfree;
1003 break;
1004 }
Tim Peters86821b22001-01-07 21:19:34 +00001005 p = memchr(pvfree, '\n', nfree);
1006 if (p != NULL) {
1007 if (p+1 < pvend && *(p+1) == '\0') {
1008 /* \n came from fgets */
1009 ++p;
1010 break;
1011 }
1012 /* \n came from us; last line of file, no newline */
1013 assert(p > pvfree && *(p-1) == '\0');
1014 --p;
1015 break;
1016 }
1017 /* expand buffer and try again */
1018 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001019 increment = total_v_size >> 2; /* mild exponential growth */
1020 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001021 if (total_v_size > INT_MAX) {
1022 PyErr_SetString(PyExc_OverflowError,
1023 "line is longer than a Python string can hold");
1024 Py_DECREF(v);
1025 return NULL;
1026 }
1027 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1028 return NULL;
1029 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001030 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001031 }
1032 if (BUF(v) + total_v_size != p)
1033 _PyString_Resize(&v, p - BUF(v));
1034 return v;
1035#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001036#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001037}
Tim Petersf29b64d2001-01-15 06:33:19 +00001038#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001039
Guido van Rossum0bd24411991-04-04 15:21:57 +00001040/* Internal routine to get a line.
1041 Size argument interpretation:
1042 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001043 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001044*/
1045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001046static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001047get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001048{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001049 FILE *fp = f->f_fp;
1050 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001051 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001052 size_t total_v_size; /* total # of slots in buffer */
1053 size_t used_v_size; /* # used slots in buffer */
1054 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001055 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001056 int newlinetypes = f->f_newlinetypes;
1057 int skipnextlf = f->f_skipnextlf;
1058 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001059
Jack Jansen7b8c7542002-04-14 20:12:41 +00001060#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001061 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001062 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001063#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001064 total_v_size = n > 0 ? n : 100;
1065 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001066 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001067 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001068 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001069 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001070
Guido van Rossumce5ba841991-03-06 13:06:18 +00001071 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001072 Py_BEGIN_ALLOW_THREADS
1073 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001074 if (univ_newline) {
1075 c = 'x'; /* Shut up gcc warning */
1076 while ( buf != end && (c = GETC(fp)) != EOF ) {
1077 if (skipnextlf ) {
1078 skipnextlf = 0;
1079 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001080 /* Seeing a \n here with
1081 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001082 * saw a \r before.
1083 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001084 newlinetypes |= NEWLINE_CRLF;
1085 c = GETC(fp);
1086 if (c == EOF) break;
1087 } else {
1088 newlinetypes |= NEWLINE_CR;
1089 }
1090 }
1091 if (c == '\r') {
1092 skipnextlf = 1;
1093 c = '\n';
1094 } else if ( c == '\n')
1095 newlinetypes |= NEWLINE_LF;
1096 *buf++ = c;
1097 if (c == '\n') break;
1098 }
1099 if ( c == EOF && skipnextlf )
1100 newlinetypes |= NEWLINE_CR;
1101 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001102 while ((c = GETC(fp)) != EOF &&
1103 (*buf++ = c) != '\n' &&
1104 buf != end)
1105 ;
1106 FUNLOCKFILE(fp);
1107 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001108 f->f_newlinetypes = newlinetypes;
1109 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001110 if (c == '\n')
1111 break;
1112 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001113 if (ferror(fp)) {
1114 PyErr_SetFromErrno(PyExc_IOError);
1115 clearerr(fp);
1116 Py_DECREF(v);
1117 return NULL;
1118 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001119 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001120 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001121 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001122 return NULL;
1123 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001124 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001125 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001126 /* Must be because buf == end */
1127 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001128 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001129 used_v_size = total_v_size;
1130 increment = total_v_size >> 2; /* mild exponential growth */
1131 total_v_size += increment;
1132 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001133 PyErr_SetString(PyExc_OverflowError,
1134 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001135 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001136 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001137 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001138 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001139 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001140 buf = BUF(v) + used_v_size;
1141 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001142 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001143
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001144 used_v_size = buf - BUF(v);
1145 if (used_v_size != total_v_size)
1146 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001147 return v;
1148}
1149
Guido van Rossum0bd24411991-04-04 15:21:57 +00001150/* External C interface */
1151
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001152PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001153PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001154{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001155 PyObject *result;
1156
Guido van Rossum3165fe61992-09-25 21:59:05 +00001157 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001158 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001159 return NULL;
1160 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001161
1162 if (PyFile_Check(f)) {
1163 if (((PyFileObject*)f)->f_fp == NULL)
1164 return err_closed();
1165 result = get_line((PyFileObject *)f, n);
1166 }
1167 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001168 PyObject *reader;
1169 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001171 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001172 if (reader == NULL)
1173 return NULL;
1174 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001175 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001176 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001177 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001178 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001179 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001180 return NULL;
1181 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001182 result = PyEval_CallObject(reader, args);
1183 Py_DECREF(reader);
1184 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001185 if (result != NULL && !PyString_Check(result) &&
1186 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001187 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001188 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001189 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001190 "object.readline() returned non-string");
1191 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001192 }
1193
1194 if (n < 0 && result != NULL && PyString_Check(result)) {
1195 char *s = PyString_AS_STRING(result);
1196 int len = PyString_GET_SIZE(result);
1197 if (len == 0) {
1198 Py_DECREF(result);
1199 result = NULL;
1200 PyErr_SetString(PyExc_EOFError,
1201 "EOF when reading a line");
1202 }
1203 else if (s[len-1] == '\n') {
1204 if (result->ob_refcnt == 1)
1205 _PyString_Resize(&result, len-1);
1206 else {
1207 PyObject *v;
1208 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001209 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001210 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001211 }
1212 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001213 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001214#ifdef Py_USING_UNICODE
1215 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1216 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1217 int len = PyUnicode_GET_SIZE(result);
1218 if (len == 0) {
1219 Py_DECREF(result);
1220 result = NULL;
1221 PyErr_SetString(PyExc_EOFError,
1222 "EOF when reading a line");
1223 }
1224 else if (s[len-1] == '\n') {
1225 if (result->ob_refcnt == 1)
1226 PyUnicode_Resize(&result, len-1);
1227 else {
1228 PyObject *v;
1229 v = PyUnicode_FromUnicode(s, len-1);
1230 Py_DECREF(result);
1231 result = v;
1232 }
1233 }
1234 }
1235#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001236 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001237}
1238
1239/* Python method */
1240
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001241static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001242file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001243{
Guido van Rossum789a1611997-05-10 22:33:55 +00001244 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001245
Guido van Rossumd7297e61992-07-06 14:19:26 +00001246 if (f->f_fp == NULL)
1247 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001248 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001249 return NULL;
1250 if (n == 0)
1251 return PyString_FromString("");
1252 if (n < 0)
1253 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001254 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001255}
1256
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001257static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001258file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001259{
Guido van Rossum789a1611997-05-10 22:33:55 +00001260 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001261 PyObject *list;
1262 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001263 char small_buffer[SMALLCHUNK];
1264 char *buffer = small_buffer;
1265 size_t buffersize = SMALLCHUNK;
1266 PyObject *big_buffer = NULL;
1267 size_t nfilled = 0;
1268 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001269 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001270 char *p, *q, *end;
1271 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001272 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001273
Guido van Rossumd7297e61992-07-06 14:19:26 +00001274 if (f->f_fp == NULL)
1275 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001276 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001277 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001278 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001279 return NULL;
1280 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001281 if (shortread)
1282 nread = 0;
1283 else {
1284 Py_BEGIN_ALLOW_THREADS
1285 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001286 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001287 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001288 Py_END_ALLOW_THREADS
1289 shortread = (nread < buffersize-nfilled);
1290 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001291 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001292 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001293 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001294 break;
1295 PyErr_SetFromErrno(PyExc_IOError);
1296 clearerr(f->f_fp);
1297 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001298 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001299 list = NULL;
1300 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001301 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001302 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001303 p = memchr(buffer+nfilled, '\n', nread);
1304 if (p == NULL) {
1305 /* Need a larger buffer to fit this line */
1306 nfilled += nread;
1307 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001308 if (buffersize > INT_MAX) {
1309 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001310 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001311 goto error;
1312 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001313 if (big_buffer == NULL) {
1314 /* Create the big buffer */
1315 big_buffer = PyString_FromStringAndSize(
1316 NULL, buffersize);
1317 if (big_buffer == NULL)
1318 goto error;
1319 buffer = PyString_AS_STRING(big_buffer);
1320 memcpy(buffer, small_buffer, nfilled);
1321 }
1322 else {
1323 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001324 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1325 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001326 buffer = PyString_AS_STRING(big_buffer);
1327 }
1328 continue;
1329 }
1330 end = buffer+nfilled+nread;
1331 q = buffer;
1332 do {
1333 /* Process complete lines */
1334 p++;
1335 line = PyString_FromStringAndSize(q, p-q);
1336 if (line == NULL)
1337 goto error;
1338 err = PyList_Append(list, line);
1339 Py_DECREF(line);
1340 if (err != 0)
1341 goto error;
1342 q = p;
1343 p = memchr(q, '\n', end-q);
1344 } while (p != NULL);
1345 /* Move the remaining incomplete line to the start */
1346 nfilled = end-q;
1347 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001348 if (sizehint > 0)
1349 if (totalread >= (size_t)sizehint)
1350 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001351 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001352 if (nfilled != 0) {
1353 /* Partial last line */
1354 line = PyString_FromStringAndSize(buffer, nfilled);
1355 if (line == NULL)
1356 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001357 if (sizehint > 0) {
1358 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001359 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001360 if (rest == NULL) {
1361 Py_DECREF(line);
1362 goto error;
1363 }
1364 PyString_Concat(&line, rest);
1365 Py_DECREF(rest);
1366 if (line == NULL)
1367 goto error;
1368 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001369 err = PyList_Append(list, line);
1370 Py_DECREF(line);
1371 if (err != 0)
1372 goto error;
1373 }
1374 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001375 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001376 return list;
1377}
1378
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001379static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001380file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001381{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001382 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001383 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001384 if (f->f_fp == NULL)
1385 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001386 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001387 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001388 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001389 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001390 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001391 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001392 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001393 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001394 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001395 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001396 return NULL;
1397 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001398 Py_INCREF(Py_None);
1399 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001400}
1401
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001402static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001403file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001404{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001405#define CHUNKSIZE 1000
1406 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001407 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001408 PyObject *result;
1409 int i, j, index, len, nwritten, islist;
1410
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001411 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001412 if (f->f_fp == NULL)
1413 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001414
1415 result = NULL;
1416 list = NULL;
1417 islist = PyList_Check(seq);
1418 if (islist)
1419 it = NULL;
1420 else {
1421 it = PyObject_GetIter(seq);
1422 if (it == NULL) {
1423 PyErr_SetString(PyExc_TypeError,
1424 "writelines() requires an iterable argument");
1425 return NULL;
1426 }
1427 /* From here on, fail by going to error, to reclaim "it". */
1428 list = PyList_New(CHUNKSIZE);
1429 if (list == NULL)
1430 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001431 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001432
1433 /* Strategy: slurp CHUNKSIZE lines into a private list,
1434 checking that they are all strings, then write that list
1435 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001436 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001437 if (islist) {
1438 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001439 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001440 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001441 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001442 j = PyList_GET_SIZE(list);
1443 }
1444 else {
1445 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001446 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001447 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001448 if (PyErr_Occurred())
1449 goto error;
1450 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001451 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001452 PyList_SetItem(list, j, line);
1453 }
1454 }
1455 if (j == 0)
1456 break;
1457
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001458 /* Check that all entries are indeed strings. If not,
1459 apply the same rules as for file.write() and
1460 convert the results to strings. This is slow, but
1461 seems to be the only way since all conversion APIs
1462 could potentially execute Python code. */
1463 for (i = 0; i < j; i++) {
1464 PyObject *v = PyList_GET_ITEM(list, i);
1465 if (!PyString_Check(v)) {
1466 const char *buffer;
1467 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001468 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001469 PyObject_AsReadBuffer(v,
1470 (const void**)&buffer,
1471 &len)) ||
1472 PyObject_AsCharBuffer(v,
1473 &buffer,
1474 &len))) {
1475 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001476 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001477 goto error;
1478 }
1479 line = PyString_FromStringAndSize(buffer,
1480 len);
1481 if (line == NULL)
1482 goto error;
1483 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001484 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001485 }
1486 }
1487
1488 /* Since we are releasing the global lock, the
1489 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001490 Py_BEGIN_ALLOW_THREADS
1491 f->f_softspace = 0;
1492 errno = 0;
1493 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001494 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001495 len = PyString_GET_SIZE(line);
1496 nwritten = fwrite(PyString_AS_STRING(line),
1497 1, len, f->f_fp);
1498 if (nwritten != len) {
1499 Py_BLOCK_THREADS
1500 PyErr_SetFromErrno(PyExc_IOError);
1501 clearerr(f->f_fp);
1502 goto error;
1503 }
1504 }
1505 Py_END_ALLOW_THREADS
1506
1507 if (j < CHUNKSIZE)
1508 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001509 }
1510
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001511 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001512 result = Py_None;
1513 error:
1514 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001515 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001516 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001517#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001518}
1519
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001520static PyObject *
1521file_getiter(PyFileObject *f)
1522{
1523 if (f->f_fp == NULL)
1524 return err_closed();
1525 Py_INCREF(f);
1526 return (PyObject *)f;
1527}
1528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001529PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001530"readline([size]) -> next line from the file, as a string.\n"
1531"\n"
1532"Retain newline. A non-negative size argument limits the maximum\n"
1533"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001534"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001536PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001537"read([size]) -> read at most size bytes, returned as a string.\n"
1538"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001539"If the size argument is negative or omitted, read until EOF is reached.\n"
1540"Notice that when in non-blocking mode, less data than what was requested\n"
1541"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001543PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001544"write(str) -> None. Write string str to file.\n"
1545"\n"
1546"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001547"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001550"fileno() -> integer \"file descriptor\".\n"
1551"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001552"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001554PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001555"seek(offset[, whence]) -> None. Move to new file position.\n"
1556"\n"
1557"Argument offset is a byte count. Optional argument whence defaults to\n"
1558"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1559"(move relative to current position, positive or negative), and 2 (move\n"
1560"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001561"seeking beyond the end of a file). If the file is opened in text mode,\n"
1562"only offsets returned by tell() are legal. Use of other offsets causes\n"
1563"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001564"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001565"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001566
Guido van Rossumd7047b31995-01-02 19:07:15 +00001567#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001568PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001569"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1570"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001571"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001572#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001573
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001574PyDoc_STRVAR(tell_doc,
1575"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001577PyDoc_STRVAR(readinto_doc,
1578"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001580PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001581"readlines([size]) -> list of strings, each a line from the file.\n"
1582"\n"
1583"Call readline() repeatedly and return a list of the lines so read.\n"
1584"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001585"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001587PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001588"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001589"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001590"For backward compatibility. File objects now include the performance\n"
1591"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001593PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001594"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001595"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001596"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001597"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001598
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001599PyDoc_STRVAR(flush_doc,
1600"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001602PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001603"close() -> None or (perhaps) an integer. Close the file.\n"
1604"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001605"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001606"further I/O operations. close() may be called more than once without\n"
1607"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001608"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001610PyDoc_STRVAR(isatty_doc,
1611"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001612
1613static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001614 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1615 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1616 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1617 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1618 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001619#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001620 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001621#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001622 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1623 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1624 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1625 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1626 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1627 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1628 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1629 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1630 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001631};
1632
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001633#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001634
Guido van Rossum6f799372001-09-20 20:46:19 +00001635static PyMemberDef file_memberlist[] = {
1636 {"softspace", T_INT, OFF(f_softspace), 0,
1637 "flag indicating that a space needs to be printed; used by print"},
1638 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001639 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001640 {"name", T_OBJECT, OFF(f_name), RO,
1641 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001642 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1643 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001644 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001645 {NULL} /* Sentinel */
1646};
1647
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001648static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001650{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001651 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001652}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001653static PyObject *
1654get_newlines(PyFileObject *f, void *closure)
1655{
1656 switch (f->f_newlinetypes) {
1657 case NEWLINE_UNKNOWN:
1658 Py_INCREF(Py_None);
1659 return Py_None;
1660 case NEWLINE_CR:
1661 return PyString_FromString("\r");
1662 case NEWLINE_LF:
1663 return PyString_FromString("\n");
1664 case NEWLINE_CR|NEWLINE_LF:
1665 return Py_BuildValue("(ss)", "\r", "\n");
1666 case NEWLINE_CRLF:
1667 return PyString_FromString("\r\n");
1668 case NEWLINE_CR|NEWLINE_CRLF:
1669 return Py_BuildValue("(ss)", "\r", "\r\n");
1670 case NEWLINE_LF|NEWLINE_CRLF:
1671 return Py_BuildValue("(ss)", "\n", "\r\n");
1672 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1673 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1674 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001675 PyErr_Format(PyExc_SystemError,
1676 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001677 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001678 return NULL;
1679 }
1680}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001681
Guido van Rossum32d34c82001-09-20 21:45:26 +00001682static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001683 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001684 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001685 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 {0},
1687};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001688
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001689static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001690drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001691{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001692 if (f->f_buf != NULL) {
1693 PyMem_Free(f->f_buf);
1694 f->f_buf = NULL;
1695 }
Guido van Rossum65967252001-04-21 13:20:18 +00001696}
1697
Tim Petersf1827cf2003-09-07 03:30:18 +00001698/* Make sure that file has a readahead buffer with at least one byte
1699 (unless at EOF) and no more than bufsize. Returns negative value on
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001700 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001701static int
1702readahead(PyFileObject *f, int bufsize)
1703{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001704 int chunksize;
1705
1706 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001707 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001708 return 0;
1709 else
1710 drop_readahead(f);
1711 }
1712 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1713 return -1;
1714 }
1715 Py_BEGIN_ALLOW_THREADS
1716 errno = 0;
1717 chunksize = Py_UniversalNewlineFread(
1718 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1719 Py_END_ALLOW_THREADS
1720 if (chunksize == 0) {
1721 if (ferror(f->f_fp)) {
1722 PyErr_SetFromErrno(PyExc_IOError);
1723 clearerr(f->f_fp);
1724 drop_readahead(f);
1725 return -1;
1726 }
1727 }
1728 f->f_bufptr = f->f_buf;
1729 f->f_bufend = f->f_buf + chunksize;
1730 return 0;
1731}
1732
1733/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001734 uninitialized bytes followed by the remainder of the line. Don't be
1735 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001736 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1737
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001738static PyStringObject *
1739readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1740{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001741 PyStringObject* s;
1742 char *bufptr;
1743 char *buf;
1744 int len;
1745
1746 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001747 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001748 return NULL;
1749
1750 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001751 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001752 return (PyStringObject *)
1753 PyString_FromStringAndSize(NULL, skip);
1754 bufptr = memchr(f->f_bufptr, '\n', len);
1755 if (bufptr != NULL) {
1756 bufptr++; /* Count the '\n' */
1757 len = bufptr - f->f_bufptr;
1758 s = (PyStringObject *)
1759 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001760 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001761 return NULL;
1762 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1763 f->f_bufptr = bufptr;
1764 if (bufptr == f->f_bufend)
1765 drop_readahead(f);
1766 } else {
1767 bufptr = f->f_bufptr;
1768 buf = f->f_buf;
1769 f->f_buf = NULL; /* Force new readahead buffer */
1770 s = readahead_get_line_skip(
1771 f, skip+len, bufsize + (bufsize>>2) );
1772 if (s == NULL) {
1773 PyMem_Free(buf);
1774 return NULL;
1775 }
1776 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1777 PyMem_Free(buf);
1778 }
1779 return s;
1780}
1781
1782/* A larger buffer size may actually decrease performance. */
1783#define READAHEAD_BUFSIZE 8192
1784
1785static PyObject *
1786file_iternext(PyFileObject *f)
1787{
1788 PyStringObject* l;
1789
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001790 if (f->f_fp == NULL)
1791 return err_closed();
1792
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001793 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1794 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1795 Py_XDECREF(l);
1796 return NULL;
1797 }
1798 return (PyObject *)l;
1799}
1800
1801
Tim Peters59c9a642001-09-13 05:38:56 +00001802static PyObject *
1803file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1804{
Tim Peters44410012001-09-14 03:26:08 +00001805 PyObject *self;
1806 static PyObject *not_yet_string;
1807
1808 assert(type != NULL && type->tp_alloc != NULL);
1809
1810 if (not_yet_string == NULL) {
1811 not_yet_string = PyString_FromString("<uninitialized file>");
1812 if (not_yet_string == NULL)
1813 return NULL;
1814 }
1815
1816 self = type->tp_alloc(type, 0);
1817 if (self != NULL) {
1818 /* Always fill in the name and mode, so that nobody else
1819 needs to special-case NULLs there. */
1820 Py_INCREF(not_yet_string);
1821 ((PyFileObject *)self)->f_name = not_yet_string;
1822 Py_INCREF(not_yet_string);
1823 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001824 Py_INCREF(Py_None);
1825 ((PyFileObject *)self)->f_encoding = Py_None;
Tim Peters44410012001-09-14 03:26:08 +00001826 }
1827 return self;
1828}
1829
1830static int
1831file_init(PyObject *self, PyObject *args, PyObject *kwds)
1832{
1833 PyFileObject *foself = (PyFileObject *)self;
1834 int ret = 0;
Tim Peters59c9a642001-09-13 05:38:56 +00001835 static char *kwlist[] = {"name", "mode", "buffering", 0};
1836 char *name = NULL;
1837 char *mode = "r";
1838 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001839 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001840
1841 assert(PyFile_Check(self));
1842 if (foself->f_fp != NULL) {
1843 /* Have to close the existing file first. */
1844 PyObject *closeresult = file_close(foself);
1845 if (closeresult == NULL)
1846 return -1;
1847 Py_DECREF(closeresult);
1848 }
Tim Peters59c9a642001-09-13 05:38:56 +00001849
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001850#ifdef Py_WIN_WIDE_FILENAMES
1851 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1852 PyObject *po;
1853 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1854 kwlist, &po, &mode, &bufsize)) {
1855 wideargument = 1;
1856 if (fill_file_fields(foself, NULL, name, mode,
1857 fclose, po) == NULL)
1858 goto Error;
1859 } else {
1860 /* Drop the argument parsing error as narrow
1861 strings are also valid. */
1862 PyErr_Clear();
1863 }
1864 }
1865#endif
1866
1867 if (!wideargument) {
1868 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1869 Py_FileSystemDefaultEncoding,
1870 &name,
1871 &mode, &bufsize))
1872 return -1;
1873 if (fill_file_fields(foself, NULL, name, mode,
1874 fclose, NULL) == NULL)
1875 goto Error;
1876 }
Tim Peters44410012001-09-14 03:26:08 +00001877 if (open_the_file(foself, name, mode) == NULL)
1878 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001879 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001880 PyFile_SetBufSize(self, bufsize);
1881 goto Done;
1882
1883Error:
1884 ret = -1;
1885 /* fall through */
1886Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001887 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001888 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001889}
1890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891PyDoc_VAR(file_doc) =
1892PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001893"file(name[, mode[, buffering]]) -> file object\n"
1894"\n"
1895"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1896"writing or appending. The file will be created if it doesn't exist\n"
1897"when opened for writing or appending; it will be truncated when\n"
1898"opened for writing. Add a 'b' to the mode for binary files.\n"
1899"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1900"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001901"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001902)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001903PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001904"Add a 'U' to mode to open the file for input with universal newline\n"
1905"support. Any line ending in the input file will be seen as a '\\n'\n"
1906"in Python. Also, a file so opened gains the attribute 'newlines';\n"
1907"the value for this attribute is one of None (no newline read yet),\n"
1908"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
1909"\n"
1910"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001911)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001912PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001913"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001914"Note: open() is an alias for file()."
1915);
Tim Peters59c9a642001-09-13 05:38:56 +00001916
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001917PyTypeObject PyFile_Type = {
1918 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001919 0,
1920 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001921 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001922 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001923 (destructor)file_dealloc, /* tp_dealloc */
1924 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925 0, /* tp_getattr */
1926 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001927 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001929 0, /* tp_as_number */
1930 0, /* tp_as_sequence */
1931 0, /* tp_as_mapping */
1932 0, /* tp_hash */
1933 0, /* tp_call */
1934 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00001936 /* softspace is writable: we must supply tp_setattro */
1937 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00001938 0, /* tp_as_buffer */
Guido van Rossum9475a232001-10-05 20:51:39 +00001939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00001940 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 0, /* tp_traverse */
1942 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00001943 0, /* tp_richcompare */
1944 0, /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001945 (getiterfunc)file_getiter, /* tp_iter */
1946 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947 file_methods, /* tp_methods */
1948 file_memberlist, /* tp_members */
1949 file_getsetlist, /* tp_getset */
1950 0, /* tp_base */
1951 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00001952 0, /* tp_descr_get */
1953 0, /* tp_descr_set */
1954 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00001955 (initproc)file_init, /* tp_init */
1956 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00001957 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00001958 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001959};
Guido van Rossumeb183da1991-04-04 10:44:06 +00001960
1961/* Interface for the 'soft space' between print items. */
1962
1963int
Fred Drakefd99de62000-07-09 05:02:18 +00001964PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00001965{
1966 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001967 if (f == NULL) {
1968 /* Do nothing */
1969 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001970 else if (PyFile_Check(f)) {
1971 oldflag = ((PyFileObject *)f)->f_softspace;
1972 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001973 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001974 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001975 PyObject *v;
1976 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001977 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001978 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00001979 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001980 if (PyInt_Check(v))
1981 oldflag = PyInt_AsLong(v);
1982 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001983 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001984 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001985 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001986 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00001987 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001988 if (PyObject_SetAttrString(f, "softspace", v) != 0)
1989 PyErr_Clear();
1990 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001991 }
1992 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00001993 return oldflag;
1994}
Guido van Rossum3165fe61992-09-25 21:59:05 +00001995
1996/* Interfaces to write objects/strings to file-like objects */
1997
1998int
Fred Drakefd99de62000-07-09 05:02:18 +00001999PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002000{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002001 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002002 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002004 return -1;
2005 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002006 else if (PyFile_Check(f)) {
2007 FILE *fp = PyFile_AsFile(f);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002008 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2009 int result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002010 if (fp == NULL) {
2011 err_closed();
2012 return -1;
2013 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002014#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002015 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002016 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002017 char *cenc = PyString_AS_STRING(enc);
2018 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2019 if (value == NULL)
2020 return -1;
2021 } else {
2022 value = v;
2023 Py_INCREF(value);
2024 }
2025 result = PyObject_Print(value, fp, flags);
2026 Py_DECREF(value);
2027 return result;
2028#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002029 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002030#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002031 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002032 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002033 if (writer == NULL)
2034 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002035 if (flags & Py_PRINT_RAW) {
2036 if (PyUnicode_Check(v)) {
2037 value = v;
2038 Py_INCREF(value);
2039 } else
2040 value = PyObject_Str(v);
2041 }
2042 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002044 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002045 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002046 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002047 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002048 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002049 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002050 Py_DECREF(value);
2051 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002052 return -1;
2053 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054 result = PyEval_CallObject(writer, args);
2055 Py_DECREF(args);
2056 Py_DECREF(value);
2057 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002058 if (result == NULL)
2059 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002060 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002061 return 0;
2062}
2063
Guido van Rossum27a60b11997-05-22 22:25:11 +00002064int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002065PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002066{
2067 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002068 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002069 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002070 PyErr_SetString(PyExc_SystemError,
2071 "null file for PyFile_WriteString");
2072 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002073 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074 else if (PyFile_Check(f)) {
2075 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002076 if (fp == NULL) {
2077 err_closed();
2078 return -1;
2079 }
2080 fputs(s, fp);
2081 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002082 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002083 else if (!PyErr_Occurred()) {
2084 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002085 int err;
2086 if (v == NULL)
2087 return -1;
2088 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2089 Py_DECREF(v);
2090 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002091 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002092 else
2093 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002094}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002095
2096/* Try to get a file-descriptor from a Python object. If the object
2097 is an integer or long integer, its value is returned. If not, the
2098 object's fileno() method is called if it exists; the method must return
2099 an integer or long integer, which is returned as the file descriptor value.
2100 -1 is returned on failure.
2101*/
2102
2103int PyObject_AsFileDescriptor(PyObject *o)
2104{
2105 int fd;
2106 PyObject *meth;
2107
2108 if (PyInt_Check(o)) {
2109 fd = PyInt_AsLong(o);
2110 }
2111 else if (PyLong_Check(o)) {
2112 fd = PyLong_AsLong(o);
2113 }
2114 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2115 {
2116 PyObject *fno = PyEval_CallObject(meth, NULL);
2117 Py_DECREF(meth);
2118 if (fno == NULL)
2119 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002120
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002121 if (PyInt_Check(fno)) {
2122 fd = PyInt_AsLong(fno);
2123 Py_DECREF(fno);
2124 }
2125 else if (PyLong_Check(fno)) {
2126 fd = PyLong_AsLong(fno);
2127 Py_DECREF(fno);
2128 }
2129 else {
2130 PyErr_SetString(PyExc_TypeError,
2131 "fileno() returned a non-integer");
2132 Py_DECREF(fno);
2133 return -1;
2134 }
2135 }
2136 else {
2137 PyErr_SetString(PyExc_TypeError,
2138 "argument must be an int, or have a fileno() method.");
2139 return -1;
2140 }
2141
2142 if (fd < 0) {
2143 PyErr_Format(PyExc_ValueError,
2144 "file descriptor cannot be a negative integer (%i)",
2145 fd);
2146 return -1;
2147 }
2148 return fd;
2149}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002150
Jack Jansen7b8c7542002-04-14 20:12:41 +00002151/* From here on we need access to the real fgets and fread */
2152#undef fgets
2153#undef fread
2154
2155/*
2156** Py_UniversalNewlineFgets is an fgets variation that understands
2157** all of \r, \n and \r\n conventions.
2158** The stream should be opened in binary mode.
2159** If fobj is NULL the routine always does newline conversion, and
2160** it may peek one char ahead to gobble the second char in \r\n.
2161** If fobj is non-NULL it must be a PyFileObject. In this case there
2162** is no readahead but in stead a flag is used to skip a following
2163** \n on the next read. Also, if the file is open in binary mode
2164** the whole conversion is skipped. Finally, the routine keeps track of
2165** the different types of newlines seen.
2166** Note that we need no error handling: fgets() treats error and eof
2167** identically.
2168*/
2169char *
2170Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2171{
2172 char *p = buf;
2173 int c;
2174 int newlinetypes = 0;
2175 int skipnextlf = 0;
2176 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002177
Jack Jansen7b8c7542002-04-14 20:12:41 +00002178 if (fobj) {
2179 if (!PyFile_Check(fobj)) {
2180 errno = ENXIO; /* What can you do... */
2181 return NULL;
2182 }
2183 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2184 if ( !univ_newline )
2185 return fgets(buf, n, stream);
2186 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2187 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2188 }
2189 FLOCKFILE(stream);
2190 c = 'x'; /* Shut up gcc warning */
2191 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2192 if (skipnextlf ) {
2193 skipnextlf = 0;
2194 if (c == '\n') {
2195 /* Seeing a \n here with skipnextlf true
2196 ** means we saw a \r before.
2197 */
2198 newlinetypes |= NEWLINE_CRLF;
2199 c = GETC(stream);
2200 if (c == EOF) break;
2201 } else {
2202 /*
2203 ** Note that c == EOF also brings us here,
2204 ** so we're okay if the last char in the file
2205 ** is a CR.
2206 */
2207 newlinetypes |= NEWLINE_CR;
2208 }
2209 }
2210 if (c == '\r') {
2211 /* A \r is translated into a \n, and we skip
2212 ** an adjacent \n, if any. We don't set the
2213 ** newlinetypes flag until we've seen the next char.
2214 */
2215 skipnextlf = 1;
2216 c = '\n';
2217 } else if ( c == '\n') {
2218 newlinetypes |= NEWLINE_LF;
2219 }
2220 *p++ = c;
2221 if (c == '\n') break;
2222 }
2223 if ( c == EOF && skipnextlf )
2224 newlinetypes |= NEWLINE_CR;
2225 FUNLOCKFILE(stream);
2226 *p = '\0';
2227 if (fobj) {
2228 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2229 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2230 } else if ( skipnextlf ) {
2231 /* If we have no file object we cannot save the
2232 ** skipnextlf flag. We have to readahead, which
2233 ** will cause a pause if we're reading from an
2234 ** interactive stream, but that is very unlikely
2235 ** unless we're doing something silly like
2236 ** execfile("/dev/tty").
2237 */
2238 c = GETC(stream);
2239 if ( c != '\n' )
2240 ungetc(c, stream);
2241 }
2242 if (p == buf)
2243 return NULL;
2244 return buf;
2245}
2246
2247/*
2248** Py_UniversalNewlineFread is an fread variation that understands
2249** all of \r, \n and \r\n conventions.
2250** The stream should be opened in binary mode.
2251** fobj must be a PyFileObject. In this case there
2252** is no readahead but in stead a flag is used to skip a following
2253** \n on the next read. Also, if the file is open in binary mode
2254** the whole conversion is skipped. Finally, the routine keeps track of
2255** the different types of newlines seen.
2256*/
2257size_t
Tim Peters058b1412002-04-21 07:29:14 +00002258Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002259 FILE *stream, PyObject *fobj)
2260{
Tim Peters058b1412002-04-21 07:29:14 +00002261 char *dst = buf;
2262 PyFileObject *f = (PyFileObject *)fobj;
2263 int newlinetypes, skipnextlf;
2264
2265 assert(buf != NULL);
2266 assert(stream != NULL);
2267
Jack Jansen7b8c7542002-04-14 20:12:41 +00002268 if (!fobj || !PyFile_Check(fobj)) {
2269 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002270 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002271 }
Tim Peters058b1412002-04-21 07:29:14 +00002272 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002273 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002274 newlinetypes = f->f_newlinetypes;
2275 skipnextlf = f->f_skipnextlf;
2276 /* Invariant: n is the number of bytes remaining to be filled
2277 * in the buffer.
2278 */
2279 while (n) {
2280 size_t nread;
2281 int shortread;
2282 char *src = dst;
2283
2284 nread = fread(dst, 1, n, stream);
2285 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002286 if (nread == 0)
2287 break;
2288
Tim Peterse1682a82002-04-21 18:15:20 +00002289 n -= nread; /* assuming 1 byte out for each in; will adjust */
2290 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002291 while (nread--) {
2292 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002293 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002294 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002295 *dst++ = '\n';
2296 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002297 }
2298 else if (skipnextlf && c == '\n') {
2299 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002300 skipnextlf = 0;
2301 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002302 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002303 }
2304 else {
2305 /* Normal char to be stored in buffer. Also
2306 * update the newlinetypes flag if either this
2307 * is an LF or the previous char was a CR.
2308 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002309 if (c == '\n')
2310 newlinetypes |= NEWLINE_LF;
2311 else if (skipnextlf)
2312 newlinetypes |= NEWLINE_CR;
2313 *dst++ = c;
2314 skipnextlf = 0;
2315 }
2316 }
Tim Peters058b1412002-04-21 07:29:14 +00002317 if (shortread) {
2318 /* If this is EOF, update type flags. */
2319 if (skipnextlf && feof(stream))
2320 newlinetypes |= NEWLINE_CR;
2321 break;
2322 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002323 }
Tim Peters058b1412002-04-21 07:29:14 +00002324 f->f_newlinetypes = newlinetypes;
2325 f->f_skipnextlf = skipnextlf;
2326 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002327}