blob: 8f903d1b467bf31f163f9a6224964b4e5ac1bae3 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* File object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossumff7e83d1999-08-27 20:39:37 +00007#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00009#endif /* DONT_HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Guido van Rossum685a38e1996-12-05 21:54:17 +000011#ifdef HAVE_UNISTD_H
12#include <unistd.h>
13#endif
14
Guido van Rossumb8199141997-05-06 15:23:24 +000015#ifdef MS_WIN32
Guido van Rossumb8199141997-05-06 15:23:24 +000016#define fileno _fileno
Trent Mickf29f47b2000-08-11 19:02:59 +000017/* can (almost fully) duplicate with _chsize, see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000018#define HAVE_FTRUNCATE
19#endif
20
Guido van Rossumf2044e11998-04-28 16:05:59 +000021#ifdef macintosh
22#ifdef USE_GUSI
23#define HAVE_FTRUNCATE
24#endif
25#endif
26
Jack Jansene08dea191995-04-23 22:12:47 +000027#ifdef __MWERKS__
28/* Mwerks fopen() doesn't always set errno */
29#define NO_FOPEN_ERRNO
30#endif
Guido van Rossum295d1711995-02-19 15:55:19 +000031
Guido van Rossumc0b618a1997-05-02 03:12:38 +000032#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000033
Guido van Rossumff7e83d1999-08-27 20:39:37 +000034#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000035#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000036#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037
Trent Mickf29f47b2000-08-11 19:02:59 +000038
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000039typedef struct {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040 PyObject_HEAD
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000041 FILE *f_fp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000042 PyObject *f_name;
43 PyObject *f_mode;
Tim Petersdbd9ba62000-07-09 03:09:57 +000044 int (*f_close)(FILE *);
Guido van Rossumeb183da1991-04-04 10:44:06 +000045 int f_softspace; /* Flag used by 'print' command */
Guido van Rossum4c08d552000-03-10 22:55:18 +000046 int f_binary; /* Flag which indicates whether the file is open
47 open in binary (1) or test (0) mode */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000048} PyFileObject;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049
50FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000051PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000053 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000055 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000056 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057}
58
Guido van Rossumc0b618a1997-05-02 03:12:38 +000059PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000060PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000063 return NULL;
64 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066}
67
Tim Peters59c9a642001-09-13 05:38:56 +000068
69static PyObject *
70fill_file_fields(PyFileObject *f, FILE *fp, char *name, char *mode,
71 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072{
Tim Peters59c9a642001-09-13 05:38:56 +000073 assert(f != NULL);
74 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +000075 assert(f->f_fp == NULL);
76
77 Py_DECREF(f->f_name);
78 Py_DECREF(f->f_mode);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 f->f_name = PyString_FromString(name);
80 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +000081
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +000082 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +000083 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +000084 f->f_binary = strchr(mode,'b') != NULL;
Tim Peters44410012001-09-14 03:26:08 +000085
Tim Peters59c9a642001-09-13 05:38:56 +000086 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000088 f->f_fp = fp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000089 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090}
91
Tim Peters59c9a642001-09-13 05:38:56 +000092static PyObject *
93open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000094{
Tim Peters59c9a642001-09-13 05:38:56 +000095 assert(f != NULL);
96 assert(PyFile_Check(f));
97 assert(name != NULL);
98 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +000099 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000100
Tim Peters8fa45672001-09-13 21:01:29 +0000101 /* rexec.py can't stop a user from getting the file() constructor --
102 all they have to do is get *any* file object f, and then do
103 type(f). Here we prevent them from doing damage with it. */
104 if (PyEval_GetRestricted()) {
105 PyErr_SetString(PyExc_IOError,
106 "file() constructor not accessible in restricted mode");
107 return NULL;
108 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000109#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000110 if (*mode == '*') {
111 FILE *fopenRF();
112 f->f_fp = fopenRF(name, mode+1);
113 }
114 else
115#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000116 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000118 f->f_fp = fopen(name, mode);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000119 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000120 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000121 if (f->f_fp == NULL) {
Jack Jansene08dea191995-04-23 22:12:47 +0000122#ifdef NO_FOPEN_ERRNO
Barry Warsaw52ddc0e1998-07-23 16:07:02 +0000123 /* Metroworks only, not testable, so unchanged */
Jack Jansene08dea191995-04-23 22:12:47 +0000124 if ( errno == 0 ) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125 PyErr_SetString(PyExc_IOError, "Cannot open file");
126 Py_DECREF(f);
Jack Jansene08dea191995-04-23 22:12:47 +0000127 return NULL;
128 }
129#endif
Barry Warsaw52ddc0e1998-07-23 16:07:02 +0000130 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Tim Peters59c9a642001-09-13 05:38:56 +0000131 f = NULL;
132 }
133 return (PyObject *)f;
134}
135
136PyObject *
137PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
138{
Tim Peters44410012001-09-14 03:26:08 +0000139 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
140 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000141 if (f != NULL) {
142 if (fill_file_fields(f, fp, name, mode, close) == NULL) {
143 Py_DECREF(f);
144 f = NULL;
145 }
146 }
147 return (PyObject *) f;
148}
149
150PyObject *
151PyFile_FromString(char *name, char *mode)
152{
153 extern int fclose(FILE *);
154 PyFileObject *f;
155
156 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
157 if (f != NULL) {
158 if (open_the_file(f, name, mode) == NULL) {
159 Py_DECREF(f);
160 f = NULL;
161 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Guido van Rossumb6775db1994-08-01 11:34:53 +0000166void
Fred Drakefd99de62000-07-09 05:02:18 +0000167PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000168{
169 if (bufsize >= 0) {
170#ifdef HAVE_SETVBUF
171 int type;
172 switch (bufsize) {
173 case 0:
174 type = _IONBF;
175 break;
176 case 1:
177 type = _IOLBF;
178 bufsize = BUFSIZ;
179 break;
180 default:
181 type = _IOFBF;
182 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
184 type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000185#else /* !HAVE_SETVBUF */
186 if (bufsize <= 1)
187 setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
188#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000189 }
190}
191
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000193err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000194{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000196 return NULL;
197}
198
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199/* Methods */
200
201static void
Fred Drakefd99de62000-07-09 05:02:18 +0000202file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000204 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000206 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000208 }
Tim Peters44410012001-09-14 03:26:08 +0000209 Py_XDECREF(f->f_name);
210 Py_XDECREF(f->f_mode);
Guido van Rossum9475a232001-10-05 20:51:39 +0000211 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212}
213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000215file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000217 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
218 f->f_fp == NULL ? "closed" : "open",
219 PyString_AsString(f->f_name),
220 PyString_AsString(f->f_mode),
221 f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222}
223
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000224static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000225file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000227 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000228 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000229 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000231 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000232 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000233 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000234 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 f->f_fp = NULL;
236 }
Guido van Rossumfebd5511992-03-04 16:39:24 +0000237 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000239 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 return PyInt_FromLong((long)sts);
241 Py_INCREF(Py_None);
242 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243}
244
Trent Mickf29f47b2000-08-11 19:02:59 +0000245
Guido van Rossumb8552162001-09-05 14:58:11 +0000246/* Our very own off_t-like type, 64-bit if possible */
247#if !defined(HAVE_LARGEFILE_SUPPORT)
248typedef off_t Py_off_t;
249#elif SIZEOF_OFF_T >= 8
250typedef off_t Py_off_t;
251#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000252typedef fpos_t Py_off_t;
253#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000254#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000255#endif
256
257
Trent Mickf29f47b2000-08-11 19:02:59 +0000258/* a portable fseek() function
259 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000260static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000261_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000262{
Guido van Rossumb8552162001-09-05 14:58:11 +0000263#if !defined(HAVE_LARGEFILE_SUPPORT)
264 return fseek(fp, offset, whence);
265#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000266 return fseeko(fp, offset, whence);
267#elif defined(HAVE_FSEEK64)
268 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000269#elif defined(__BEOS__)
270 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000271#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000272 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
273 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000274 fpos_t pos;
275 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000276 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000277#ifdef MS_WINDOWS
278 fflush(fp);
279 if (_lseeki64(fileno(fp), 0, 2) == -1)
280 return -1;
281#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000282 if (fseek(fp, 0, SEEK_END) != 0)
283 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000284#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000285 /* fall through */
286 case SEEK_CUR:
287 if (fgetpos(fp, &pos) != 0)
288 return -1;
289 offset += pos;
290 break;
291 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000292 }
293 return fsetpos(fp, &offset);
294#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000295#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000296#endif
297}
298
299
300/* a portable ftell() function
301 Return -1 on failure with errno set appropriately, current file
302 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000303static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000304_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000305{
Guido van Rossumb8552162001-09-05 14:58:11 +0000306#if !defined(HAVE_LARGEFILE_SUPPORT)
307 return ftell(fp);
308#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
309 return ftello(fp);
310#elif defined(HAVE_FTELL64)
311 return ftell64(fp);
312#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000313 fpos_t pos;
314 if (fgetpos(fp, &pos) != 0)
315 return -1;
316 return pos;
317#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000318#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000319#endif
320}
321
322
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000324file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000326 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000327 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000328 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000329 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000330
Guido van Rossumd7297e61992-07-06 14:19:26 +0000331 if (f->f_fp == NULL)
332 return err_closed();
333 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000334 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000335 return NULL;
336#if !defined(HAVE_LARGEFILE_SUPPORT)
337 offset = PyInt_AsLong(offobj);
338#else
339 offset = PyLong_Check(offobj) ?
340 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
341#endif
342 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000343 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000344
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000346 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000347 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000348 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000349
Guido van Rossumff4949e1992-08-05 19:58:53 +0000350 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000352 clearerr(f->f_fp);
353 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000354 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 Py_INCREF(Py_None);
356 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000357}
358
Trent Mickf29f47b2000-08-11 19:02:59 +0000359
Guido van Rossumd7047b31995-01-02 19:07:15 +0000360#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000362file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000363{
Guido van Rossumd7047b31995-01-02 19:07:15 +0000364 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000365 Py_off_t newsize;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000366 PyObject *newsizeobj;
Tim Peters86821b22001-01-07 21:19:34 +0000367
Guido van Rossumd7047b31995-01-02 19:07:15 +0000368 if (f->f_fp == NULL)
369 return err_closed();
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000370 newsizeobj = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +0000371 if (!PyArg_ParseTuple(args, "|O:truncate", &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000372 return NULL;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000373 if (newsizeobj != NULL) {
374#if !defined(HAVE_LARGEFILE_SUPPORT)
375 newsize = PyInt_AsLong(newsizeobj);
376#else
377 newsize = PyLong_Check(newsizeobj) ?
378 PyLong_AsLongLong(newsizeobj) :
379 PyInt_AsLong(newsizeobj);
380#endif
381 if (PyErr_Occurred())
382 return NULL;
383 } else {
384 /* Default to current position*/
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000385 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000386 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000387 newsize = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388 Py_END_ALLOW_THREADS
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000389 if (newsize == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000390 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000391 clearerr(f->f_fp);
392 return NULL;
393 }
394 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000396 errno = 0;
397 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000399 if (ret != 0) goto onioerror;
400
401#ifdef MS_WIN32
402 /* can use _chsize; if, however, the newsize overflows 32-bits then
403 _chsize is *not* adequate; in this case, an OverflowError is raised */
404 if (newsize > LONG_MAX) {
405 PyErr_SetString(PyExc_OverflowError,
406 "the new size is too long for _chsize (it is limited to 32-bit values)");
Guido van Rossumd7047b31995-01-02 19:07:15 +0000407 return NULL;
Trent Mickf29f47b2000-08-11 19:02:59 +0000408 } else {
409 Py_BEGIN_ALLOW_THREADS
410 errno = 0;
Tim Peters6e13a562001-09-06 00:32:15 +0000411 ret = _chsize(fileno(f->f_fp), (long)newsize);
Trent Mickf29f47b2000-08-11 19:02:59 +0000412 Py_END_ALLOW_THREADS
413 if (ret != 0) goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000414 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000415#else
416 Py_BEGIN_ALLOW_THREADS
417 errno = 0;
418 ret = ftruncate(fileno(f->f_fp), newsize);
419 Py_END_ALLOW_THREADS
420 if (ret != 0) goto onioerror;
421#endif /* !MS_WIN32 */
Tim Peters86821b22001-01-07 21:19:34 +0000422
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000423 Py_INCREF(Py_None);
424 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000425
426onioerror:
427 PyErr_SetFromErrno(PyExc_IOError);
428 clearerr(f->f_fp);
429 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000430}
431#endif /* HAVE_FTRUNCATE */
432
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000434file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000435{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000436 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000437
Guido van Rossumd7297e61992-07-06 14:19:26 +0000438 if (f->f_fp == NULL)
439 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000441 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000442 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000443 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000444 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000446 clearerr(f->f_fp);
447 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000448 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000449#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000450 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000451#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000452 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000453#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000454}
455
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000457file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000458{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000459 if (f->f_fp == NULL)
460 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000462}
463
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000465file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000466{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000467 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000468
Guido van Rossumd7297e61992-07-06 14:19:26 +0000469 if (f->f_fp == NULL)
470 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000472 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000473 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000475 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000477 clearerr(f->f_fp);
478 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000479 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 Py_INCREF(Py_None);
481 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000482}
483
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000485file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000486{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000487 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000488 if (f->f_fp == NULL)
489 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000491 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 Py_END_ALLOW_THREADS
493 return PyInt_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000494}
495
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000496
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000497#if BUFSIZ < 8192
498#define SMALLCHUNK 8192
499#else
500#define SMALLCHUNK BUFSIZ
501#endif
502
Guido van Rossum3c259041999-01-14 19:00:14 +0000503#if SIZEOF_INT < 4
504#define BIGCHUNK (512 * 32)
505#else
506#define BIGCHUNK (512 * 1024)
507#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000508
509static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000510new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000511{
512#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000513 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000514 struct stat st;
515 if (fstat(fileno(f->f_fp), &st) == 0) {
516 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000517 /* The following is not a bug: we really need to call lseek()
518 *and* ftell(). The reason is that some stdio libraries
519 mistakenly flush their buffer when ftell() is called and
520 the lseek() call it makes fails, thereby throwing away
521 data that cannot be recovered in any way. To avoid this,
522 we first test lseek(), and only call ftell() if lseek()
523 works. We can't use the lseek() value either, because we
524 need to take the amount of buffered data into account.
525 (Yet another reason why stdio stinks. :-) */
Jack Jansen2771b5b2001-10-10 22:03:27 +0000526#ifdef USE_GUSI2
527 pos = lseek(fileno(f->f_fp), 1L, SEEK_CUR);
528 pos = lseek(fileno(f->f_fp), -1L, SEEK_CUR);
529#else
Guido van Rossum91aaa921998-05-05 22:21:35 +0000530 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000531#endif
532 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000533 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000534 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000535 if (pos < 0)
536 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000537 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000538 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000539 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000540 }
541#endif
542 if (currentsize > SMALLCHUNK) {
543 /* Keep doubling until we reach BIGCHUNK;
544 then keep adding BIGCHUNK. */
545 if (currentsize <= BIGCHUNK)
546 return currentsize + currentsize;
547 else
548 return currentsize + BIGCHUNK;
549 }
550 return currentsize + SMALLCHUNK;
551}
552
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000554file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000555{
Guido van Rossum789a1611997-05-10 22:33:55 +0000556 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000557 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000559
Guido van Rossumd7297e61992-07-06 14:19:26 +0000560 if (f->f_fp == NULL)
561 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000562 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000563 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000564 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000565 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000566 else
567 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000568 if (buffersize > INT_MAX) {
569 PyErr_SetString(PyExc_OverflowError,
570 "requested number of bytes is more than a Python string can hold");
571 return NULL;
572 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000573 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000574 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000576 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000577 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000578 Py_BEGIN_ALLOW_THREADS
579 errno = 0;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000580 chunksize = fread(BUF(v) + bytesread, 1,
581 buffersize - bytesread, f->f_fp);
Guido van Rossum6263d541997-05-10 22:07:25 +0000582 Py_END_ALLOW_THREADS
583 if (chunksize == 0) {
584 if (!ferror(f->f_fp))
585 break;
586 PyErr_SetFromErrno(PyExc_IOError);
587 clearerr(f->f_fp);
588 Py_DECREF(v);
589 return NULL;
590 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000591 bytesread += chunksize;
592 if (bytesread < buffersize)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000593 break;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000594 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000595 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000596 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000597 return NULL;
598 }
599 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000600 if (bytesread != buffersize)
601 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602 return v;
603}
604
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000605static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000606file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000607{
608 char *ptr;
Trent Mickf29f47b2000-08-11 19:02:59 +0000609 size_t ntodo, ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000610
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000611 if (f->f_fp == NULL)
612 return err_closed();
613 if (!PyArg_Parse(args, "w#", &ptr, &ntodo))
614 return NULL;
615 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000616 while (ntodo > 0) {
617 Py_BEGIN_ALLOW_THREADS
618 errno = 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000619 nnow = fread(ptr+ndone, 1, ntodo, f->f_fp);
Guido van Rossum6263d541997-05-10 22:07:25 +0000620 Py_END_ALLOW_THREADS
621 if (nnow == 0) {
622 if (!ferror(f->f_fp))
623 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000624 PyErr_SetFromErrno(PyExc_IOError);
625 clearerr(f->f_fp);
626 return NULL;
627 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000628 ndone += nnow;
629 ntodo -= nnow;
630 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000631 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000632}
633
Tim Peters86821b22001-01-07 21:19:34 +0000634/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000635Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000636
637Under MSVC 6:
638
Tim Peters1c733232001-01-08 04:02:07 +0000639+ MS threadsafe getc is very slow (multiple layers of function calls before+
640 after each character, to lock+unlock the stream).
641+ The stream-locking functions are MS-internal -- can't access them from user
642 code.
643+ There's nothing Tim could find in the MS C or platform SDK libraries that
644 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000645+ MS fgets locks/unlocks only once per line; it's the only hook we have.
646
647So we use fgets for speed(!), despite that it's painful.
648
649MS realloc is also slow.
650
Tim Petersf29b64d2001-01-15 06:33:19 +0000651Reports from other platforms on this method vs getc_unlocked (which MS doesn't
652have):
653 Linux a wash
654 Solaris a wash
655 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000656
Tim Petersf29b64d2001-01-15 06:33:19 +0000657CAUTION: The C std isn't clear about this: in those cases where fgets
658writes something into the buffer, can it write into any position beyond the
659required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
660known on which it does; and it would be a strange way to code fgets. Still,
661getline_via_fgets may not work correctly if it does. The std test
662test_bufio.py should fail if platform fgets() routinely writes beyond the
663trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000664**************************************************************************/
665
Tim Petersf29b64d2001-01-15 06:33:19 +0000666/* Use this routine if told to, or by default on non-get_unlocked()
667 * platforms unless told not to. Yikes! Let's spell that out:
668 * On a platform with getc_unlocked():
669 * By default, use getc_unlocked().
670 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
671 * On a platform without getc_unlocked():
672 * By default, use fgets().
673 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
674 */
675#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
676#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000677#endif
678
Tim Petersf29b64d2001-01-15 06:33:19 +0000679#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
680#undef USE_FGETS_IN_GETLINE
681#endif
682
683#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000684static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000685getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000686{
Tim Peters15b83852001-01-08 00:53:12 +0000687/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000688 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
689 * to fill this much of the buffer with a known value in order to figure out
690 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
691 * than "most" lines, we waste time filling unused buffer slots. 100 is
692 * surely adequate for most peoples' email archives, chewing over source code,
693 * etc -- "regular old text files".
694 * MAXBUFSIZE is the maximum line length that lets us get away with the less
695 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
696 * cautions about boosting that. 300 was chosen because the worst real-life
697 * text-crunching job reported on Python-Dev was a mail-log crawler where over
698 * half the lines were 254 chars.
699 * INCBUFSIZE is the amount by which we grow the buffer, if MAXBUFSIZE isn't
700 * enough. It doesn't much matter what this is set to: we only get here for
701 * absurdly long lines anyway.
Tim Peters15b83852001-01-08 00:53:12 +0000702 */
Tim Peters142297a2001-01-15 10:36:56 +0000703#define INITBUFSIZE 100
704#define MAXBUFSIZE 300
Tim Peters86821b22001-01-07 21:19:34 +0000705#define INCBUFSIZE 1000
Tim Peters142297a2001-01-15 10:36:56 +0000706 char* p; /* temp */
707 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000708 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000709 char* pvfree; /* address of next free slot */
710 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000711 size_t nfree; /* # of free buffer slots; pvend-pvfree */
712 size_t total_v_size; /* total # of slots in buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000713
Tim Peters15b83852001-01-08 00:53:12 +0000714 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000715 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000716 */
Tim Peters142297a2001-01-15 10:36:56 +0000717 total_v_size = INITBUFSIZE; /* start small and pray */
718 pvfree = buf;
719 for (;;) {
720 Py_BEGIN_ALLOW_THREADS
721 pvend = buf + total_v_size;
722 nfree = pvend - pvfree;
723 memset(pvfree, '\n', nfree);
724 p = fgets(pvfree, nfree, fp);
725 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000726
Tim Peters142297a2001-01-15 10:36:56 +0000727 if (p == NULL) {
728 clearerr(fp);
729 if (PyErr_CheckSignals())
730 return NULL;
731 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000732 return v;
733 }
Tim Peters142297a2001-01-15 10:36:56 +0000734 /* fgets read *something* */
735 p = memchr(pvfree, '\n', nfree);
736 if (p != NULL) {
737 /* Did the \n come from fgets or from us?
738 * Since fgets stops at the first \n, and then writes
739 * \0, if it's from fgets a \0 must be next. But if
740 * that's so, it could not have come from us, since
741 * the \n's we filled the buffer with have only more
742 * \n's to the right.
743 */
744 if (p+1 < pvend && *(p+1) == '\0') {
745 /* It's from fgets: we win! In particular,
746 * we haven't done any mallocs yet, and can
747 * build the final result on the first try.
748 */
749 ++p; /* include \n from fgets */
750 }
751 else {
752 /* Must be from us: fgets didn't fill the
753 * buffer and didn't find a newline, so it
754 * must be the last and newline-free line of
755 * the file.
756 */
757 assert(p > pvfree && *(p-1) == '\0');
758 --p; /* don't include \0 from fgets */
759 }
760 v = PyString_FromStringAndSize(buf, p - buf);
761 return v;
762 }
763 /* yuck: fgets overwrote all the newlines, i.e. the entire
764 * buffer. So this line isn't over yet, or maybe it is but
765 * we're exactly at EOF. If we haven't already, try using the
766 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +0000767 */
Tim Peters142297a2001-01-15 10:36:56 +0000768 assert(*(pvend-1) == '\0');
769 if (pvfree == buf) {
770 pvfree = pvend - 1; /* overwrite trailing null */
771 total_v_size = MAXBUFSIZE;
772 }
773 else
774 break;
Tim Peters86821b22001-01-07 21:19:34 +0000775 }
Tim Peters142297a2001-01-15 10:36:56 +0000776
777 /* The stack buffer isn't big enough; malloc a string object and read
778 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +0000779 */
Tim Peters142297a2001-01-15 10:36:56 +0000780 total_v_size = MAXBUFSIZE + INCBUFSIZE;
Tim Peters1c733232001-01-08 04:02:07 +0000781 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +0000782 if (v == NULL)
783 return v;
784 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +0000785 memcpy(BUF(v), buf, MAXBUFSIZE-1);
786 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +0000787
788 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +0000789 * after setting p one beyond the end of the line. The code here is
790 * very much like the code above, except reads into v's buffer; see
791 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +0000792 */
793 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +0000794 Py_BEGIN_ALLOW_THREADS
795 pvend = BUF(v) + total_v_size;
796 nfree = pvend - pvfree;
797 memset(pvfree, '\n', nfree);
798 p = fgets(pvfree, nfree, fp);
799 Py_END_ALLOW_THREADS
800
801 if (p == NULL) {
802 clearerr(fp);
803 if (PyErr_CheckSignals()) {
804 Py_DECREF(v);
805 return NULL;
806 }
807 p = pvfree;
808 break;
809 }
Tim Peters86821b22001-01-07 21:19:34 +0000810 p = memchr(pvfree, '\n', nfree);
811 if (p != NULL) {
812 if (p+1 < pvend && *(p+1) == '\0') {
813 /* \n came from fgets */
814 ++p;
815 break;
816 }
817 /* \n came from us; last line of file, no newline */
818 assert(p > pvfree && *(p-1) == '\0');
819 --p;
820 break;
821 }
822 /* expand buffer and try again */
823 assert(*(pvend-1) == '\0');
824 total_v_size += INCBUFSIZE;
825 if (total_v_size > INT_MAX) {
826 PyErr_SetString(PyExc_OverflowError,
827 "line is longer than a Python string can hold");
828 Py_DECREF(v);
829 return NULL;
830 }
831 if (_PyString_Resize(&v, (int)total_v_size) < 0)
832 return NULL;
833 /* overwrite the trailing null byte */
834 pvfree = BUF(v) + (total_v_size - INCBUFSIZE - 1);
835 }
836 if (BUF(v) + total_v_size != p)
837 _PyString_Resize(&v, p - BUF(v));
838 return v;
839#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +0000840#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +0000841#undef INCBUFSIZE
842}
Tim Petersf29b64d2001-01-15 06:33:19 +0000843#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000844
Guido van Rossum0bd24411991-04-04 15:21:57 +0000845/* Internal routine to get a line.
846 Size argument interpretation:
847 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +0000848 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +0000849*/
850
Guido van Rossum1187aa42001-01-05 14:43:05 +0000851#ifdef HAVE_GETC_UNLOCKED
852#define GETC(f) getc_unlocked(f)
853#define FLOCKFILE(f) flockfile(f)
854#define FUNLOCKFILE(f) funlockfile(f)
855#else
856#define GETC(f) getc(f)
857#define FLOCKFILE(f)
858#define FUNLOCKFILE(f)
859#endif
860
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000861static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000862get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000863{
Guido van Rossum1187aa42001-01-05 14:43:05 +0000864 FILE *fp = f->f_fp;
865 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +0000866 char *buf, *end;
Trent Mickf29f47b2000-08-11 19:02:59 +0000867 size_t n1, n2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000868 PyObject *v;
Guido van Rossum0bd24411991-04-04 15:21:57 +0000869
Tim Petersf29b64d2001-01-15 06:33:19 +0000870#ifdef USE_FGETS_IN_GETLINE
Guido van Rossum86282062001-01-08 01:26:47 +0000871 if (n <= 0)
Tim Petersf29b64d2001-01-15 06:33:19 +0000872 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +0000873#endif
Guido van Rossum0bd24411991-04-04 15:21:57 +0000874 n2 = n > 0 ? n : 100;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000875 v = PyString_FromStringAndSize((char *)NULL, n2);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000876 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000877 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000878 buf = BUF(v);
879 end = buf + n2;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000880
Guido van Rossumce5ba841991-03-06 13:06:18 +0000881 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +0000882 Py_BEGIN_ALLOW_THREADS
883 FLOCKFILE(fp);
884 while ((c = GETC(fp)) != EOF &&
885 (*buf++ = c) != '\n' &&
886 buf != end)
887 ;
888 FUNLOCKFILE(fp);
889 Py_END_ALLOW_THREADS
890 if (c == '\n')
891 break;
892 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +0000893 if (ferror(fp)) {
894 PyErr_SetFromErrno(PyExc_IOError);
895 clearerr(fp);
896 Py_DECREF(v);
897 return NULL;
898 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +0000899 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000900 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000901 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +0000902 return NULL;
903 }
Guido van Rossumce5ba841991-03-06 13:06:18 +0000904 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +0000905 }
Guido van Rossum1187aa42001-01-05 14:43:05 +0000906 /* Must be because buf == end */
907 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +0000908 break;
Guido van Rossum1187aa42001-01-05 14:43:05 +0000909 n1 = n2;
910 n2 += 1000;
911 if (n2 > INT_MAX) {
912 PyErr_SetString(PyExc_OverflowError,
913 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +0000914 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +0000915 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +0000916 }
Guido van Rossum1187aa42001-01-05 14:43:05 +0000917 if (_PyString_Resize(&v, n2) < 0)
918 return NULL;
919 buf = BUF(v) + n1;
920 end = BUF(v) + n2;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000921 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000922
Guido van Rossumce5ba841991-03-06 13:06:18 +0000923 n1 = buf - BUF(v);
924 if (n1 != n2)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925 _PyString_Resize(&v, n1);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000926 return v;
927}
928
Guido van Rossum0bd24411991-04-04 15:21:57 +0000929/* External C interface */
930
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000931PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000932PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +0000933{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +0000934 PyObject *result;
935
Guido van Rossum3165fe61992-09-25 21:59:05 +0000936 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000937 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +0000938 return NULL;
939 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +0000940
941 if (PyFile_Check(f)) {
942 if (((PyFileObject*)f)->f_fp == NULL)
943 return err_closed();
944 result = get_line((PyFileObject *)f, n);
945 }
946 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000947 PyObject *reader;
948 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +0000949
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000950 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000951 if (reader == NULL)
952 return NULL;
953 if (n <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 args = Py_BuildValue("()");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000955 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000956 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +0000957 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000958 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +0000959 return NULL;
960 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000961 result = PyEval_CallObject(reader, args);
962 Py_DECREF(reader);
963 Py_DECREF(args);
964 if (result != NULL && !PyString_Check(result)) {
965 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +0000966 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000967 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +0000968 "object.readline() returned non-string");
969 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +0000970 }
971
972 if (n < 0 && result != NULL && PyString_Check(result)) {
973 char *s = PyString_AS_STRING(result);
974 int len = PyString_GET_SIZE(result);
975 if (len == 0) {
976 Py_DECREF(result);
977 result = NULL;
978 PyErr_SetString(PyExc_EOFError,
979 "EOF when reading a line");
980 }
981 else if (s[len-1] == '\n') {
982 if (result->ob_refcnt == 1)
983 _PyString_Resize(&result, len-1);
984 else {
985 PyObject *v;
986 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000987 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +0000988 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +0000989 }
990 }
Guido van Rossum3165fe61992-09-25 21:59:05 +0000991 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +0000992 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +0000993}
994
995/* Python method */
996
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000998file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +0000999{
Guido van Rossum789a1611997-05-10 22:33:55 +00001000 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001001
Guido van Rossumd7297e61992-07-06 14:19:26 +00001002 if (f->f_fp == NULL)
1003 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001004 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001005 return NULL;
1006 if (n == 0)
1007 return PyString_FromString("");
1008 if (n < 0)
1009 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001010 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001011}
1012
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001013static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001014file_xreadlines(PyFileObject *f)
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001015{
1016 static PyObject* xreadlines_function = NULL;
Tim Petersf29b64d2001-01-15 06:33:19 +00001017
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001018 if (!xreadlines_function) {
1019 PyObject *xreadlines_module =
1020 PyImport_ImportModule("xreadlines");
1021 if(!xreadlines_module)
1022 return NULL;
1023
1024 xreadlines_function = PyObject_GetAttrString(xreadlines_module,
1025 "xreadlines");
1026 Py_DECREF(xreadlines_module);
1027 if(!xreadlines_function)
1028 return NULL;
1029 }
1030 return PyObject_CallFunction(xreadlines_function, "(O)", f);
1031}
1032
1033static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001034file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001035{
Guido van Rossum789a1611997-05-10 22:33:55 +00001036 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001037 PyObject *list;
1038 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001039 char small_buffer[SMALLCHUNK];
1040 char *buffer = small_buffer;
1041 size_t buffersize = SMALLCHUNK;
1042 PyObject *big_buffer = NULL;
1043 size_t nfilled = 0;
1044 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001045 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001046 char *p, *q, *end;
1047 int err;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001048
Guido van Rossumd7297e61992-07-06 14:19:26 +00001049 if (f->f_fp == NULL)
1050 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001051 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001052 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001053 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001054 return NULL;
1055 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +00001056 Py_BEGIN_ALLOW_THREADS
1057 errno = 0;
1058 nread = fread(buffer+nfilled, 1, buffersize-nfilled, f->f_fp);
1059 Py_END_ALLOW_THREADS
1060 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001061 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001062 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001063 break;
1064 PyErr_SetFromErrno(PyExc_IOError);
1065 clearerr(f->f_fp);
1066 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001067 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001068 list = NULL;
1069 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001070 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001071 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001072 p = memchr(buffer+nfilled, '\n', nread);
1073 if (p == NULL) {
1074 /* Need a larger buffer to fit this line */
1075 nfilled += nread;
1076 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001077 if (buffersize > INT_MAX) {
1078 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001079 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001080 goto error;
1081 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001082 if (big_buffer == NULL) {
1083 /* Create the big buffer */
1084 big_buffer = PyString_FromStringAndSize(
1085 NULL, buffersize);
1086 if (big_buffer == NULL)
1087 goto error;
1088 buffer = PyString_AS_STRING(big_buffer);
1089 memcpy(buffer, small_buffer, nfilled);
1090 }
1091 else {
1092 /* Grow the big buffer */
1093 _PyString_Resize(&big_buffer, buffersize);
1094 buffer = PyString_AS_STRING(big_buffer);
1095 }
1096 continue;
1097 }
1098 end = buffer+nfilled+nread;
1099 q = buffer;
1100 do {
1101 /* Process complete lines */
1102 p++;
1103 line = PyString_FromStringAndSize(q, p-q);
1104 if (line == NULL)
1105 goto error;
1106 err = PyList_Append(list, line);
1107 Py_DECREF(line);
1108 if (err != 0)
1109 goto error;
1110 q = p;
1111 p = memchr(q, '\n', end-q);
1112 } while (p != NULL);
1113 /* Move the remaining incomplete line to the start */
1114 nfilled = end-q;
1115 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001116 if (sizehint > 0)
1117 if (totalread >= (size_t)sizehint)
1118 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001119 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001120 if (nfilled != 0) {
1121 /* Partial last line */
1122 line = PyString_FromStringAndSize(buffer, nfilled);
1123 if (line == NULL)
1124 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001125 if (sizehint > 0) {
1126 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001127 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001128 if (rest == NULL) {
1129 Py_DECREF(line);
1130 goto error;
1131 }
1132 PyString_Concat(&line, rest);
1133 Py_DECREF(rest);
1134 if (line == NULL)
1135 goto error;
1136 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001137 err = PyList_Append(list, line);
1138 Py_DECREF(line);
1139 if (err != 0)
1140 goto error;
1141 }
1142 cleanup:
Guido van Rossum1109fbc1998-04-10 22:16:39 +00001143 if (big_buffer) {
Guido van Rossum6263d541997-05-10 22:07:25 +00001144 Py_DECREF(big_buffer);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00001145 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001146 return list;
1147}
1148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001149static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001150file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001151{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001152 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001153 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001154 if (f->f_fp == NULL)
1155 return err_closed();
Guido van Rossum4c08d552000-03-10 22:55:18 +00001156 if (!PyArg_Parse(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001157 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001158 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001159 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001160 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001161 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001162 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001163 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001164 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001165 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001166 return NULL;
1167 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001168 Py_INCREF(Py_None);
1169 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001170}
1171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001172static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001173file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001174{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001175#define CHUNKSIZE 1000
1176 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001177 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001178 PyObject *result;
1179 int i, j, index, len, nwritten, islist;
1180
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001181 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001182 if (f->f_fp == NULL)
1183 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001184
1185 result = NULL;
1186 list = NULL;
1187 islist = PyList_Check(seq);
1188 if (islist)
1189 it = NULL;
1190 else {
1191 it = PyObject_GetIter(seq);
1192 if (it == NULL) {
1193 PyErr_SetString(PyExc_TypeError,
1194 "writelines() requires an iterable argument");
1195 return NULL;
1196 }
1197 /* From here on, fail by going to error, to reclaim "it". */
1198 list = PyList_New(CHUNKSIZE);
1199 if (list == NULL)
1200 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001201 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001202
1203 /* Strategy: slurp CHUNKSIZE lines into a private list,
1204 checking that they are all strings, then write that list
1205 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001206 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001207 if (islist) {
1208 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001209 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001210 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001211 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001212 j = PyList_GET_SIZE(list);
1213 }
1214 else {
1215 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001216 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001217 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001218 if (PyErr_Occurred())
1219 goto error;
1220 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001221 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001222 PyList_SetItem(list, j, line);
1223 }
1224 }
1225 if (j == 0)
1226 break;
1227
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001228 /* Check that all entries are indeed strings. If not,
1229 apply the same rules as for file.write() and
1230 convert the results to strings. This is slow, but
1231 seems to be the only way since all conversion APIs
1232 could potentially execute Python code. */
1233 for (i = 0; i < j; i++) {
1234 PyObject *v = PyList_GET_ITEM(list, i);
1235 if (!PyString_Check(v)) {
1236 const char *buffer;
1237 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001238 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001239 PyObject_AsReadBuffer(v,
1240 (const void**)&buffer,
1241 &len)) ||
1242 PyObject_AsCharBuffer(v,
1243 &buffer,
1244 &len))) {
1245 PyErr_SetString(PyExc_TypeError,
Fred Drake661ea262000-10-24 19:57:45 +00001246 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001247 goto error;
1248 }
1249 line = PyString_FromStringAndSize(buffer,
1250 len);
1251 if (line == NULL)
1252 goto error;
1253 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001254 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001255 }
1256 }
1257
1258 /* Since we are releasing the global lock, the
1259 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001260 Py_BEGIN_ALLOW_THREADS
1261 f->f_softspace = 0;
1262 errno = 0;
1263 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001264 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001265 len = PyString_GET_SIZE(line);
1266 nwritten = fwrite(PyString_AS_STRING(line),
1267 1, len, f->f_fp);
1268 if (nwritten != len) {
1269 Py_BLOCK_THREADS
1270 PyErr_SetFromErrno(PyExc_IOError);
1271 clearerr(f->f_fp);
1272 goto error;
1273 }
1274 }
1275 Py_END_ALLOW_THREADS
1276
1277 if (j < CHUNKSIZE)
1278 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001279 }
1280
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001281 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001282 result = Py_None;
1283 error:
1284 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001285 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001286 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001287#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001288}
1289
Tim Petersefc3a3a2001-09-20 07:55:22 +00001290static char readline_doc[] =
1291"readline([size]) -> next line from the file, as a string.\n"
1292"\n"
1293"Retain newline. A non-negative size argument limits the maximum\n"
1294"number of bytes to return (an incomplete line may be returned then).\n"
1295"Return an empty string at EOF.";
1296
1297static char read_doc[] =
1298"read([size]) -> read at most size bytes, returned as a string.\n"
1299"\n"
1300"If the size argument is negative or omitted, read until EOF is reached.";
1301
1302static char write_doc[] =
1303"write(str) -> None. Write string str to file.\n"
1304"\n"
1305"Note that due to buffering, flush() or close() may be needed before\n"
1306"the file on disk reflects the data written.";
1307
1308static char fileno_doc[] =
1309"fileno() -> integer \"file descriptor\".\n"
1310"\n"
1311"This is needed for lower-level file interfaces, such os.read().";
1312
1313static char seek_doc[] =
1314"seek(offset[, whence]) -> None. Move to new file position.\n"
1315"\n"
1316"Argument offset is a byte count. Optional argument whence defaults to\n"
1317"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1318"(move relative to current position, positive or negative), and 2 (move\n"
1319"relative to end of file, usually negative, although many platforms allow\n"
1320"seeking beyond the end of a file).\n"
1321"\n"
1322"Note that not all file objects are seekable.";
1323
Guido van Rossumd7047b31995-01-02 19:07:15 +00001324#ifdef HAVE_FTRUNCATE
Tim Petersefc3a3a2001-09-20 07:55:22 +00001325static char truncate_doc[] =
1326"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1327"\n"
1328"Size defaults to the current file position, as returned by tell().";
Guido van Rossumd7047b31995-01-02 19:07:15 +00001329#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001330
1331static char tell_doc[] =
1332"tell() -> current file position, an integer (may be a long integer).";
1333
1334static char readinto_doc[] =
1335"readinto() -> Undocumented. Don't use this; it may go away.";
1336
1337static char readlines_doc[] =
1338"readlines([size]) -> list of strings, each a line from the file.\n"
1339"\n"
1340"Call readline() repeatedly and return a list of the lines so read.\n"
1341"The optional size argument, if given, is an approximate bound on the\n"
1342"total number of bytes in the lines returned.";
1343
1344static char xreadlines_doc[] =
1345"xreadlines() -> next line from the file, as a string.\n"
1346"\n"
1347"Equivalent to xreadlines.xreadlines(file). This is like readline(), but\n"
1348"often quicker, due to reading ahead internally.";
1349
1350static char writelines_doc[] =
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001351"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001352"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001353"Note that newlines are not added. The sequence can be any iterable object\n"
1354"producing strings. This is equivalent to calling write() for each string.";
Tim Petersefc3a3a2001-09-20 07:55:22 +00001355
1356static char flush_doc[] =
1357"flush() -> None. Flush the internal I/O buffer.";
1358
1359static char close_doc[] =
1360"close() -> None or (perhaps) an integer. Close the file.\n"
1361"\n"
1362"Sets data attribute .closed to true. A closed file cannot be used for\n"
1363"further I/O operations. close() may be called more than once without\n"
1364"error. Some kinds of file objects (for example, opened by popen())\n"
1365"may return an exit status upon closing.";
1366
1367static char isatty_doc[] =
1368"isatty() -> true or false. True if the file is connected to a tty device.";
1369
1370static PyMethodDef file_methods[] = {
1371 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1372 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1373 {"write", (PyCFunction)file_write, METH_OLDARGS, write_doc},
1374 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1375 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
1376#ifdef HAVE_FTRUNCATE
1377 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
1378#endif
1379 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1380 {"readinto", (PyCFunction)file_readinto, METH_OLDARGS, readinto_doc},
1381 {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
1382 {"xreadlines", (PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
1383 {"writelines", (PyCFunction)file_writelines, METH_O, writelines_doc},
1384 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1385 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1386 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001387 {NULL, NULL} /* sentinel */
1388};
1389
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001390#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001391
Guido van Rossum6f799372001-09-20 20:46:19 +00001392static PyMemberDef file_memberlist[] = {
1393 {"softspace", T_INT, OFF(f_softspace), 0,
1394 "flag indicating that a space needs to be printed; used by print"},
1395 {"mode", T_OBJECT, OFF(f_mode), RO,
1396 "file mode ('r', 'w', 'a', possibly with 'b' or '+' added)"},
1397 {"name", T_OBJECT, OFF(f_name), RO,
1398 "file name"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001399 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001400 {NULL} /* Sentinel */
1401};
1402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001403static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001405{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406 return PyInt_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001407}
1408
Guido van Rossum32d34c82001-09-20 21:45:26 +00001409static PyGetSetDef file_getsetlist[] = {
1410 {"closed", (getter)get_closed, NULL, "flag set if the file is closed"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001411 {0},
1412};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001413
Guido van Rossum65967252001-04-21 13:20:18 +00001414static PyObject *
Guido van Rossum5b021842001-05-22 16:48:37 +00001415file_getiter(PyObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001416{
Guido van Rossum5b021842001-05-22 16:48:37 +00001417 return PyObject_CallMethod(f, "xreadlines", "");
Guido van Rossum65967252001-04-21 13:20:18 +00001418}
1419
Tim Peters59c9a642001-09-13 05:38:56 +00001420static PyObject *
1421file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1422{
Tim Peters44410012001-09-14 03:26:08 +00001423 PyObject *self;
1424 static PyObject *not_yet_string;
1425
1426 assert(type != NULL && type->tp_alloc != NULL);
1427
1428 if (not_yet_string == NULL) {
1429 not_yet_string = PyString_FromString("<uninitialized file>");
1430 if (not_yet_string == NULL)
1431 return NULL;
1432 }
1433
1434 self = type->tp_alloc(type, 0);
1435 if (self != NULL) {
1436 /* Always fill in the name and mode, so that nobody else
1437 needs to special-case NULLs there. */
1438 Py_INCREF(not_yet_string);
1439 ((PyFileObject *)self)->f_name = not_yet_string;
1440 Py_INCREF(not_yet_string);
1441 ((PyFileObject *)self)->f_mode = not_yet_string;
1442 }
1443 return self;
1444}
1445
1446static int
1447file_init(PyObject *self, PyObject *args, PyObject *kwds)
1448{
1449 PyFileObject *foself = (PyFileObject *)self;
1450 int ret = 0;
Tim Peters59c9a642001-09-13 05:38:56 +00001451 static char *kwlist[] = {"name", "mode", "buffering", 0};
1452 char *name = NULL;
1453 char *mode = "r";
1454 int bufsize = -1;
Tim Peters44410012001-09-14 03:26:08 +00001455
1456 assert(PyFile_Check(self));
1457 if (foself->f_fp != NULL) {
1458 /* Have to close the existing file first. */
1459 PyObject *closeresult = file_close(foself);
1460 if (closeresult == NULL)
1461 return -1;
1462 Py_DECREF(closeresult);
1463 }
Tim Peters59c9a642001-09-13 05:38:56 +00001464
1465 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1466 Py_FileSystemDefaultEncoding, &name,
1467 &mode, &bufsize))
Tim Peters44410012001-09-14 03:26:08 +00001468 return -1;
1469 if (fill_file_fields(foself, NULL, name, mode, fclose) == NULL)
1470 goto Error;
1471 if (open_the_file(foself, name, mode) == NULL)
1472 goto Error;
1473 PyFile_SetBufSize(self, bufsize);
1474 goto Done;
1475
1476Error:
1477 ret = -1;
1478 /* fall through */
1479Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001480 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001481 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001482}
1483
Tim Peters59c9a642001-09-13 05:38:56 +00001484static char file_doc[] =
1485"file(name[, mode[, buffering]]) -> file object\n"
1486"\n"
1487"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1488"writing or appending. The file will be created if it doesn't exist\n"
1489"when opened for writing or appending; it will be truncated when\n"
1490"opened for writing. Add a 'b' to the mode for binary files.\n"
1491"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1492"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001493"buffered, and larger numbers specify the buffer size.\n"
1494"Note: open() is an alias for file().\n";
Tim Peters59c9a642001-09-13 05:38:56 +00001495
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001496PyTypeObject PyFile_Type = {
1497 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001498 0,
1499 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001500 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001501 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001502 (destructor)file_dealloc, /* tp_dealloc */
1503 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504 0, /* tp_getattr */
1505 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001506 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001508 0, /* tp_as_number */
1509 0, /* tp_as_sequence */
1510 0, /* tp_as_mapping */
1511 0, /* tp_hash */
1512 0, /* tp_call */
1513 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65967252001-04-21 13:20:18 +00001515 0, /* tp_setattro */
1516 0, /* tp_as_buffer */
Guido van Rossum9475a232001-10-05 20:51:39 +00001517 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00001518 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 0, /* tp_traverse */
1520 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00001521 0, /* tp_richcompare */
1522 0, /* tp_weaklistoffset */
Guido van Rossum5b021842001-05-22 16:48:37 +00001523 file_getiter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001524 0, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525 file_methods, /* tp_methods */
1526 file_memberlist, /* tp_members */
1527 file_getsetlist, /* tp_getset */
1528 0, /* tp_base */
1529 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00001530 0, /* tp_descr_get */
1531 0, /* tp_descr_set */
1532 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00001533 (initproc)file_init, /* tp_init */
1534 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00001535 file_new, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001536 _PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001537};
Guido van Rossumeb183da1991-04-04 10:44:06 +00001538
1539/* Interface for the 'soft space' between print items. */
1540
1541int
Fred Drakefd99de62000-07-09 05:02:18 +00001542PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00001543{
1544 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001545 if (f == NULL) {
1546 /* Do nothing */
1547 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001548 else if (PyFile_Check(f)) {
1549 oldflag = ((PyFileObject *)f)->f_softspace;
1550 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001551 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001552 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001553 PyObject *v;
1554 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001555 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001556 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00001557 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001558 if (PyInt_Check(v))
1559 oldflag = PyInt_AsLong(v);
1560 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001561 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001562 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001563 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001564 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00001565 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001566 if (PyObject_SetAttrString(f, "softspace", v) != 0)
1567 PyErr_Clear();
1568 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001569 }
1570 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00001571 return oldflag;
1572}
Guido van Rossum3165fe61992-09-25 21:59:05 +00001573
1574/* Interfaces to write objects/strings to file-like objects */
1575
1576int
Fred Drakefd99de62000-07-09 05:02:18 +00001577PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00001578{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001579 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001580 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001581 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001582 return -1;
1583 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001584 else if (PyFile_Check(f)) {
1585 FILE *fp = PyFile_AsFile(f);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001586 if (fp == NULL) {
1587 err_closed();
1588 return -1;
1589 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001590 return PyObject_Print(v, fp, flags);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001591 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001592 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001593 if (writer == NULL)
1594 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00001595 if (flags & Py_PRINT_RAW) {
1596 if (PyUnicode_Check(v)) {
1597 value = v;
1598 Py_INCREF(value);
1599 } else
1600 value = PyObject_Str(v);
1601 }
1602 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001603 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00001604 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001605 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00001606 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001607 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001608 args = Py_BuildValue("(O)", value);
Guido van Rossume9eec541997-05-22 14:02:25 +00001609 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001610 Py_DECREF(value);
1611 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00001612 return -1;
1613 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001614 result = PyEval_CallObject(writer, args);
1615 Py_DECREF(args);
1616 Py_DECREF(value);
1617 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001618 if (result == NULL)
1619 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001620 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001621 return 0;
1622}
1623
Guido van Rossum27a60b11997-05-22 22:25:11 +00001624int
Fred Drakefd99de62000-07-09 05:02:18 +00001625PyFile_WriteString(char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00001626{
1627 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00001628 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00001629 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00001630 PyErr_SetString(PyExc_SystemError,
1631 "null file for PyFile_WriteString");
1632 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001633 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001634 else if (PyFile_Check(f)) {
1635 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00001636 if (fp == NULL) {
1637 err_closed();
1638 return -1;
1639 }
1640 fputs(s, fp);
1641 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001642 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001643 else if (!PyErr_Occurred()) {
1644 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00001645 int err;
1646 if (v == NULL)
1647 return -1;
1648 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
1649 Py_DECREF(v);
1650 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001651 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00001652 else
1653 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001654}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00001655
1656/* Try to get a file-descriptor from a Python object. If the object
1657 is an integer or long integer, its value is returned. If not, the
1658 object's fileno() method is called if it exists; the method must return
1659 an integer or long integer, which is returned as the file descriptor value.
1660 -1 is returned on failure.
1661*/
1662
1663int PyObject_AsFileDescriptor(PyObject *o)
1664{
1665 int fd;
1666 PyObject *meth;
1667
1668 if (PyInt_Check(o)) {
1669 fd = PyInt_AsLong(o);
1670 }
1671 else if (PyLong_Check(o)) {
1672 fd = PyLong_AsLong(o);
1673 }
1674 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
1675 {
1676 PyObject *fno = PyEval_CallObject(meth, NULL);
1677 Py_DECREF(meth);
1678 if (fno == NULL)
1679 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00001680
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00001681 if (PyInt_Check(fno)) {
1682 fd = PyInt_AsLong(fno);
1683 Py_DECREF(fno);
1684 }
1685 else if (PyLong_Check(fno)) {
1686 fd = PyLong_AsLong(fno);
1687 Py_DECREF(fno);
1688 }
1689 else {
1690 PyErr_SetString(PyExc_TypeError,
1691 "fileno() returned a non-integer");
1692 Py_DECREF(fno);
1693 return -1;
1694 }
1695 }
1696 else {
1697 PyErr_SetString(PyExc_TypeError,
1698 "argument must be an int, or have a fileno() method.");
1699 return -1;
1700 }
1701
1702 if (fd < 0) {
1703 PyErr_Format(PyExc_ValueError,
1704 "file descriptor cannot be a negative integer (%i)",
1705 fd);
1706 return -1;
1707 }
1708 return fd;
1709}