blob: 66e5f2865f6d314eae8d904e56e4125add2fe989 [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
44#ifdef WITH_UNIVERSAL_NEWLINES
45/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
50#endif
Trent Mickf29f47b2000-08-11 19:02:59 +000051
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000053PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000056 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000057 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059}
60
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000062PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000063{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000065 return NULL;
66 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000068}
69
Neil Schemenauered19b882002-03-23 02:06:50 +000070/* On Unix, fopen will succeed for directories.
71 In Python, there should be no file objects referring to
72 directories, so we need a check. */
73
74static PyFileObject*
75dircheck(PyFileObject* f)
76{
77#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
78 struct stat buf;
79 if (f->f_fp == NULL)
80 return f;
81 if (fstat(fileno(f->f_fp), &buf) == 0 &&
82 S_ISDIR(buf.st_mode)) {
83#ifdef HAVE_STRERROR
84 char *msg = strerror(EISDIR);
85#else
86 char *msg = "Is a directory";
87#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000088 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000089 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000090 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000091 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000092 return NULL;
93 }
94#endif
95 return f;
96}
97
Tim Peters59c9a642001-09-13 05:38:56 +000098
99static PyObject *
100fill_file_fields(PyFileObject *f, FILE *fp, char *name, char *mode,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000101 int (*close)(FILE *), PyObject *wname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102{
Tim Peters59c9a642001-09-13 05:38:56 +0000103 assert(f != NULL);
104 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000105 assert(f->f_fp == NULL);
106
107 Py_DECREF(f->f_name);
108 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000109 Py_DECREF(f->f_encoding);
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000110#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000111 if (wname)
112 f->f_name = PyUnicode_FromObject(wname);
113 else
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000114#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000115 f->f_name = PyString_FromString(name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000117
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000118 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000119 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000120 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000121 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000122#ifdef WITH_UNIVERSAL_NEWLINES
123 f->f_univ_newline = (strchr(mode, 'U') != NULL);
124 f->f_newlinetypes = NEWLINE_UNKNOWN;
125 f->f_skipnextlf = 0;
126#endif
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000127 Py_INCREF(Py_None);
128 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000129
Tim Peters59c9a642001-09-13 05:38:56 +0000130 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000133 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135}
136
Tim Peters59c9a642001-09-13 05:38:56 +0000137static PyObject *
138open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139{
Tim Peters59c9a642001-09-13 05:38:56 +0000140 assert(f != NULL);
141 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000142#ifdef MS_WINDOWS
143 /* windows ignores the passed name in order to support Unicode */
144 assert(f->f_name != NULL);
145#else
Tim Peters59c9a642001-09-13 05:38:56 +0000146 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000147#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000148 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000149 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000150
Tim Peters8fa45672001-09-13 21:01:29 +0000151 /* rexec.py can't stop a user from getting the file() constructor --
152 all they have to do is get *any* file object f, and then do
153 type(f). Here we prevent them from doing damage with it. */
154 if (PyEval_GetRestricted()) {
155 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000156 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000157 return NULL;
158 }
Tim Petersa27a1502001-11-09 20:59:14 +0000159 errno = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000160#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000161 if (*mode == '*') {
162 FILE *fopenRF();
163 f->f_fp = fopenRF(name, mode+1);
164 }
165 else
166#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000167 {
Jack Jansen7b8c7542002-04-14 20:12:41 +0000168#ifdef WITH_UNIVERSAL_NEWLINES
169 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
170 mode = "rb";
171#else
172 /* Compatibility: specifying U in a Python without universal
173 ** newlines is allowed, and the file is opened as a normal text
174 ** file.
175 */
176 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
177 mode = "r";
178#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000179#ifdef MS_WINDOWS
180 if (PyUnicode_Check(f->f_name)) {
Tim Petersf1827cf2003-09-07 03:30:18 +0000181 PyObject *wmode;
182 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000183 if (f->f_name && wmode) {
184 Py_BEGIN_ALLOW_THREADS
185 /* PyUnicode_AS_UNICODE OK without thread
186 lock as it is a simple dereference. */
187 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
188 PyUnicode_AS_UNICODE(wmode));
189 Py_END_ALLOW_THREADS
190 }
191 Py_XDECREF(wmode);
192 }
193#endif
194 if (NULL == f->f_fp && NULL != name) {
195 Py_BEGIN_ALLOW_THREADS
196 f->f_fp = fopen(name, mode);
197 Py_END_ALLOW_THREADS
198 }
Guido van Rossumff4949e1992-08-05 19:58:53 +0000199 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000200 if (f->f_fp == NULL) {
Tim Peters2ea91112002-04-08 04:13:12 +0000201#ifdef _MSC_VER
202 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
203 * across all Windows flavors. When it sets EINVAL varies
204 * across Windows flavors, the exact conditions aren't
205 * documented, and the answer lies in the OS's implementation
206 * of Win32's CreateFile function (whose source is secret).
207 * Seems the best we can do is map EINVAL to ENOENT.
208 */
209 if (errno == 0) /* bad mode string */
210 errno = EINVAL;
211 else if (errno == EINVAL) /* unknown, but not a mode string */
212 errno = ENOENT;
213#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000214 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000215 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000216 mode);
217 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000218#ifdef MS_WINDOWS
219 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
220#else
Jeremy Hylton41c83212001-11-09 16:17:24 +0000221 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000222#endif /* MS_WINDOWS */
Tim Peters59c9a642001-09-13 05:38:56 +0000223 f = NULL;
224 }
Tim Peters2ea91112002-04-08 04:13:12 +0000225 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000226 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000227 return (PyObject *)f;
228}
229
230PyObject *
231PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
232{
Tim Peters44410012001-09-14 03:26:08 +0000233 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
234 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000235 if (f != NULL) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000236 if (fill_file_fields(f, fp, name, mode, close, NULL) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000237 Py_DECREF(f);
238 f = NULL;
239 }
240 }
241 return (PyObject *) f;
242}
243
244PyObject *
245PyFile_FromString(char *name, char *mode)
246{
247 extern int fclose(FILE *);
248 PyFileObject *f;
249
250 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
251 if (f != NULL) {
252 if (open_the_file(f, name, mode) == NULL) {
253 Py_DECREF(f);
254 f = NULL;
255 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000256 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000257 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258}
259
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260void
Fred Drakefd99de62000-07-09 05:02:18 +0000261PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000262{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000263 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000264 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000265 int type;
266 switch (bufsize) {
267 case 0:
268 type = _IONBF;
269 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000270#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000271 case 1:
272 type = _IOLBF;
273 bufsize = BUFSIZ;
274 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000275#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000276 default:
277 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000278#ifndef HAVE_SETVBUF
279 bufsize = BUFSIZ;
280#endif
281 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000282 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000283 fflush(file->f_fp);
284 if (type == _IONBF) {
285 PyMem_Free(file->f_setbuf);
286 file->f_setbuf = NULL;
287 } else {
288 file->f_setbuf = PyMem_Realloc(file->f_setbuf, bufsize);
289 }
290#ifdef HAVE_SETVBUF
291 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000292#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000293 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000294#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000295 }
296}
297
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000298/* Set the encoding used to output Unicode strings.
299 Returh 1 on success, 0 on failure. */
300
301int
302PyFile_SetEncoding(PyObject *f, const char *enc)
303{
304 PyFileObject *file = (PyFileObject*)f;
305 PyObject *str = PyString_FromString(enc);
306 if (!str)
307 return 0;
308 Py_DECREF(file->f_encoding);
309 file->f_encoding = str;
310 return 1;
311}
312
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000314err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000315{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000316 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000317 return NULL;
318}
319
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000320static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000321
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000322/* Methods */
323
324static void
Fred Drakefd99de62000-07-09 05:02:18 +0000325file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000327 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000329 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000331 }
Tim Peters44410012001-09-14 03:26:08 +0000332 Py_XDECREF(f->f_name);
333 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000334 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000335 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000336 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337}
338
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000340file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000342 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000343#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000344 PyObject *ret = NULL;
345 PyObject *name;
346 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
347 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
348 f->f_fp == NULL ? "closed" : "open",
349 PyString_AsString(name),
350 PyString_AsString(f->f_mode),
351 f);
352 Py_XDECREF(name);
353 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000354#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000355 } else {
356 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000357 f->f_fp == NULL ? "closed" : "open",
358 PyString_AsString(f->f_name),
359 PyString_AsString(f->f_mode),
360 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000361 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362}
363
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000365file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000367 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000369 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000371 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000372 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000374 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375 f->f_fp = NULL;
376 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000377 PyMem_Free(f->f_setbuf);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000378 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000379 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000380 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000381 return PyInt_FromLong((long)sts);
382 Py_INCREF(Py_None);
383 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384}
385
Trent Mickf29f47b2000-08-11 19:02:59 +0000386
Guido van Rossumb8552162001-09-05 14:58:11 +0000387/* Our very own off_t-like type, 64-bit if possible */
388#if !defined(HAVE_LARGEFILE_SUPPORT)
389typedef off_t Py_off_t;
390#elif SIZEOF_OFF_T >= 8
391typedef off_t Py_off_t;
392#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000393typedef fpos_t Py_off_t;
394#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000395#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000396#endif
397
398
Trent Mickf29f47b2000-08-11 19:02:59 +0000399/* a portable fseek() function
400 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000401static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000402_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000403{
Guido van Rossumb8552162001-09-05 14:58:11 +0000404#if !defined(HAVE_LARGEFILE_SUPPORT)
405 return fseek(fp, offset, whence);
406#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000407 return fseeko(fp, offset, whence);
408#elif defined(HAVE_FSEEK64)
409 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000410#elif defined(__BEOS__)
411 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000412#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000413 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
414 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000415 fpos_t pos;
416 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000417 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000418#ifdef MS_WINDOWS
419 fflush(fp);
420 if (_lseeki64(fileno(fp), 0, 2) == -1)
421 return -1;
422#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000423 if (fseek(fp, 0, SEEK_END) != 0)
424 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000425#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000426 /* fall through */
427 case SEEK_CUR:
428 if (fgetpos(fp, &pos) != 0)
429 return -1;
430 offset += pos;
431 break;
432 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000433 }
434 return fsetpos(fp, &offset);
435#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000436#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000437#endif
438}
439
440
441/* a portable ftell() function
442 Return -1 on failure with errno set appropriately, current file
443 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000444static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000445_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000446{
Guido van Rossumb8552162001-09-05 14:58:11 +0000447#if !defined(HAVE_LARGEFILE_SUPPORT)
448 return ftell(fp);
449#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
450 return ftello(fp);
451#elif defined(HAVE_FTELL64)
452 return ftell64(fp);
453#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000454 fpos_t pos;
455 if (fgetpos(fp, &pos) != 0)
456 return -1;
457 return pos;
458#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000459#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000460#endif
461}
462
463
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000465file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000466{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000467 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000468 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000469 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000470 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000471
Guido van Rossumd7297e61992-07-06 14:19:26 +0000472 if (f->f_fp == NULL)
473 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000474 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000475 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000476 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000477 return NULL;
478#if !defined(HAVE_LARGEFILE_SUPPORT)
479 offset = PyInt_AsLong(offobj);
480#else
481 offset = PyLong_Check(offobj) ?
482 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
483#endif
484 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000485 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000486
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000488 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000489 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000491
Guido van Rossumff4949e1992-08-05 19:58:53 +0000492 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000494 clearerr(f->f_fp);
495 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000496 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000497#ifdef WITH_UNIVERSAL_NEWLINES
498 f->f_skipnextlf = 0;
499#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500 Py_INCREF(Py_None);
501 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000502}
503
Trent Mickf29f47b2000-08-11 19:02:59 +0000504
Guido van Rossumd7047b31995-01-02 19:07:15 +0000505#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000507file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000508{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000509 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000510 PyObject *newsizeobj = NULL;
511 Py_off_t initialpos;
512 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000513
Guido van Rossumd7047b31995-01-02 19:07:15 +0000514 if (f->f_fp == NULL)
515 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000516 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000517 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000518
Tim Petersf1827cf2003-09-07 03:30:18 +0000519 /* Get current file position. If the file happens to be open for
520 * update and the last operation was an input operation, C doesn't
521 * define what the later fflush() will do, but we promise truncate()
522 * won't change the current position (and fflush() *does* change it
523 * then at least on Windows). The easiest thing is to capture
524 * current pos now and seek back to it at the end.
525 */
526 Py_BEGIN_ALLOW_THREADS
527 errno = 0;
528 initialpos = _portable_ftell(f->f_fp);
529 Py_END_ALLOW_THREADS
530 if (initialpos == -1)
531 goto onioerror;
532
Tim Petersfb05db22002-03-11 00:24:00 +0000533 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000534 * specified value.
535 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000536 if (newsizeobj != NULL) {
537#if !defined(HAVE_LARGEFILE_SUPPORT)
538 newsize = PyInt_AsLong(newsizeobj);
539#else
540 newsize = PyLong_Check(newsizeobj) ?
541 PyLong_AsLongLong(newsizeobj) :
542 PyInt_AsLong(newsizeobj);
543#endif
544 if (PyErr_Occurred())
545 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000546 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000547 else /* default to current position */
548 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000549
Tim Petersf1827cf2003-09-07 03:30:18 +0000550 /* Flush the stream. We're mixing stream-level I/O with lower-level
551 * I/O, and a flush may be necessary to synch both platform views
552 * of the current file state.
553 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000555 errno = 0;
556 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000557 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000558 if (ret != 0)
559 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000560
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000561#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000562 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000563 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000564 {
Tim Petersfb05db22002-03-11 00:24:00 +0000565 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000566
Tim Petersf1827cf2003-09-07 03:30:18 +0000567 /* Have to move current pos to desired endpoint on Windows. */
568 Py_BEGIN_ALLOW_THREADS
569 errno = 0;
570 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
571 Py_END_ALLOW_THREADS
572 if (ret)
573 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000574
Tim Peters8f01b682002-03-12 03:04:44 +0000575 /* Truncate. Note that this may grow the file! */
576 Py_BEGIN_ALLOW_THREADS
577 errno = 0;
578 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000579 ret = hFile == (HANDLE)-1;
580 if (ret == 0) {
581 ret = SetEndOfFile(hFile) == 0;
582 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000583 errno = EACCES;
584 }
585 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000586 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000587 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000588 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000589#else
590 Py_BEGIN_ALLOW_THREADS
591 errno = 0;
592 ret = ftruncate(fileno(f->f_fp), newsize);
593 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000594 if (ret != 0)
595 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000596#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000597
Tim Petersf1827cf2003-09-07 03:30:18 +0000598 /* Restore original file position. */
599 Py_BEGIN_ALLOW_THREADS
600 errno = 0;
601 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
602 Py_END_ALLOW_THREADS
603 if (ret)
604 goto onioerror;
605
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606 Py_INCREF(Py_None);
607 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000608
609onioerror:
610 PyErr_SetFromErrno(PyExc_IOError);
611 clearerr(f->f_fp);
612 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000613}
614#endif /* HAVE_FTRUNCATE */
615
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000617file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000618{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000619 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000620
Guido van Rossumd7297e61992-07-06 14:19:26 +0000621 if (f->f_fp == NULL)
622 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000624 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000625 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000627 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000628 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000629 clearerr(f->f_fp);
630 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000631 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000632#ifdef WITH_UNIVERSAL_NEWLINES
633 if (f->f_skipnextlf) {
634 int c;
635 c = GETC(f->f_fp);
636 if (c == '\n') {
637 pos++;
638 f->f_skipnextlf = 0;
639 } else if (c != EOF) ungetc(c, f->f_fp);
640 }
641#endif
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000642#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000643 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000644#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000645 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000646#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000647}
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000650file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000651{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000652 if (f->f_fp == NULL)
653 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000654 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000655}
656
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000658file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000659{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000660 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000661
Guido van Rossumd7297e61992-07-06 14:19:26 +0000662 if (f->f_fp == NULL)
663 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000664 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000665 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000666 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000668 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000670 clearerr(f->f_fp);
671 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000672 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673 Py_INCREF(Py_None);
674 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000675}
676
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000678file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000679{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000680 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000681 if (f->f_fp == NULL)
682 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000684 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000686 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000687}
688
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000689
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000690#if BUFSIZ < 8192
691#define SMALLCHUNK 8192
692#else
693#define SMALLCHUNK BUFSIZ
694#endif
695
Guido van Rossum3c259041999-01-14 19:00:14 +0000696#if SIZEOF_INT < 4
697#define BIGCHUNK (512 * 32)
698#else
699#define BIGCHUNK (512 * 1024)
700#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000701
702static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000703new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000704{
705#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000706 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000707 struct stat st;
708 if (fstat(fileno(f->f_fp), &st) == 0) {
709 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000710 /* The following is not a bug: we really need to call lseek()
711 *and* ftell(). The reason is that some stdio libraries
712 mistakenly flush their buffer when ftell() is called and
713 the lseek() call it makes fails, thereby throwing away
714 data that cannot be recovered in any way. To avoid this,
715 we first test lseek(), and only call ftell() if lseek()
716 works. We can't use the lseek() value either, because we
717 need to take the amount of buffered data into account.
718 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000719 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000720 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000721 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000722 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000723 if (pos < 0)
724 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000725 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000726 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000727 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000728 }
729#endif
730 if (currentsize > SMALLCHUNK) {
731 /* Keep doubling until we reach BIGCHUNK;
732 then keep adding BIGCHUNK. */
733 if (currentsize <= BIGCHUNK)
734 return currentsize + currentsize;
735 else
736 return currentsize + BIGCHUNK;
737 }
738 return currentsize + SMALLCHUNK;
739}
740
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000741#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
742#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
743#else
744#ifdef EWOULDBLOCK
745#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
746#else
747#ifdef EAGAIN
748#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
749#else
750#define BLOCKED_ERRNO(x) 0
751#endif
752#endif
753#endif
754
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000755static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000756file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000757{
Guido van Rossum789a1611997-05-10 22:33:55 +0000758 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000759 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000761
Guido van Rossumd7297e61992-07-06 14:19:26 +0000762 if (f->f_fp == NULL)
763 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000764 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000765 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000766 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000767 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000768 else
769 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000770 if (buffersize > INT_MAX) {
771 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000772 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000773 return NULL;
774 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000775 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000776 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000778 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000779 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000780 Py_BEGIN_ALLOW_THREADS
781 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000782 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000783 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000784 Py_END_ALLOW_THREADS
785 if (chunksize == 0) {
786 if (!ferror(f->f_fp))
787 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000788 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000789 /* When in non-blocking mode, data shouldn't
790 * be discarded if a blocking signal was
791 * received. That will also happen if
792 * chunksize != 0, but bytesread < buffersize. */
793 if (bytesread > 0 && BLOCKED_ERRNO(errno))
794 break;
795 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000796 Py_DECREF(v);
797 return NULL;
798 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000799 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000800 if (bytesread < buffersize) {
801 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000802 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000803 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000804 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000805 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000806 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000807 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000808 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000809 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000810 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000811 }
812 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000813 if (bytesread != buffersize)
814 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815 return v;
816}
817
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000818static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000819file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000820{
821 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000822 int ntodo;
823 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000824
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000825 if (f->f_fp == NULL)
826 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000827 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000828 return NULL;
829 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000830 while (ntodo > 0) {
831 Py_BEGIN_ALLOW_THREADS
832 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000833 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000834 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000835 Py_END_ALLOW_THREADS
836 if (nnow == 0) {
837 if (!ferror(f->f_fp))
838 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000839 PyErr_SetFromErrno(PyExc_IOError);
840 clearerr(f->f_fp);
841 return NULL;
842 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000843 ndone += nnow;
844 ntodo -= nnow;
845 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000846 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000847}
848
Tim Peters86821b22001-01-07 21:19:34 +0000849/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000850Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000851
852Under MSVC 6:
853
Tim Peters1c733232001-01-08 04:02:07 +0000854+ MS threadsafe getc is very slow (multiple layers of function calls before+
855 after each character, to lock+unlock the stream).
856+ The stream-locking functions are MS-internal -- can't access them from user
857 code.
858+ There's nothing Tim could find in the MS C or platform SDK libraries that
859 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000860+ MS fgets locks/unlocks only once per line; it's the only hook we have.
861
862So we use fgets for speed(!), despite that it's painful.
863
864MS realloc is also slow.
865
Tim Petersf29b64d2001-01-15 06:33:19 +0000866Reports from other platforms on this method vs getc_unlocked (which MS doesn't
867have):
868 Linux a wash
869 Solaris a wash
870 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000871
Tim Petersf29b64d2001-01-15 06:33:19 +0000872CAUTION: The C std isn't clear about this: in those cases where fgets
873writes something into the buffer, can it write into any position beyond the
874required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
875known on which it does; and it would be a strange way to code fgets. Still,
876getline_via_fgets may not work correctly if it does. The std test
877test_bufio.py should fail if platform fgets() routinely writes beyond the
878trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000879**************************************************************************/
880
Tim Petersf29b64d2001-01-15 06:33:19 +0000881/* Use this routine if told to, or by default on non-get_unlocked()
882 * platforms unless told not to. Yikes! Let's spell that out:
883 * On a platform with getc_unlocked():
884 * By default, use getc_unlocked().
885 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
886 * On a platform without getc_unlocked():
887 * By default, use fgets().
888 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
889 */
890#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
891#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000892#endif
893
Tim Petersf29b64d2001-01-15 06:33:19 +0000894#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
895#undef USE_FGETS_IN_GETLINE
896#endif
897
898#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000899static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000900getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000901{
Tim Peters15b83852001-01-08 00:53:12 +0000902/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000903 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
904 * to fill this much of the buffer with a known value in order to figure out
905 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
906 * than "most" lines, we waste time filling unused buffer slots. 100 is
907 * surely adequate for most peoples' email archives, chewing over source code,
908 * etc -- "regular old text files".
909 * MAXBUFSIZE is the maximum line length that lets us get away with the less
910 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
911 * cautions about boosting that. 300 was chosen because the worst real-life
912 * text-crunching job reported on Python-Dev was a mail-log crawler where over
913 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000914 */
Tim Peters142297a2001-01-15 10:36:56 +0000915#define INITBUFSIZE 100
916#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000917 char* p; /* temp */
918 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000919 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000920 char* pvfree; /* address of next free slot */
921 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000922 size_t nfree; /* # of free buffer slots; pvend-pvfree */
923 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000924 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000925
Tim Peters15b83852001-01-08 00:53:12 +0000926 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000927 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000928 */
Tim Peters142297a2001-01-15 10:36:56 +0000929 total_v_size = INITBUFSIZE; /* start small and pray */
930 pvfree = buf;
931 for (;;) {
932 Py_BEGIN_ALLOW_THREADS
933 pvend = buf + total_v_size;
934 nfree = pvend - pvfree;
935 memset(pvfree, '\n', nfree);
936 p = fgets(pvfree, nfree, fp);
937 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000938
Tim Peters142297a2001-01-15 10:36:56 +0000939 if (p == NULL) {
940 clearerr(fp);
941 if (PyErr_CheckSignals())
942 return NULL;
943 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000944 return v;
945 }
Tim Peters142297a2001-01-15 10:36:56 +0000946 /* fgets read *something* */
947 p = memchr(pvfree, '\n', nfree);
948 if (p != NULL) {
949 /* Did the \n come from fgets or from us?
950 * Since fgets stops at the first \n, and then writes
951 * \0, if it's from fgets a \0 must be next. But if
952 * that's so, it could not have come from us, since
953 * the \n's we filled the buffer with have only more
954 * \n's to the right.
955 */
956 if (p+1 < pvend && *(p+1) == '\0') {
957 /* It's from fgets: we win! In particular,
958 * we haven't done any mallocs yet, and can
959 * build the final result on the first try.
960 */
961 ++p; /* include \n from fgets */
962 }
963 else {
964 /* Must be from us: fgets didn't fill the
965 * buffer and didn't find a newline, so it
966 * must be the last and newline-free line of
967 * the file.
968 */
969 assert(p > pvfree && *(p-1) == '\0');
970 --p; /* don't include \0 from fgets */
971 }
972 v = PyString_FromStringAndSize(buf, p - buf);
973 return v;
974 }
975 /* yuck: fgets overwrote all the newlines, i.e. the entire
976 * buffer. So this line isn't over yet, or maybe it is but
977 * we're exactly at EOF. If we haven't already, try using the
978 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +0000979 */
Tim Peters142297a2001-01-15 10:36:56 +0000980 assert(*(pvend-1) == '\0');
981 if (pvfree == buf) {
982 pvfree = pvend - 1; /* overwrite trailing null */
983 total_v_size = MAXBUFSIZE;
984 }
985 else
986 break;
Tim Peters86821b22001-01-07 21:19:34 +0000987 }
Tim Peters142297a2001-01-15 10:36:56 +0000988
989 /* The stack buffer isn't big enough; malloc a string object and read
990 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +0000991 */
Tim Petersddea2082002-03-23 10:03:50 +0000992 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +0000993 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +0000994 if (v == NULL)
995 return v;
996 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +0000997 memcpy(BUF(v), buf, MAXBUFSIZE-1);
998 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +0000999
1000 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001001 * after setting p one beyond the end of the line. The code here is
1002 * very much like the code above, except reads into v's buffer; see
1003 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001004 */
1005 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001006 Py_BEGIN_ALLOW_THREADS
1007 pvend = BUF(v) + total_v_size;
1008 nfree = pvend - pvfree;
1009 memset(pvfree, '\n', nfree);
1010 p = fgets(pvfree, nfree, fp);
1011 Py_END_ALLOW_THREADS
1012
1013 if (p == NULL) {
1014 clearerr(fp);
1015 if (PyErr_CheckSignals()) {
1016 Py_DECREF(v);
1017 return NULL;
1018 }
1019 p = pvfree;
1020 break;
1021 }
Tim Peters86821b22001-01-07 21:19:34 +00001022 p = memchr(pvfree, '\n', nfree);
1023 if (p != NULL) {
1024 if (p+1 < pvend && *(p+1) == '\0') {
1025 /* \n came from fgets */
1026 ++p;
1027 break;
1028 }
1029 /* \n came from us; last line of file, no newline */
1030 assert(p > pvfree && *(p-1) == '\0');
1031 --p;
1032 break;
1033 }
1034 /* expand buffer and try again */
1035 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001036 increment = total_v_size >> 2; /* mild exponential growth */
1037 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001038 if (total_v_size > INT_MAX) {
1039 PyErr_SetString(PyExc_OverflowError,
1040 "line is longer than a Python string can hold");
1041 Py_DECREF(v);
1042 return NULL;
1043 }
1044 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1045 return NULL;
1046 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001047 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001048 }
1049 if (BUF(v) + total_v_size != p)
1050 _PyString_Resize(&v, p - BUF(v));
1051 return v;
1052#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001053#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001054}
Tim Petersf29b64d2001-01-15 06:33:19 +00001055#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001056
Guido van Rossum0bd24411991-04-04 15:21:57 +00001057/* Internal routine to get a line.
1058 Size argument interpretation:
1059 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001060 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001061*/
1062
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001063static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001064get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001065{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001066 FILE *fp = f->f_fp;
1067 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001068 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001069 size_t total_v_size; /* total # of slots in buffer */
1070 size_t used_v_size; /* # used slots in buffer */
1071 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001072 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001073#ifdef WITH_UNIVERSAL_NEWLINES
1074 int newlinetypes = f->f_newlinetypes;
1075 int skipnextlf = f->f_skipnextlf;
1076 int univ_newline = f->f_univ_newline;
1077#endif
Guido van Rossum0bd24411991-04-04 15:21:57 +00001078
Jack Jansen7b8c7542002-04-14 20:12:41 +00001079#if defined(USE_FGETS_IN_GETLINE)
1080#ifdef WITH_UNIVERSAL_NEWLINES
1081 if (n <= 0 && !univ_newline )
1082#else
Guido van Rossum86282062001-01-08 01:26:47 +00001083 if (n <= 0)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001084#endif
Tim Petersf29b64d2001-01-15 06:33:19 +00001085 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001086#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001087 total_v_size = n > 0 ? n : 100;
1088 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001089 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001090 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001091 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001092 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001093
Guido van Rossumce5ba841991-03-06 13:06:18 +00001094 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001095 Py_BEGIN_ALLOW_THREADS
1096 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001097#ifdef WITH_UNIVERSAL_NEWLINES
1098 if (univ_newline) {
1099 c = 'x'; /* Shut up gcc warning */
1100 while ( buf != end && (c = GETC(fp)) != EOF ) {
1101 if (skipnextlf ) {
1102 skipnextlf = 0;
1103 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001104 /* Seeing a \n here with
1105 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001106 * saw a \r before.
1107 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001108 newlinetypes |= NEWLINE_CRLF;
1109 c = GETC(fp);
1110 if (c == EOF) break;
1111 } else {
1112 newlinetypes |= NEWLINE_CR;
1113 }
1114 }
1115 if (c == '\r') {
1116 skipnextlf = 1;
1117 c = '\n';
1118 } else if ( c == '\n')
1119 newlinetypes |= NEWLINE_LF;
1120 *buf++ = c;
1121 if (c == '\n') break;
1122 }
1123 if ( c == EOF && skipnextlf )
1124 newlinetypes |= NEWLINE_CR;
1125 } else /* If not universal newlines use the normal loop */
1126#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001127 while ((c = GETC(fp)) != EOF &&
1128 (*buf++ = c) != '\n' &&
1129 buf != end)
1130 ;
1131 FUNLOCKFILE(fp);
1132 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001133#ifdef WITH_UNIVERSAL_NEWLINES
1134 f->f_newlinetypes = newlinetypes;
1135 f->f_skipnextlf = skipnextlf;
1136#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001137 if (c == '\n')
1138 break;
1139 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001140 if (ferror(fp)) {
1141 PyErr_SetFromErrno(PyExc_IOError);
1142 clearerr(fp);
1143 Py_DECREF(v);
1144 return NULL;
1145 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001146 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001147 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001148 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001149 return NULL;
1150 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001151 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001152 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001153 /* Must be because buf == end */
1154 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001155 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001156 used_v_size = total_v_size;
1157 increment = total_v_size >> 2; /* mild exponential growth */
1158 total_v_size += increment;
1159 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001160 PyErr_SetString(PyExc_OverflowError,
1161 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001162 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001163 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001164 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001165 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001166 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001167 buf = BUF(v) + used_v_size;
1168 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001169 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001171 used_v_size = buf - BUF(v);
1172 if (used_v_size != total_v_size)
1173 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001174 return v;
1175}
1176
Guido van Rossum0bd24411991-04-04 15:21:57 +00001177/* External C interface */
1178
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001179PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001180PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001181{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001182 PyObject *result;
1183
Guido van Rossum3165fe61992-09-25 21:59:05 +00001184 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001185 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001186 return NULL;
1187 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001188
1189 if (PyFile_Check(f)) {
1190 if (((PyFileObject*)f)->f_fp == NULL)
1191 return err_closed();
1192 result = get_line((PyFileObject *)f, n);
1193 }
1194 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001195 PyObject *reader;
1196 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001197
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001198 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001199 if (reader == NULL)
1200 return NULL;
1201 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001202 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001203 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001204 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001205 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001206 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001207 return NULL;
1208 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001209 result = PyEval_CallObject(reader, args);
1210 Py_DECREF(reader);
1211 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001212 if (result != NULL && !PyString_Check(result) &&
1213 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001214 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001215 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001216 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001217 "object.readline() returned non-string");
1218 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001219 }
1220
1221 if (n < 0 && result != NULL && PyString_Check(result)) {
1222 char *s = PyString_AS_STRING(result);
1223 int len = PyString_GET_SIZE(result);
1224 if (len == 0) {
1225 Py_DECREF(result);
1226 result = NULL;
1227 PyErr_SetString(PyExc_EOFError,
1228 "EOF when reading a line");
1229 }
1230 else if (s[len-1] == '\n') {
1231 if (result->ob_refcnt == 1)
1232 _PyString_Resize(&result, len-1);
1233 else {
1234 PyObject *v;
1235 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001236 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001237 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001238 }
1239 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001240 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001241#ifdef Py_USING_UNICODE
1242 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1243 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1244 int len = PyUnicode_GET_SIZE(result);
1245 if (len == 0) {
1246 Py_DECREF(result);
1247 result = NULL;
1248 PyErr_SetString(PyExc_EOFError,
1249 "EOF when reading a line");
1250 }
1251 else if (s[len-1] == '\n') {
1252 if (result->ob_refcnt == 1)
1253 PyUnicode_Resize(&result, len-1);
1254 else {
1255 PyObject *v;
1256 v = PyUnicode_FromUnicode(s, len-1);
1257 Py_DECREF(result);
1258 result = v;
1259 }
1260 }
1261 }
1262#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001263 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001264}
1265
1266/* Python method */
1267
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001268static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001269file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001270{
Guido van Rossum789a1611997-05-10 22:33:55 +00001271 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001272
Guido van Rossumd7297e61992-07-06 14:19:26 +00001273 if (f->f_fp == NULL)
1274 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001275 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001276 return NULL;
1277 if (n == 0)
1278 return PyString_FromString("");
1279 if (n < 0)
1280 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001281 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001282}
1283
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001284static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001285file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001286{
Guido van Rossum789a1611997-05-10 22:33:55 +00001287 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001288 PyObject *list;
1289 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001290 char small_buffer[SMALLCHUNK];
1291 char *buffer = small_buffer;
1292 size_t buffersize = SMALLCHUNK;
1293 PyObject *big_buffer = NULL;
1294 size_t nfilled = 0;
1295 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001296 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001297 char *p, *q, *end;
1298 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001299 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001300
Guido van Rossumd7297e61992-07-06 14:19:26 +00001301 if (f->f_fp == NULL)
1302 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001303 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001304 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001305 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001306 return NULL;
1307 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001308 if (shortread)
1309 nread = 0;
1310 else {
1311 Py_BEGIN_ALLOW_THREADS
1312 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001313 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001314 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001315 Py_END_ALLOW_THREADS
1316 shortread = (nread < buffersize-nfilled);
1317 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001318 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001319 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001320 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001321 break;
1322 PyErr_SetFromErrno(PyExc_IOError);
1323 clearerr(f->f_fp);
1324 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001325 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001326 list = NULL;
1327 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001328 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001329 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001330 p = memchr(buffer+nfilled, '\n', nread);
1331 if (p == NULL) {
1332 /* Need a larger buffer to fit this line */
1333 nfilled += nread;
1334 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001335 if (buffersize > INT_MAX) {
1336 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001337 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001338 goto error;
1339 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001340 if (big_buffer == NULL) {
1341 /* Create the big buffer */
1342 big_buffer = PyString_FromStringAndSize(
1343 NULL, buffersize);
1344 if (big_buffer == NULL)
1345 goto error;
1346 buffer = PyString_AS_STRING(big_buffer);
1347 memcpy(buffer, small_buffer, nfilled);
1348 }
1349 else {
1350 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001351 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1352 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001353 buffer = PyString_AS_STRING(big_buffer);
1354 }
1355 continue;
1356 }
1357 end = buffer+nfilled+nread;
1358 q = buffer;
1359 do {
1360 /* Process complete lines */
1361 p++;
1362 line = PyString_FromStringAndSize(q, p-q);
1363 if (line == NULL)
1364 goto error;
1365 err = PyList_Append(list, line);
1366 Py_DECREF(line);
1367 if (err != 0)
1368 goto error;
1369 q = p;
1370 p = memchr(q, '\n', end-q);
1371 } while (p != NULL);
1372 /* Move the remaining incomplete line to the start */
1373 nfilled = end-q;
1374 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001375 if (sizehint > 0)
1376 if (totalread >= (size_t)sizehint)
1377 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001378 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001379 if (nfilled != 0) {
1380 /* Partial last line */
1381 line = PyString_FromStringAndSize(buffer, nfilled);
1382 if (line == NULL)
1383 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001384 if (sizehint > 0) {
1385 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001386 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001387 if (rest == NULL) {
1388 Py_DECREF(line);
1389 goto error;
1390 }
1391 PyString_Concat(&line, rest);
1392 Py_DECREF(rest);
1393 if (line == NULL)
1394 goto error;
1395 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001396 err = PyList_Append(list, line);
1397 Py_DECREF(line);
1398 if (err != 0)
1399 goto error;
1400 }
1401 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001402 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001403 return list;
1404}
1405
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001406static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001407file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001408{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001409 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001410 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001411 if (f->f_fp == NULL)
1412 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001413 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001414 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001415 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001416 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001417 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001418 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001419 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001420 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001421 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001422 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001423 return NULL;
1424 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001425 Py_INCREF(Py_None);
1426 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001427}
1428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001430file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001431{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001432#define CHUNKSIZE 1000
1433 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001434 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001435 PyObject *result;
1436 int i, j, index, len, nwritten, islist;
1437
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001438 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001439 if (f->f_fp == NULL)
1440 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001441
1442 result = NULL;
1443 list = NULL;
1444 islist = PyList_Check(seq);
1445 if (islist)
1446 it = NULL;
1447 else {
1448 it = PyObject_GetIter(seq);
1449 if (it == NULL) {
1450 PyErr_SetString(PyExc_TypeError,
1451 "writelines() requires an iterable argument");
1452 return NULL;
1453 }
1454 /* From here on, fail by going to error, to reclaim "it". */
1455 list = PyList_New(CHUNKSIZE);
1456 if (list == NULL)
1457 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001458 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001459
1460 /* Strategy: slurp CHUNKSIZE lines into a private list,
1461 checking that they are all strings, then write that list
1462 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001463 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001464 if (islist) {
1465 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001466 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001467 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001468 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001469 j = PyList_GET_SIZE(list);
1470 }
1471 else {
1472 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001473 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001474 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001475 if (PyErr_Occurred())
1476 goto error;
1477 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001478 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001479 PyList_SetItem(list, j, line);
1480 }
1481 }
1482 if (j == 0)
1483 break;
1484
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001485 /* Check that all entries are indeed strings. If not,
1486 apply the same rules as for file.write() and
1487 convert the results to strings. This is slow, but
1488 seems to be the only way since all conversion APIs
1489 could potentially execute Python code. */
1490 for (i = 0; i < j; i++) {
1491 PyObject *v = PyList_GET_ITEM(list, i);
1492 if (!PyString_Check(v)) {
1493 const char *buffer;
1494 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001495 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001496 PyObject_AsReadBuffer(v,
1497 (const void**)&buffer,
1498 &len)) ||
1499 PyObject_AsCharBuffer(v,
1500 &buffer,
1501 &len))) {
1502 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001503 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001504 goto error;
1505 }
1506 line = PyString_FromStringAndSize(buffer,
1507 len);
1508 if (line == NULL)
1509 goto error;
1510 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001511 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001512 }
1513 }
1514
1515 /* Since we are releasing the global lock, the
1516 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001517 Py_BEGIN_ALLOW_THREADS
1518 f->f_softspace = 0;
1519 errno = 0;
1520 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001521 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001522 len = PyString_GET_SIZE(line);
1523 nwritten = fwrite(PyString_AS_STRING(line),
1524 1, len, f->f_fp);
1525 if (nwritten != len) {
1526 Py_BLOCK_THREADS
1527 PyErr_SetFromErrno(PyExc_IOError);
1528 clearerr(f->f_fp);
1529 goto error;
1530 }
1531 }
1532 Py_END_ALLOW_THREADS
1533
1534 if (j < CHUNKSIZE)
1535 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001536 }
1537
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001538 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539 result = Py_None;
1540 error:
1541 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001542 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001543 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001544#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001545}
1546
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001547static PyObject *
1548file_getiter(PyFileObject *f)
1549{
1550 if (f->f_fp == NULL)
1551 return err_closed();
1552 Py_INCREF(f);
1553 return (PyObject *)f;
1554}
1555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001556PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001557"readline([size]) -> next line from the file, as a string.\n"
1558"\n"
1559"Retain newline. A non-negative size argument limits the maximum\n"
1560"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001561"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001563PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001564"read([size]) -> read at most size bytes, returned as a string.\n"
1565"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001566"If the size argument is negative or omitted, read until EOF is reached.\n"
1567"Notice that when in non-blocking mode, less data than what was requested\n"
1568"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001570PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001571"write(str) -> None. Write string str to file.\n"
1572"\n"
1573"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001574"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001576PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001577"fileno() -> integer \"file descriptor\".\n"
1578"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001579"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001581PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001582"seek(offset[, whence]) -> None. Move to new file position.\n"
1583"\n"
1584"Argument offset is a byte count. Optional argument whence defaults to\n"
1585"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1586"(move relative to current position, positive or negative), and 2 (move\n"
1587"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001588"seeking beyond the end of a file). If the file is opened in text mode,\n"
1589"only offsets returned by tell() are legal. Use of other offsets causes\n"
1590"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001591"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001592"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001593
Guido van Rossumd7047b31995-01-02 19:07:15 +00001594#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001595PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001596"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1597"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001598"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001599#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001601PyDoc_STRVAR(tell_doc,
1602"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001604PyDoc_STRVAR(readinto_doc,
1605"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001607PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001608"readlines([size]) -> list of strings, each a line from the file.\n"
1609"\n"
1610"Call readline() repeatedly and return a list of the lines so read.\n"
1611"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001612"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001613
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001614PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001615"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001616"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001617"For backward compatibility. File objects now include the performance\n"
1618"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001620PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001621"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001622"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001623"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001624"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001626PyDoc_STRVAR(flush_doc,
1627"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001629PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001630"close() -> None or (perhaps) an integer. Close the file.\n"
1631"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001632"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001633"further I/O operations. close() may be called more than once without\n"
1634"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001636
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001637PyDoc_STRVAR(isatty_doc,
1638"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001639
1640static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001641 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1642 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1643 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1644 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1645 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001646#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001647 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001648#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001649 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1650 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1651 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1652 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1653 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1654 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1655 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1656 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1657 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001658};
1659
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001660#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001661
Guido van Rossum6f799372001-09-20 20:46:19 +00001662static PyMemberDef file_memberlist[] = {
1663 {"softspace", T_INT, OFF(f_softspace), 0,
1664 "flag indicating that a space needs to be printed; used by print"},
1665 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001666 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001667 {"name", T_OBJECT, OFF(f_name), RO,
1668 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001669 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1670 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001671 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001672 {NULL} /* Sentinel */
1673};
1674
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001675static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001677{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001678 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001679}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001680#ifdef WITH_UNIVERSAL_NEWLINES
1681static PyObject *
1682get_newlines(PyFileObject *f, void *closure)
1683{
1684 switch (f->f_newlinetypes) {
1685 case NEWLINE_UNKNOWN:
1686 Py_INCREF(Py_None);
1687 return Py_None;
1688 case NEWLINE_CR:
1689 return PyString_FromString("\r");
1690 case NEWLINE_LF:
1691 return PyString_FromString("\n");
1692 case NEWLINE_CR|NEWLINE_LF:
1693 return Py_BuildValue("(ss)", "\r", "\n");
1694 case NEWLINE_CRLF:
1695 return PyString_FromString("\r\n");
1696 case NEWLINE_CR|NEWLINE_CRLF:
1697 return Py_BuildValue("(ss)", "\r", "\r\n");
1698 case NEWLINE_LF|NEWLINE_CRLF:
1699 return Py_BuildValue("(ss)", "\n", "\r\n");
1700 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1701 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1702 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001703 PyErr_Format(PyExc_SystemError,
1704 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001705 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001706 return NULL;
1707 }
1708}
1709#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +00001710
Guido van Rossum32d34c82001-09-20 21:45:26 +00001711static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001712 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001713#ifdef WITH_UNIVERSAL_NEWLINES
Tim Petersf1827cf2003-09-07 03:30:18 +00001714 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001715 "end-of-line convention used in this file"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001716#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717 {0},
1718};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001719
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001720static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001721drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001722{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001723 if (f->f_buf != NULL) {
1724 PyMem_Free(f->f_buf);
1725 f->f_buf = NULL;
1726 }
Guido van Rossum65967252001-04-21 13:20:18 +00001727}
1728
Tim Petersf1827cf2003-09-07 03:30:18 +00001729/* Make sure that file has a readahead buffer with at least one byte
1730 (unless at EOF) and no more than bufsize. Returns negative value on
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001731 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001732static int
1733readahead(PyFileObject *f, int bufsize)
1734{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001735 int chunksize;
1736
1737 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001738 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001739 return 0;
1740 else
1741 drop_readahead(f);
1742 }
1743 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1744 return -1;
1745 }
1746 Py_BEGIN_ALLOW_THREADS
1747 errno = 0;
1748 chunksize = Py_UniversalNewlineFread(
1749 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1750 Py_END_ALLOW_THREADS
1751 if (chunksize == 0) {
1752 if (ferror(f->f_fp)) {
1753 PyErr_SetFromErrno(PyExc_IOError);
1754 clearerr(f->f_fp);
1755 drop_readahead(f);
1756 return -1;
1757 }
1758 }
1759 f->f_bufptr = f->f_buf;
1760 f->f_bufend = f->f_buf + chunksize;
1761 return 0;
1762}
1763
1764/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001765 uninitialized bytes followed by the remainder of the line. Don't be
1766 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001767 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1768
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001769static PyStringObject *
1770readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1771{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001772 PyStringObject* s;
1773 char *bufptr;
1774 char *buf;
1775 int len;
1776
1777 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001778 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001779 return NULL;
1780
1781 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001782 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001783 return (PyStringObject *)
1784 PyString_FromStringAndSize(NULL, skip);
1785 bufptr = memchr(f->f_bufptr, '\n', len);
1786 if (bufptr != NULL) {
1787 bufptr++; /* Count the '\n' */
1788 len = bufptr - f->f_bufptr;
1789 s = (PyStringObject *)
1790 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001791 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001792 return NULL;
1793 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1794 f->f_bufptr = bufptr;
1795 if (bufptr == f->f_bufend)
1796 drop_readahead(f);
1797 } else {
1798 bufptr = f->f_bufptr;
1799 buf = f->f_buf;
1800 f->f_buf = NULL; /* Force new readahead buffer */
1801 s = readahead_get_line_skip(
1802 f, skip+len, bufsize + (bufsize>>2) );
1803 if (s == NULL) {
1804 PyMem_Free(buf);
1805 return NULL;
1806 }
1807 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1808 PyMem_Free(buf);
1809 }
1810 return s;
1811}
1812
1813/* A larger buffer size may actually decrease performance. */
1814#define READAHEAD_BUFSIZE 8192
1815
1816static PyObject *
1817file_iternext(PyFileObject *f)
1818{
1819 PyStringObject* l;
1820
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001821 if (f->f_fp == NULL)
1822 return err_closed();
1823
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001824 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1825 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1826 Py_XDECREF(l);
1827 return NULL;
1828 }
1829 return (PyObject *)l;
1830}
1831
1832
Tim Peters59c9a642001-09-13 05:38:56 +00001833static PyObject *
1834file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1835{
Tim Peters44410012001-09-14 03:26:08 +00001836 PyObject *self;
1837 static PyObject *not_yet_string;
1838
1839 assert(type != NULL && type->tp_alloc != NULL);
1840
1841 if (not_yet_string == NULL) {
1842 not_yet_string = PyString_FromString("<uninitialized file>");
1843 if (not_yet_string == NULL)
1844 return NULL;
1845 }
1846
1847 self = type->tp_alloc(type, 0);
1848 if (self != NULL) {
1849 /* Always fill in the name and mode, so that nobody else
1850 needs to special-case NULLs there. */
1851 Py_INCREF(not_yet_string);
1852 ((PyFileObject *)self)->f_name = not_yet_string;
1853 Py_INCREF(not_yet_string);
1854 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001855 Py_INCREF(Py_None);
1856 ((PyFileObject *)self)->f_encoding = Py_None;
Tim Peters44410012001-09-14 03:26:08 +00001857 }
1858 return self;
1859}
1860
1861static int
1862file_init(PyObject *self, PyObject *args, PyObject *kwds)
1863{
1864 PyFileObject *foself = (PyFileObject *)self;
1865 int ret = 0;
Tim Peters59c9a642001-09-13 05:38:56 +00001866 static char *kwlist[] = {"name", "mode", "buffering", 0};
1867 char *name = NULL;
1868 char *mode = "r";
1869 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001870 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001871
1872 assert(PyFile_Check(self));
1873 if (foself->f_fp != NULL) {
1874 /* Have to close the existing file first. */
1875 PyObject *closeresult = file_close(foself);
1876 if (closeresult == NULL)
1877 return -1;
1878 Py_DECREF(closeresult);
1879 }
Tim Peters59c9a642001-09-13 05:38:56 +00001880
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001881#ifdef Py_WIN_WIDE_FILENAMES
1882 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1883 PyObject *po;
1884 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1885 kwlist, &po, &mode, &bufsize)) {
1886 wideargument = 1;
1887 if (fill_file_fields(foself, NULL, name, mode,
1888 fclose, po) == NULL)
1889 goto Error;
1890 } else {
1891 /* Drop the argument parsing error as narrow
1892 strings are also valid. */
1893 PyErr_Clear();
1894 }
1895 }
1896#endif
1897
1898 if (!wideargument) {
1899 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1900 Py_FileSystemDefaultEncoding,
1901 &name,
1902 &mode, &bufsize))
1903 return -1;
1904 if (fill_file_fields(foself, NULL, name, mode,
1905 fclose, NULL) == NULL)
1906 goto Error;
1907 }
Tim Peters44410012001-09-14 03:26:08 +00001908 if (open_the_file(foself, name, mode) == NULL)
1909 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00001910 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001911 PyFile_SetBufSize(self, bufsize);
1912 goto Done;
1913
1914Error:
1915 ret = -1;
1916 /* fall through */
1917Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001918 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001919 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001920}
1921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001922PyDoc_VAR(file_doc) =
1923PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001924"file(name[, mode[, buffering]]) -> file object\n"
1925"\n"
1926"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1927"writing or appending. The file will be created if it doesn't exist\n"
1928"when opened for writing or appending; it will be truncated when\n"
1929"opened for writing. Add a 'b' to the mode for binary files.\n"
1930"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1931"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001932"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001933)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001934#ifdef WITH_UNIVERSAL_NEWLINES
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001935PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001936"Add a 'U' to mode to open the file for input with universal newline\n"
1937"support. Any line ending in the input file will be seen as a '\\n'\n"
1938"in Python. Also, a file so opened gains the attribute 'newlines';\n"
1939"the value for this attribute is one of None (no newline read yet),\n"
1940"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
1941"\n"
1942"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001943)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001944#endif /* WITH_UNIVERSAL_NEWLINES */
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001945PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001946"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001947"Note: open() is an alias for file()."
1948);
Tim Peters59c9a642001-09-13 05:38:56 +00001949
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001950PyTypeObject PyFile_Type = {
1951 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001952 0,
1953 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001954 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001955 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001956 (destructor)file_dealloc, /* tp_dealloc */
1957 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001958 0, /* tp_getattr */
1959 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001960 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001962 0, /* tp_as_number */
1963 0, /* tp_as_sequence */
1964 0, /* tp_as_mapping */
1965 0, /* tp_hash */
1966 0, /* tp_call */
1967 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00001969 /* softspace is writable: we must supply tp_setattro */
1970 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00001971 0, /* tp_as_buffer */
Guido van Rossum9475a232001-10-05 20:51:39 +00001972 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00001973 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974 0, /* tp_traverse */
1975 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00001976 0, /* tp_richcompare */
1977 0, /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001978 (getiterfunc)file_getiter, /* tp_iter */
1979 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980 file_methods, /* tp_methods */
1981 file_memberlist, /* tp_members */
1982 file_getsetlist, /* tp_getset */
1983 0, /* tp_base */
1984 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00001985 0, /* tp_descr_get */
1986 0, /* tp_descr_set */
1987 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00001988 (initproc)file_init, /* tp_init */
1989 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00001990 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00001991 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001992};
Guido van Rossumeb183da1991-04-04 10:44:06 +00001993
1994/* Interface for the 'soft space' between print items. */
1995
1996int
Fred Drakefd99de62000-07-09 05:02:18 +00001997PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00001998{
1999 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002000 if (f == NULL) {
2001 /* Do nothing */
2002 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003 else if (PyFile_Check(f)) {
2004 oldflag = ((PyFileObject *)f)->f_softspace;
2005 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002006 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002007 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008 PyObject *v;
2009 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002010 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002011 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002012 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002013 if (PyInt_Check(v))
2014 oldflag = PyInt_AsLong(v);
2015 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002016 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002017 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002018 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002020 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002021 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2022 PyErr_Clear();
2023 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002024 }
2025 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00002026 return oldflag;
2027}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002028
2029/* Interfaces to write objects/strings to file-like objects */
2030
2031int
Fred Drakefd99de62000-07-09 05:02:18 +00002032PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002033{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002035 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002036 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002037 return -1;
2038 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002039 else if (PyFile_Check(f)) {
2040 FILE *fp = PyFile_AsFile(f);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002041 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2042 int result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002043 if (fp == NULL) {
2044 err_closed();
2045 return -1;
2046 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002047#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002048 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002049 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002050 char *cenc = PyString_AS_STRING(enc);
2051 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2052 if (value == NULL)
2053 return -1;
2054 } else {
2055 value = v;
2056 Py_INCREF(value);
2057 }
2058 result = PyObject_Print(value, fp, flags);
2059 Py_DECREF(value);
2060 return result;
2061#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002062 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002063#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002064 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002065 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002066 if (writer == NULL)
2067 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002068 if (flags & Py_PRINT_RAW) {
2069 if (PyUnicode_Check(v)) {
2070 value = v;
2071 Py_INCREF(value);
2072 } else
2073 value = PyObject_Str(v);
2074 }
2075 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002076 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002077 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002078 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002079 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002080 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002081 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002082 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002083 Py_DECREF(value);
2084 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002085 return -1;
2086 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002087 result = PyEval_CallObject(writer, args);
2088 Py_DECREF(args);
2089 Py_DECREF(value);
2090 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002091 if (result == NULL)
2092 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002094 return 0;
2095}
2096
Guido van Rossum27a60b11997-05-22 22:25:11 +00002097int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002098PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002099{
2100 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002101 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002102 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002103 PyErr_SetString(PyExc_SystemError,
2104 "null file for PyFile_WriteString");
2105 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002106 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107 else if (PyFile_Check(f)) {
2108 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002109 if (fp == NULL) {
2110 err_closed();
2111 return -1;
2112 }
2113 fputs(s, fp);
2114 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002115 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002116 else if (!PyErr_Occurred()) {
2117 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002118 int err;
2119 if (v == NULL)
2120 return -1;
2121 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2122 Py_DECREF(v);
2123 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002124 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002125 else
2126 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002127}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002128
2129/* Try to get a file-descriptor from a Python object. If the object
2130 is an integer or long integer, its value is returned. If not, the
2131 object's fileno() method is called if it exists; the method must return
2132 an integer or long integer, which is returned as the file descriptor value.
2133 -1 is returned on failure.
2134*/
2135
2136int PyObject_AsFileDescriptor(PyObject *o)
2137{
2138 int fd;
2139 PyObject *meth;
2140
2141 if (PyInt_Check(o)) {
2142 fd = PyInt_AsLong(o);
2143 }
2144 else if (PyLong_Check(o)) {
2145 fd = PyLong_AsLong(o);
2146 }
2147 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2148 {
2149 PyObject *fno = PyEval_CallObject(meth, NULL);
2150 Py_DECREF(meth);
2151 if (fno == NULL)
2152 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002153
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002154 if (PyInt_Check(fno)) {
2155 fd = PyInt_AsLong(fno);
2156 Py_DECREF(fno);
2157 }
2158 else if (PyLong_Check(fno)) {
2159 fd = PyLong_AsLong(fno);
2160 Py_DECREF(fno);
2161 }
2162 else {
2163 PyErr_SetString(PyExc_TypeError,
2164 "fileno() returned a non-integer");
2165 Py_DECREF(fno);
2166 return -1;
2167 }
2168 }
2169 else {
2170 PyErr_SetString(PyExc_TypeError,
2171 "argument must be an int, or have a fileno() method.");
2172 return -1;
2173 }
2174
2175 if (fd < 0) {
2176 PyErr_Format(PyExc_ValueError,
2177 "file descriptor cannot be a negative integer (%i)",
2178 fd);
2179 return -1;
2180 }
2181 return fd;
2182}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002183
2184#ifdef WITH_UNIVERSAL_NEWLINES
2185/* From here on we need access to the real fgets and fread */
2186#undef fgets
2187#undef fread
2188
2189/*
2190** Py_UniversalNewlineFgets is an fgets variation that understands
2191** all of \r, \n and \r\n conventions.
2192** The stream should be opened in binary mode.
2193** If fobj is NULL the routine always does newline conversion, and
2194** it may peek one char ahead to gobble the second char in \r\n.
2195** If fobj is non-NULL it must be a PyFileObject. In this case there
2196** is no readahead but in stead a flag is used to skip a following
2197** \n on the next read. Also, if the file is open in binary mode
2198** the whole conversion is skipped. Finally, the routine keeps track of
2199** the different types of newlines seen.
2200** Note that we need no error handling: fgets() treats error and eof
2201** identically.
2202*/
2203char *
2204Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2205{
2206 char *p = buf;
2207 int c;
2208 int newlinetypes = 0;
2209 int skipnextlf = 0;
2210 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002211
Jack Jansen7b8c7542002-04-14 20:12:41 +00002212 if (fobj) {
2213 if (!PyFile_Check(fobj)) {
2214 errno = ENXIO; /* What can you do... */
2215 return NULL;
2216 }
2217 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2218 if ( !univ_newline )
2219 return fgets(buf, n, stream);
2220 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2221 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2222 }
2223 FLOCKFILE(stream);
2224 c = 'x'; /* Shut up gcc warning */
2225 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2226 if (skipnextlf ) {
2227 skipnextlf = 0;
2228 if (c == '\n') {
2229 /* Seeing a \n here with skipnextlf true
2230 ** means we saw a \r before.
2231 */
2232 newlinetypes |= NEWLINE_CRLF;
2233 c = GETC(stream);
2234 if (c == EOF) break;
2235 } else {
2236 /*
2237 ** Note that c == EOF also brings us here,
2238 ** so we're okay if the last char in the file
2239 ** is a CR.
2240 */
2241 newlinetypes |= NEWLINE_CR;
2242 }
2243 }
2244 if (c == '\r') {
2245 /* A \r is translated into a \n, and we skip
2246 ** an adjacent \n, if any. We don't set the
2247 ** newlinetypes flag until we've seen the next char.
2248 */
2249 skipnextlf = 1;
2250 c = '\n';
2251 } else if ( c == '\n') {
2252 newlinetypes |= NEWLINE_LF;
2253 }
2254 *p++ = c;
2255 if (c == '\n') break;
2256 }
2257 if ( c == EOF && skipnextlf )
2258 newlinetypes |= NEWLINE_CR;
2259 FUNLOCKFILE(stream);
2260 *p = '\0';
2261 if (fobj) {
2262 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2263 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2264 } else if ( skipnextlf ) {
2265 /* If we have no file object we cannot save the
2266 ** skipnextlf flag. We have to readahead, which
2267 ** will cause a pause if we're reading from an
2268 ** interactive stream, but that is very unlikely
2269 ** unless we're doing something silly like
2270 ** execfile("/dev/tty").
2271 */
2272 c = GETC(stream);
2273 if ( c != '\n' )
2274 ungetc(c, stream);
2275 }
2276 if (p == buf)
2277 return NULL;
2278 return buf;
2279}
2280
2281/*
2282** Py_UniversalNewlineFread is an fread variation that understands
2283** all of \r, \n and \r\n conventions.
2284** The stream should be opened in binary mode.
2285** fobj must be a PyFileObject. In this case there
2286** is no readahead but in stead a flag is used to skip a following
2287** \n on the next read. Also, if the file is open in binary mode
2288** the whole conversion is skipped. Finally, the routine keeps track of
2289** the different types of newlines seen.
2290*/
2291size_t
Tim Peters058b1412002-04-21 07:29:14 +00002292Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002293 FILE *stream, PyObject *fobj)
2294{
Tim Peters058b1412002-04-21 07:29:14 +00002295 char *dst = buf;
2296 PyFileObject *f = (PyFileObject *)fobj;
2297 int newlinetypes, skipnextlf;
2298
2299 assert(buf != NULL);
2300 assert(stream != NULL);
2301
Jack Jansen7b8c7542002-04-14 20:12:41 +00002302 if (!fobj || !PyFile_Check(fobj)) {
2303 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002304 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002305 }
Tim Peters058b1412002-04-21 07:29:14 +00002306 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002307 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002308 newlinetypes = f->f_newlinetypes;
2309 skipnextlf = f->f_skipnextlf;
2310 /* Invariant: n is the number of bytes remaining to be filled
2311 * in the buffer.
2312 */
2313 while (n) {
2314 size_t nread;
2315 int shortread;
2316 char *src = dst;
2317
2318 nread = fread(dst, 1, n, stream);
2319 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002320 if (nread == 0)
2321 break;
2322
Tim Peterse1682a82002-04-21 18:15:20 +00002323 n -= nread; /* assuming 1 byte out for each in; will adjust */
2324 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002325 while (nread--) {
2326 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002327 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002328 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002329 *dst++ = '\n';
2330 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002331 }
2332 else if (skipnextlf && c == '\n') {
2333 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002334 skipnextlf = 0;
2335 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002336 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002337 }
2338 else {
2339 /* Normal char to be stored in buffer. Also
2340 * update the newlinetypes flag if either this
2341 * is an LF or the previous char was a CR.
2342 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002343 if (c == '\n')
2344 newlinetypes |= NEWLINE_LF;
2345 else if (skipnextlf)
2346 newlinetypes |= NEWLINE_CR;
2347 *dst++ = c;
2348 skipnextlf = 0;
2349 }
2350 }
Tim Peters058b1412002-04-21 07:29:14 +00002351 if (shortread) {
2352 /* If this is EOF, update type flags. */
2353 if (skipnextlf && feof(stream))
2354 newlinetypes |= NEWLINE_CR;
2355 break;
2356 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002357 }
Tim Peters058b1412002-04-21 07:29:14 +00002358 f->f_newlinetypes = newlinetypes;
2359 f->f_skipnextlf = skipnextlf;
2360 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002361}
2362#endif