blob: ebf0d40d4200221d52b1ef852e6f1aa64568f471 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossumff7e83d1999-08-27 20:39:37 +00006#ifndef DONT_HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00007#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +00008#endif /* DONT_HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +00009
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000010#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000011#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000012/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000013#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000014#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000015#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000016#endif
17
Mark Hammondc2e85bd2002-10-03 05:10:39 +000018#ifdef _MSC_VER
19/* Need GetVersion to see if on NT so safe to use _wfopen */
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22#endif /* _MSC_VER */
23
Guido van Rossumf2044e11998-04-28 16:05:59 +000024#ifdef macintosh
25#ifdef USE_GUSI
26#define HAVE_FTRUNCATE
27#endif
28#endif
29
Jack Jansene08dea191995-04-23 22:12:47 +000030#ifdef __MWERKS__
31/* Mwerks fopen() doesn't always set errno */
32#define NO_FOPEN_ERRNO
33#endif
Guido van Rossum295d1711995-02-19 15:55:19 +000034
Andrew MacIntyrec4874392002-02-26 11:36:35 +000035#if defined(PYOS_OS2) && defined(PYCC_GCC)
36#include <io.h>
37#endif
38
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000040
Guido van Rossumff7e83d1999-08-27 20:39:37 +000041#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000042#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000043#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
Jack Jansen7b8c7542002-04-14 20:12:41 +000045#ifdef HAVE_GETC_UNLOCKED
46#define GETC(f) getc_unlocked(f)
47#define FLOCKFILE(f) flockfile(f)
48#define FUNLOCKFILE(f) funlockfile(f)
49#else
50#define GETC(f) getc(f)
51#define FLOCKFILE(f)
52#define FUNLOCKFILE(f)
53#endif
54
55#ifdef WITH_UNIVERSAL_NEWLINES
56/* Bits in f_newlinetypes */
57#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
58#define NEWLINE_CR 1 /* \r newline seen */
59#define NEWLINE_LF 2 /* \n newline seen */
60#define NEWLINE_CRLF 4 /* \r\n newline seen */
61#endif
Trent Mickf29f47b2000-08-11 19:02:59 +000062
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000064PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000068 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000069 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070}
71
Guido van Rossumc0b618a1997-05-02 03:12:38 +000072PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000073PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000074{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000076 return NULL;
77 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000078 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000079}
80
Neil Schemenauered19b882002-03-23 02:06:50 +000081/* On Unix, fopen will succeed for directories.
82 In Python, there should be no file objects referring to
83 directories, so we need a check. */
84
85static PyFileObject*
86dircheck(PyFileObject* f)
87{
88#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
89 struct stat buf;
90 if (f->f_fp == NULL)
91 return f;
92 if (fstat(fileno(f->f_fp), &buf) == 0 &&
93 S_ISDIR(buf.st_mode)) {
94#ifdef HAVE_STRERROR
95 char *msg = strerror(EISDIR);
96#else
97 char *msg = "Is a directory";
98#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +000099 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
100 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +0000101 PyErr_SetObject(PyExc_IOError, exc);
102 return NULL;
103 }
104#endif
105 return f;
106}
107
Tim Peters59c9a642001-09-13 05:38:56 +0000108
109static PyObject *
110fill_file_fields(PyFileObject *f, FILE *fp, char *name, char *mode,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000111 int (*close)(FILE *), PyObject *wname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000112{
Tim Peters59c9a642001-09-13 05:38:56 +0000113 assert(f != NULL);
114 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000115 assert(f->f_fp == NULL);
116
117 Py_DECREF(f->f_name);
118 Py_DECREF(f->f_mode);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000119 if (wname)
120 f->f_name = PyUnicode_FromObject(wname);
121 else
122 f->f_name = PyString_FromString(name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000124
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000125 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000126 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000127 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000128 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000129#ifdef WITH_UNIVERSAL_NEWLINES
130 f->f_univ_newline = (strchr(mode, 'U') != NULL);
131 f->f_newlinetypes = NEWLINE_UNKNOWN;
132 f->f_skipnextlf = 0;
133#endif
Tim Peters44410012001-09-14 03:26:08 +0000134
Tim Peters59c9a642001-09-13 05:38:56 +0000135 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000138 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140}
141
Tim Peters59c9a642001-09-13 05:38:56 +0000142static PyObject *
143open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Tim Peters59c9a642001-09-13 05:38:56 +0000145 assert(f != NULL);
146 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000147#ifdef MS_WINDOWS
148 /* windows ignores the passed name in order to support Unicode */
149 assert(f->f_name != NULL);
150#else
Tim Peters59c9a642001-09-13 05:38:56 +0000151 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000152#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000153 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000154 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000155
Tim Peters8fa45672001-09-13 21:01:29 +0000156 /* rexec.py can't stop a user from getting the file() constructor --
157 all they have to do is get *any* file object f, and then do
158 type(f). Here we prevent them from doing damage with it. */
159 if (PyEval_GetRestricted()) {
160 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000161 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000162 return NULL;
163 }
Tim Petersa27a1502001-11-09 20:59:14 +0000164 errno = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000165#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000166 if (*mode == '*') {
167 FILE *fopenRF();
168 f->f_fp = fopenRF(name, mode+1);
169 }
170 else
171#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000172 {
Jack Jansen7b8c7542002-04-14 20:12:41 +0000173#ifdef WITH_UNIVERSAL_NEWLINES
174 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
175 mode = "rb";
176#else
177 /* Compatibility: specifying U in a Python without universal
178 ** newlines is allowed, and the file is opened as a normal text
179 ** file.
180 */
181 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
182 mode = "r";
183#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000184#ifdef MS_WINDOWS
185 if (PyUnicode_Check(f->f_name)) {
186 PyObject *wmode;
187 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
188 if (f->f_name && wmode) {
189 Py_BEGIN_ALLOW_THREADS
190 /* PyUnicode_AS_UNICODE OK without thread
191 lock as it is a simple dereference. */
192 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
193 PyUnicode_AS_UNICODE(wmode));
194 Py_END_ALLOW_THREADS
195 }
196 Py_XDECREF(wmode);
197 }
198#endif
199 if (NULL == f->f_fp && NULL != name) {
200 Py_BEGIN_ALLOW_THREADS
201 f->f_fp = fopen(name, mode);
202 Py_END_ALLOW_THREADS
203 }
Guido van Rossumff4949e1992-08-05 19:58:53 +0000204 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000205 if (f->f_fp == NULL) {
Jack Jansene08dea191995-04-23 22:12:47 +0000206#ifdef NO_FOPEN_ERRNO
Jack Jansenb3be2162001-11-30 14:16:36 +0000207 /* Metroworks only, wich does not always sets errno */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000208 if (errno == 0) {
Jack Jansenb3be2162001-11-30 14:16:36 +0000209 PyObject *v;
210 v = Py_BuildValue("(is)", 0, "Cannot open file");
211 if (v != NULL) {
212 PyErr_SetObject(PyExc_IOError, v);
213 Py_DECREF(v);
214 }
Jack Jansene08dea191995-04-23 22:12:47 +0000215 return NULL;
216 }
217#endif
Tim Peters2ea91112002-04-08 04:13:12 +0000218#ifdef _MSC_VER
219 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
220 * across all Windows flavors. When it sets EINVAL varies
221 * across Windows flavors, the exact conditions aren't
222 * documented, and the answer lies in the OS's implementation
223 * of Win32's CreateFile function (whose source is secret).
224 * Seems the best we can do is map EINVAL to ENOENT.
225 */
226 if (errno == 0) /* bad mode string */
227 errno = EINVAL;
228 else if (errno == EINVAL) /* unknown, but not a mode string */
229 errno = ENOENT;
230#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000231 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000232 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000233 mode);
234 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000235#ifdef MS_WINDOWS
236 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
237#else
Jeremy Hylton41c83212001-11-09 16:17:24 +0000238 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000239#endif /* MS_WINDOWS */
Tim Peters59c9a642001-09-13 05:38:56 +0000240 f = NULL;
241 }
Tim Peters2ea91112002-04-08 04:13:12 +0000242 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000243 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000244 return (PyObject *)f;
245}
246
247PyObject *
248PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
249{
Tim Peters44410012001-09-14 03:26:08 +0000250 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
251 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000252 if (f != NULL) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000253 if (fill_file_fields(f, fp, name, mode, close, NULL) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000254 Py_DECREF(f);
255 f = NULL;
256 }
257 }
258 return (PyObject *) f;
259}
260
261PyObject *
262PyFile_FromString(char *name, char *mode)
263{
264 extern int fclose(FILE *);
265 PyFileObject *f;
266
267 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
268 if (f != NULL) {
269 if (open_the_file(f, name, mode) == NULL) {
270 Py_DECREF(f);
271 f = NULL;
272 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000273 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275}
276
Guido van Rossumb6775db1994-08-01 11:34:53 +0000277void
Fred Drakefd99de62000-07-09 05:02:18 +0000278PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000279{
280 if (bufsize >= 0) {
281#ifdef HAVE_SETVBUF
282 int type;
283 switch (bufsize) {
284 case 0:
285 type = _IONBF;
286 break;
287 case 1:
288 type = _IOLBF;
289 bufsize = BUFSIZ;
290 break;
291 default:
292 type = _IOFBF;
293 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
295 type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000296#else /* !HAVE_SETVBUF */
297 if (bufsize <= 1)
298 setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
299#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300 }
301}
302
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000304err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000305{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000307 return NULL;
308}
309
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000310static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000311
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312/* Methods */
313
314static void
Fred Drakefd99de62000-07-09 05:02:18 +0000315file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000317 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000318 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000319 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000321 }
Tim Peters44410012001-09-14 03:26:08 +0000322 Py_XDECREF(f->f_name);
323 Py_XDECREF(f->f_mode);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000324 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000325 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326}
327
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000329file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000330{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000331 if (PyUnicode_Check(f->f_name)) {
332 PyObject *ret = NULL;
333 PyObject *name;
334 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
335 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
336 f->f_fp == NULL ? "closed" : "open",
337 PyString_AsString(name),
338 PyString_AsString(f->f_mode),
339 f);
340 Py_XDECREF(name);
341 return ret;
342 } else {
343 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000344 f->f_fp == NULL ? "closed" : "open",
345 PyString_AsString(f->f_name),
346 PyString_AsString(f->f_mode),
347 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000348 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349}
350
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000352file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000354 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000356 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000357 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000358 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000359 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000361 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362 f->f_fp = NULL;
363 }
Guido van Rossumfebd5511992-03-04 16:39:24 +0000364 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000366 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 return PyInt_FromLong((long)sts);
368 Py_INCREF(Py_None);
369 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370}
371
Trent Mickf29f47b2000-08-11 19:02:59 +0000372
Guido van Rossumb8552162001-09-05 14:58:11 +0000373/* Our very own off_t-like type, 64-bit if possible */
374#if !defined(HAVE_LARGEFILE_SUPPORT)
375typedef off_t Py_off_t;
376#elif SIZEOF_OFF_T >= 8
377typedef off_t Py_off_t;
378#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000379typedef fpos_t Py_off_t;
380#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000381#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000382#endif
383
384
Trent Mickf29f47b2000-08-11 19:02:59 +0000385/* a portable fseek() function
386 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000387static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000388_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000389{
Guido van Rossumb8552162001-09-05 14:58:11 +0000390#if !defined(HAVE_LARGEFILE_SUPPORT)
391 return fseek(fp, offset, whence);
392#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000393 return fseeko(fp, offset, whence);
394#elif defined(HAVE_FSEEK64)
395 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000396#elif defined(__BEOS__)
397 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000398#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000399 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
400 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000401 fpos_t pos;
402 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000403 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000404#ifdef MS_WINDOWS
405 fflush(fp);
406 if (_lseeki64(fileno(fp), 0, 2) == -1)
407 return -1;
408#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000409 if (fseek(fp, 0, SEEK_END) != 0)
410 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000411#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000412 /* fall through */
413 case SEEK_CUR:
414 if (fgetpos(fp, &pos) != 0)
415 return -1;
416 offset += pos;
417 break;
418 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000419 }
420 return fsetpos(fp, &offset);
421#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000422#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000423#endif
424}
425
426
427/* a portable ftell() function
428 Return -1 on failure with errno set appropriately, current file
429 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000430static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000431_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000432{
Guido van Rossumb8552162001-09-05 14:58:11 +0000433#if !defined(HAVE_LARGEFILE_SUPPORT)
434 return ftell(fp);
435#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
436 return ftello(fp);
437#elif defined(HAVE_FTELL64)
438 return ftell64(fp);
439#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000440 fpos_t pos;
441 if (fgetpos(fp, &pos) != 0)
442 return -1;
443 return pos;
444#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000445#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000446#endif
447}
448
449
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000451file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000453 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000454 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000455 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000456 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000457
Guido van Rossumd7297e61992-07-06 14:19:26 +0000458 if (f->f_fp == NULL)
459 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000460 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000461 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000462 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000463 return NULL;
464#if !defined(HAVE_LARGEFILE_SUPPORT)
465 offset = PyInt_AsLong(offobj);
466#else
467 offset = PyLong_Check(offobj) ?
468 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
469#endif
470 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000471 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000472
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000474 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000475 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000477
Guido van Rossumff4949e1992-08-05 19:58:53 +0000478 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000480 clearerr(f->f_fp);
481 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000482 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000483#ifdef WITH_UNIVERSAL_NEWLINES
484 f->f_skipnextlf = 0;
485#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 Py_INCREF(Py_None);
487 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000488}
489
Trent Mickf29f47b2000-08-11 19:02:59 +0000490
Guido van Rossumd7047b31995-01-02 19:07:15 +0000491#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000493file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000494{
Guido van Rossumd7047b31995-01-02 19:07:15 +0000495 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000496 Py_off_t newsize;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000497 PyObject *newsizeobj;
Tim Peters86821b22001-01-07 21:19:34 +0000498
Guido van Rossumd7047b31995-01-02 19:07:15 +0000499 if (f->f_fp == NULL)
500 return err_closed();
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000501 newsizeobj = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +0000502 if (!PyArg_ParseTuple(args, "|O:truncate", &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000503 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000504
505 /* Set newsize to current postion if newsizeobj NULL, else to the
506 specified value. */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000507 if (newsizeobj != NULL) {
508#if !defined(HAVE_LARGEFILE_SUPPORT)
509 newsize = PyInt_AsLong(newsizeobj);
510#else
511 newsize = PyLong_Check(newsizeobj) ?
512 PyLong_AsLongLong(newsizeobj) :
513 PyInt_AsLong(newsizeobj);
514#endif
515 if (PyErr_Occurred())
516 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000517 }
518 else {
519 /* Default to current position. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000520 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000521 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000522 newsize = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000524 if (newsize == -1)
525 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000526 }
Tim Petersfb05db22002-03-11 00:24:00 +0000527
528 /* Flush the file. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000529 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000530 errno = 0;
531 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000533 if (ret != 0)
534 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000535
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000536#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000537 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000538 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000539 {
Tim Peters8f01b682002-03-12 03:04:44 +0000540 Py_off_t current; /* current file position */
Tim Petersfb05db22002-03-11 00:24:00 +0000541 HANDLE hFile;
542 int error;
543
Tim Peters8f01b682002-03-12 03:04:44 +0000544 /* current <- current file postion. */
545 if (newsizeobj == NULL)
546 current = newsize;
547 else {
Tim Petersfb05db22002-03-11 00:24:00 +0000548 Py_BEGIN_ALLOW_THREADS
549 errno = 0;
Tim Peters8f01b682002-03-12 03:04:44 +0000550 current = _portable_ftell(f->f_fp);
551 Py_END_ALLOW_THREADS
552 if (current == -1)
553 goto onioerror;
554 }
555
556 /* Move to newsize. */
557 if (current != newsize) {
558 Py_BEGIN_ALLOW_THREADS
559 errno = 0;
560 error = _portable_fseek(f->f_fp, newsize, SEEK_SET)
561 != 0;
Tim Petersfb05db22002-03-11 00:24:00 +0000562 Py_END_ALLOW_THREADS
563 if (error)
564 goto onioerror;
565 }
566
Tim Peters8f01b682002-03-12 03:04:44 +0000567 /* Truncate. Note that this may grow the file! */
568 Py_BEGIN_ALLOW_THREADS
569 errno = 0;
570 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
571 error = hFile == (HANDLE)-1;
572 if (!error) {
573 error = SetEndOfFile(hFile) == 0;
574 if (error)
575 errno = EACCES;
576 }
577 Py_END_ALLOW_THREADS
578 if (error)
579 goto onioerror;
580
581 /* Restore original file position. */
582 if (current != newsize) {
583 Py_BEGIN_ALLOW_THREADS
584 errno = 0;
585 error = _portable_fseek(f->f_fp, current, SEEK_SET)
586 != 0;
587 Py_END_ALLOW_THREADS
588 if (error)
589 goto onioerror;
590 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000591 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000592#else
593 Py_BEGIN_ALLOW_THREADS
594 errno = 0;
595 ret = ftruncate(fileno(f->f_fp), newsize);
596 Py_END_ALLOW_THREADS
597 if (ret != 0) goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000598#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000599
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000600 Py_INCREF(Py_None);
601 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000602
603onioerror:
604 PyErr_SetFromErrno(PyExc_IOError);
605 clearerr(f->f_fp);
606 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000607}
608#endif /* HAVE_FTRUNCATE */
609
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000611file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000612{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000613 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000614
Guido van Rossumd7297e61992-07-06 14:19:26 +0000615 if (f->f_fp == NULL)
616 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000617 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000618 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000619 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000620 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000621 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000622 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000623 clearerr(f->f_fp);
624 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000625 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000626#ifdef WITH_UNIVERSAL_NEWLINES
627 if (f->f_skipnextlf) {
628 int c;
629 c = GETC(f->f_fp);
630 if (c == '\n') {
631 pos++;
632 f->f_skipnextlf = 0;
633 } else if (c != EOF) ungetc(c, f->f_fp);
634 }
635#endif
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000636#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000637 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000638#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000639 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000640#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000641}
642
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000644file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000645{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000646 if (f->f_fp == NULL)
647 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000648 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000649}
650
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000651static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000652file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000653{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000654 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000655
Guido van Rossumd7297e61992-07-06 14:19:26 +0000656 if (f->f_fp == NULL)
657 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000658 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000659 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000660 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000661 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000662 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000664 clearerr(f->f_fp);
665 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000666 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 Py_INCREF(Py_None);
668 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000669}
670
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000672file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000673{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000674 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000675 if (f->f_fp == NULL)
676 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000678 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000680 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000681}
682
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000683
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000684#if BUFSIZ < 8192
685#define SMALLCHUNK 8192
686#else
687#define SMALLCHUNK BUFSIZ
688#endif
689
Guido van Rossum3c259041999-01-14 19:00:14 +0000690#if SIZEOF_INT < 4
691#define BIGCHUNK (512 * 32)
692#else
693#define BIGCHUNK (512 * 1024)
694#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000695
696static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000697new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000698{
699#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000700 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000701 struct stat st;
702 if (fstat(fileno(f->f_fp), &st) == 0) {
703 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000704 /* The following is not a bug: we really need to call lseek()
705 *and* ftell(). The reason is that some stdio libraries
706 mistakenly flush their buffer when ftell() is called and
707 the lseek() call it makes fails, thereby throwing away
708 data that cannot be recovered in any way. To avoid this,
709 we first test lseek(), and only call ftell() if lseek()
710 works. We can't use the lseek() value either, because we
711 need to take the amount of buffered data into account.
712 (Yet another reason why stdio stinks. :-) */
Jack Jansen2771b5b2001-10-10 22:03:27 +0000713#ifdef USE_GUSI2
714 pos = lseek(fileno(f->f_fp), 1L, SEEK_CUR);
715 pos = lseek(fileno(f->f_fp), -1L, SEEK_CUR);
716#else
Guido van Rossum91aaa921998-05-05 22:21:35 +0000717 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000718#endif
719 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000720 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000721 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000722 if (pos < 0)
723 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000724 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000725 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000726 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000727 }
728#endif
729 if (currentsize > SMALLCHUNK) {
730 /* Keep doubling until we reach BIGCHUNK;
731 then keep adding BIGCHUNK. */
732 if (currentsize <= BIGCHUNK)
733 return currentsize + currentsize;
734 else
735 return currentsize + BIGCHUNK;
736 }
737 return currentsize + SMALLCHUNK;
738}
739
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000741file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000742{
Guido van Rossum789a1611997-05-10 22:33:55 +0000743 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000744 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000745 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000746
Guido van Rossumd7297e61992-07-06 14:19:26 +0000747 if (f->f_fp == NULL)
748 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000749 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000750 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000751 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000752 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000753 else
754 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000755 if (buffersize > INT_MAX) {
756 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000757 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000758 return NULL;
759 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000760 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000761 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000762 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000763 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000764 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000765 Py_BEGIN_ALLOW_THREADS
766 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000767 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000768 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000769 Py_END_ALLOW_THREADS
770 if (chunksize == 0) {
771 if (!ferror(f->f_fp))
772 break;
773 PyErr_SetFromErrno(PyExc_IOError);
774 clearerr(f->f_fp);
775 Py_DECREF(v);
776 return NULL;
777 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000778 bytesread += chunksize;
779 if (bytesread < buffersize)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000780 break;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000781 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000782 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000783 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000784 return NULL;
785 }
786 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000787 if (bytesread != buffersize)
788 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000789 return v;
790}
791
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000792static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000793file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000794{
795 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000796 int ntodo;
797 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000798
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000799 if (f->f_fp == NULL)
800 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000801 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000802 return NULL;
803 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000804 while (ntodo > 0) {
805 Py_BEGIN_ALLOW_THREADS
806 errno = 0;
Jeremy Hylton8b735422002-08-14 21:01:41 +0000807 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
808 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000809 Py_END_ALLOW_THREADS
810 if (nnow == 0) {
811 if (!ferror(f->f_fp))
812 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000813 PyErr_SetFromErrno(PyExc_IOError);
814 clearerr(f->f_fp);
815 return NULL;
816 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000817 ndone += nnow;
818 ntodo -= nnow;
819 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000820 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000821}
822
Tim Peters86821b22001-01-07 21:19:34 +0000823/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000824Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000825
826Under MSVC 6:
827
Tim Peters1c733232001-01-08 04:02:07 +0000828+ MS threadsafe getc is very slow (multiple layers of function calls before+
829 after each character, to lock+unlock the stream).
830+ The stream-locking functions are MS-internal -- can't access them from user
831 code.
832+ There's nothing Tim could find in the MS C or platform SDK libraries that
833 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000834+ MS fgets locks/unlocks only once per line; it's the only hook we have.
835
836So we use fgets for speed(!), despite that it's painful.
837
838MS realloc is also slow.
839
Tim Petersf29b64d2001-01-15 06:33:19 +0000840Reports from other platforms on this method vs getc_unlocked (which MS doesn't
841have):
842 Linux a wash
843 Solaris a wash
844 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000845
Tim Petersf29b64d2001-01-15 06:33:19 +0000846CAUTION: The C std isn't clear about this: in those cases where fgets
847writes something into the buffer, can it write into any position beyond the
848required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
849known on which it does; and it would be a strange way to code fgets. Still,
850getline_via_fgets may not work correctly if it does. The std test
851test_bufio.py should fail if platform fgets() routinely writes beyond the
852trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000853**************************************************************************/
854
Tim Petersf29b64d2001-01-15 06:33:19 +0000855/* Use this routine if told to, or by default on non-get_unlocked()
856 * platforms unless told not to. Yikes! Let's spell that out:
857 * On a platform with getc_unlocked():
858 * By default, use getc_unlocked().
859 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
860 * On a platform without getc_unlocked():
861 * By default, use fgets().
862 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
863 */
864#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
865#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000866#endif
867
Tim Petersf29b64d2001-01-15 06:33:19 +0000868#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
869#undef USE_FGETS_IN_GETLINE
870#endif
871
872#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000873static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000874getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000875{
Tim Peters15b83852001-01-08 00:53:12 +0000876/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000877 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
878 * to fill this much of the buffer with a known value in order to figure out
879 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
880 * than "most" lines, we waste time filling unused buffer slots. 100 is
881 * surely adequate for most peoples' email archives, chewing over source code,
882 * etc -- "regular old text files".
883 * MAXBUFSIZE is the maximum line length that lets us get away with the less
884 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
885 * cautions about boosting that. 300 was chosen because the worst real-life
886 * text-crunching job reported on Python-Dev was a mail-log crawler where over
887 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000888 */
Tim Peters142297a2001-01-15 10:36:56 +0000889#define INITBUFSIZE 100
890#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000891 char* p; /* temp */
892 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000893 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000894 char* pvfree; /* address of next free slot */
895 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000896 size_t nfree; /* # of free buffer slots; pvend-pvfree */
897 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000898 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000899
Tim Peters15b83852001-01-08 00:53:12 +0000900 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000901 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000902 */
Tim Peters142297a2001-01-15 10:36:56 +0000903 total_v_size = INITBUFSIZE; /* start small and pray */
904 pvfree = buf;
905 for (;;) {
906 Py_BEGIN_ALLOW_THREADS
907 pvend = buf + total_v_size;
908 nfree = pvend - pvfree;
909 memset(pvfree, '\n', nfree);
910 p = fgets(pvfree, nfree, fp);
911 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000912
Tim Peters142297a2001-01-15 10:36:56 +0000913 if (p == NULL) {
914 clearerr(fp);
915 if (PyErr_CheckSignals())
916 return NULL;
917 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000918 return v;
919 }
Tim Peters142297a2001-01-15 10:36:56 +0000920 /* fgets read *something* */
921 p = memchr(pvfree, '\n', nfree);
922 if (p != NULL) {
923 /* Did the \n come from fgets or from us?
924 * Since fgets stops at the first \n, and then writes
925 * \0, if it's from fgets a \0 must be next. But if
926 * that's so, it could not have come from us, since
927 * the \n's we filled the buffer with have only more
928 * \n's to the right.
929 */
930 if (p+1 < pvend && *(p+1) == '\0') {
931 /* It's from fgets: we win! In particular,
932 * we haven't done any mallocs yet, and can
933 * build the final result on the first try.
934 */
935 ++p; /* include \n from fgets */
936 }
937 else {
938 /* Must be from us: fgets didn't fill the
939 * buffer and didn't find a newline, so it
940 * must be the last and newline-free line of
941 * the file.
942 */
943 assert(p > pvfree && *(p-1) == '\0');
944 --p; /* don't include \0 from fgets */
945 }
946 v = PyString_FromStringAndSize(buf, p - buf);
947 return v;
948 }
949 /* yuck: fgets overwrote all the newlines, i.e. the entire
950 * buffer. So this line isn't over yet, or maybe it is but
951 * we're exactly at EOF. If we haven't already, try using the
952 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +0000953 */
Tim Peters142297a2001-01-15 10:36:56 +0000954 assert(*(pvend-1) == '\0');
955 if (pvfree == buf) {
956 pvfree = pvend - 1; /* overwrite trailing null */
957 total_v_size = MAXBUFSIZE;
958 }
959 else
960 break;
Tim Peters86821b22001-01-07 21:19:34 +0000961 }
Tim Peters142297a2001-01-15 10:36:56 +0000962
963 /* The stack buffer isn't big enough; malloc a string object and read
964 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +0000965 */
Tim Petersddea2082002-03-23 10:03:50 +0000966 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +0000967 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +0000968 if (v == NULL)
969 return v;
970 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +0000971 memcpy(BUF(v), buf, MAXBUFSIZE-1);
972 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +0000973
974 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +0000975 * after setting p one beyond the end of the line. The code here is
976 * very much like the code above, except reads into v's buffer; see
977 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +0000978 */
979 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +0000980 Py_BEGIN_ALLOW_THREADS
981 pvend = BUF(v) + total_v_size;
982 nfree = pvend - pvfree;
983 memset(pvfree, '\n', nfree);
984 p = fgets(pvfree, nfree, fp);
985 Py_END_ALLOW_THREADS
986
987 if (p == NULL) {
988 clearerr(fp);
989 if (PyErr_CheckSignals()) {
990 Py_DECREF(v);
991 return NULL;
992 }
993 p = pvfree;
994 break;
995 }
Tim Peters86821b22001-01-07 21:19:34 +0000996 p = memchr(pvfree, '\n', nfree);
997 if (p != NULL) {
998 if (p+1 < pvend && *(p+1) == '\0') {
999 /* \n came from fgets */
1000 ++p;
1001 break;
1002 }
1003 /* \n came from us; last line of file, no newline */
1004 assert(p > pvfree && *(p-1) == '\0');
1005 --p;
1006 break;
1007 }
1008 /* expand buffer and try again */
1009 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001010 increment = total_v_size >> 2; /* mild exponential growth */
1011 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001012 if (total_v_size > INT_MAX) {
1013 PyErr_SetString(PyExc_OverflowError,
1014 "line is longer than a Python string can hold");
1015 Py_DECREF(v);
1016 return NULL;
1017 }
1018 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1019 return NULL;
1020 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001021 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001022 }
1023 if (BUF(v) + total_v_size != p)
1024 _PyString_Resize(&v, p - BUF(v));
1025 return v;
1026#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001027#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001028}
Tim Petersf29b64d2001-01-15 06:33:19 +00001029#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001030
Guido van Rossum0bd24411991-04-04 15:21:57 +00001031/* Internal routine to get a line.
1032 Size argument interpretation:
1033 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001034 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001035*/
1036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001037static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001038get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001039{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001040 FILE *fp = f->f_fp;
1041 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001042 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001043 size_t total_v_size; /* total # of slots in buffer */
1044 size_t used_v_size; /* # used slots in buffer */
1045 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001046 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001047#ifdef WITH_UNIVERSAL_NEWLINES
1048 int newlinetypes = f->f_newlinetypes;
1049 int skipnextlf = f->f_skipnextlf;
1050 int univ_newline = f->f_univ_newline;
1051#endif
Guido van Rossum0bd24411991-04-04 15:21:57 +00001052
Jack Jansen7b8c7542002-04-14 20:12:41 +00001053#if defined(USE_FGETS_IN_GETLINE)
1054#ifdef WITH_UNIVERSAL_NEWLINES
1055 if (n <= 0 && !univ_newline )
1056#else
Guido van Rossum86282062001-01-08 01:26:47 +00001057 if (n <= 0)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001058#endif
Tim Petersf29b64d2001-01-15 06:33:19 +00001059 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001060#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001061 total_v_size = n > 0 ? n : 100;
1062 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001063 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001064 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001065 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001066 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001067
Guido van Rossumce5ba841991-03-06 13:06:18 +00001068 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001069 Py_BEGIN_ALLOW_THREADS
1070 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001071#ifdef WITH_UNIVERSAL_NEWLINES
1072 if (univ_newline) {
1073 c = 'x'; /* Shut up gcc warning */
1074 while ( buf != end && (c = GETC(fp)) != EOF ) {
1075 if (skipnextlf ) {
1076 skipnextlf = 0;
1077 if (c == '\n') {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001078 /* Seeing a \n here with
1079 * skipnextlf true means we
1080 * saw a \r before.
1081 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001082 newlinetypes |= NEWLINE_CRLF;
1083 c = GETC(fp);
1084 if (c == EOF) break;
1085 } else {
1086 newlinetypes |= NEWLINE_CR;
1087 }
1088 }
1089 if (c == '\r') {
1090 skipnextlf = 1;
1091 c = '\n';
1092 } else if ( c == '\n')
1093 newlinetypes |= NEWLINE_LF;
1094 *buf++ = c;
1095 if (c == '\n') break;
1096 }
1097 if ( c == EOF && skipnextlf )
1098 newlinetypes |= NEWLINE_CR;
1099 } else /* If not universal newlines use the normal loop */
1100#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001101 while ((c = GETC(fp)) != EOF &&
1102 (*buf++ = c) != '\n' &&
1103 buf != end)
1104 ;
1105 FUNLOCKFILE(fp);
1106 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001107#ifdef WITH_UNIVERSAL_NEWLINES
1108 f->f_newlinetypes = newlinetypes;
1109 f->f_skipnextlf = skipnextlf;
1110#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001111 if (c == '\n')
1112 break;
1113 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001114 if (ferror(fp)) {
1115 PyErr_SetFromErrno(PyExc_IOError);
1116 clearerr(fp);
1117 Py_DECREF(v);
1118 return NULL;
1119 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001120 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001121 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001122 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001123 return NULL;
1124 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001125 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001126 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001127 /* Must be because buf == end */
1128 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001129 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001130 used_v_size = total_v_size;
1131 increment = total_v_size >> 2; /* mild exponential growth */
1132 total_v_size += increment;
1133 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001134 PyErr_SetString(PyExc_OverflowError,
1135 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001136 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001137 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001138 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001139 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001140 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001141 buf = BUF(v) + used_v_size;
1142 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001143 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001144
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001145 used_v_size = buf - BUF(v);
1146 if (used_v_size != total_v_size)
1147 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001148 return v;
1149}
1150
Guido van Rossum0bd24411991-04-04 15:21:57 +00001151/* External C interface */
1152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001153PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001154PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001155{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001156 PyObject *result;
1157
Guido van Rossum3165fe61992-09-25 21:59:05 +00001158 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001159 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001160 return NULL;
1161 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001162
1163 if (PyFile_Check(f)) {
1164 if (((PyFileObject*)f)->f_fp == NULL)
1165 return err_closed();
1166 result = get_line((PyFileObject *)f, n);
1167 }
1168 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001169 PyObject *reader;
1170 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001172 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001173 if (reader == NULL)
1174 return NULL;
1175 if (n <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001176 args = Py_BuildValue("()");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001177 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001178 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001179 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001180 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001181 return NULL;
1182 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001183 result = PyEval_CallObject(reader, args);
1184 Py_DECREF(reader);
1185 Py_DECREF(args);
1186 if (result != NULL && !PyString_Check(result)) {
1187 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001188 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001189 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001190 "object.readline() returned non-string");
1191 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001192 }
1193
1194 if (n < 0 && result != NULL && PyString_Check(result)) {
1195 char *s = PyString_AS_STRING(result);
1196 int len = PyString_GET_SIZE(result);
1197 if (len == 0) {
1198 Py_DECREF(result);
1199 result = NULL;
1200 PyErr_SetString(PyExc_EOFError,
1201 "EOF when reading a line");
1202 }
1203 else if (s[len-1] == '\n') {
1204 if (result->ob_refcnt == 1)
1205 _PyString_Resize(&result, len-1);
1206 else {
1207 PyObject *v;
1208 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001209 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001210 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001211 }
1212 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001213 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001214 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001215}
1216
1217/* Python method */
1218
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001219static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001220file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001221{
Guido van Rossum789a1611997-05-10 22:33:55 +00001222 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001223
Guido van Rossumd7297e61992-07-06 14:19:26 +00001224 if (f->f_fp == NULL)
1225 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001226 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001227 return NULL;
1228 if (n == 0)
1229 return PyString_FromString("");
1230 if (n < 0)
1231 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001232 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001233}
1234
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001235static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001236file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001237{
Guido van Rossum789a1611997-05-10 22:33:55 +00001238 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001239 PyObject *list;
1240 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001241 char small_buffer[SMALLCHUNK];
1242 char *buffer = small_buffer;
1243 size_t buffersize = SMALLCHUNK;
1244 PyObject *big_buffer = NULL;
1245 size_t nfilled = 0;
1246 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001247 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001248 char *p, *q, *end;
1249 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001250 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001251
Guido van Rossumd7297e61992-07-06 14:19:26 +00001252 if (f->f_fp == NULL)
1253 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001254 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001255 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001256 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001257 return NULL;
1258 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001259 if (shortread)
1260 nread = 0;
1261 else {
1262 Py_BEGIN_ALLOW_THREADS
1263 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001264 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001265 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001266 Py_END_ALLOW_THREADS
1267 shortread = (nread < buffersize-nfilled);
1268 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001269 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001270 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001271 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001272 break;
1273 PyErr_SetFromErrno(PyExc_IOError);
1274 clearerr(f->f_fp);
1275 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001276 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001277 list = NULL;
1278 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001279 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001280 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001281 p = memchr(buffer+nfilled, '\n', nread);
1282 if (p == NULL) {
1283 /* Need a larger buffer to fit this line */
1284 nfilled += nread;
1285 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001286 if (buffersize > INT_MAX) {
1287 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001288 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001289 goto error;
1290 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001291 if (big_buffer == NULL) {
1292 /* Create the big buffer */
1293 big_buffer = PyString_FromStringAndSize(
1294 NULL, buffersize);
1295 if (big_buffer == NULL)
1296 goto error;
1297 buffer = PyString_AS_STRING(big_buffer);
1298 memcpy(buffer, small_buffer, nfilled);
1299 }
1300 else {
1301 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001302 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1303 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001304 buffer = PyString_AS_STRING(big_buffer);
1305 }
1306 continue;
1307 }
1308 end = buffer+nfilled+nread;
1309 q = buffer;
1310 do {
1311 /* Process complete lines */
1312 p++;
1313 line = PyString_FromStringAndSize(q, p-q);
1314 if (line == NULL)
1315 goto error;
1316 err = PyList_Append(list, line);
1317 Py_DECREF(line);
1318 if (err != 0)
1319 goto error;
1320 q = p;
1321 p = memchr(q, '\n', end-q);
1322 } while (p != NULL);
1323 /* Move the remaining incomplete line to the start */
1324 nfilled = end-q;
1325 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001326 if (sizehint > 0)
1327 if (totalread >= (size_t)sizehint)
1328 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001329 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001330 if (nfilled != 0) {
1331 /* Partial last line */
1332 line = PyString_FromStringAndSize(buffer, nfilled);
1333 if (line == NULL)
1334 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001335 if (sizehint > 0) {
1336 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001337 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001338 if (rest == NULL) {
1339 Py_DECREF(line);
1340 goto error;
1341 }
1342 PyString_Concat(&line, rest);
1343 Py_DECREF(rest);
1344 if (line == NULL)
1345 goto error;
1346 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001347 err = PyList_Append(list, line);
1348 Py_DECREF(line);
1349 if (err != 0)
1350 goto error;
1351 }
1352 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001353 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001354 return list;
1355}
1356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001358file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001359{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001360 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001361 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001362 if (f->f_fp == NULL)
1363 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001364 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001365 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001366 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001367 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001368 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001369 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001370 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001371 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001373 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001374 return NULL;
1375 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 Py_INCREF(Py_None);
1377 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001378}
1379
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001380static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001381file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001382{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001383#define CHUNKSIZE 1000
1384 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001385 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001386 PyObject *result;
1387 int i, j, index, len, nwritten, islist;
1388
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001389 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001390 if (f->f_fp == NULL)
1391 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001392
1393 result = NULL;
1394 list = NULL;
1395 islist = PyList_Check(seq);
1396 if (islist)
1397 it = NULL;
1398 else {
1399 it = PyObject_GetIter(seq);
1400 if (it == NULL) {
1401 PyErr_SetString(PyExc_TypeError,
1402 "writelines() requires an iterable argument");
1403 return NULL;
1404 }
1405 /* From here on, fail by going to error, to reclaim "it". */
1406 list = PyList_New(CHUNKSIZE);
1407 if (list == NULL)
1408 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001409 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001410
1411 /* Strategy: slurp CHUNKSIZE lines into a private list,
1412 checking that they are all strings, then write that list
1413 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001414 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001415 if (islist) {
1416 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001417 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001418 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001419 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001420 j = PyList_GET_SIZE(list);
1421 }
1422 else {
1423 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001424 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001425 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001426 if (PyErr_Occurred())
1427 goto error;
1428 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001429 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001430 PyList_SetItem(list, j, line);
1431 }
1432 }
1433 if (j == 0)
1434 break;
1435
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001436 /* Check that all entries are indeed strings. If not,
1437 apply the same rules as for file.write() and
1438 convert the results to strings. This is slow, but
1439 seems to be the only way since all conversion APIs
1440 could potentially execute Python code. */
1441 for (i = 0; i < j; i++) {
1442 PyObject *v = PyList_GET_ITEM(list, i);
1443 if (!PyString_Check(v)) {
1444 const char *buffer;
1445 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001446 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001447 PyObject_AsReadBuffer(v,
1448 (const void**)&buffer,
1449 &len)) ||
1450 PyObject_AsCharBuffer(v,
1451 &buffer,
1452 &len))) {
1453 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001454 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001455 goto error;
1456 }
1457 line = PyString_FromStringAndSize(buffer,
1458 len);
1459 if (line == NULL)
1460 goto error;
1461 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001462 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001463 }
1464 }
1465
1466 /* Since we are releasing the global lock, the
1467 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001468 Py_BEGIN_ALLOW_THREADS
1469 f->f_softspace = 0;
1470 errno = 0;
1471 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001472 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001473 len = PyString_GET_SIZE(line);
1474 nwritten = fwrite(PyString_AS_STRING(line),
1475 1, len, f->f_fp);
1476 if (nwritten != len) {
1477 Py_BLOCK_THREADS
1478 PyErr_SetFromErrno(PyExc_IOError);
1479 clearerr(f->f_fp);
1480 goto error;
1481 }
1482 }
1483 Py_END_ALLOW_THREADS
1484
1485 if (j < CHUNKSIZE)
1486 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001487 }
1488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001490 result = Py_None;
1491 error:
1492 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001493 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001494 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001495#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001496}
1497
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001498static PyObject *
1499file_getiter(PyFileObject *f)
1500{
1501 if (f->f_fp == NULL)
1502 return err_closed();
1503 Py_INCREF(f);
1504 return (PyObject *)f;
1505}
1506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001507PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001508"readline([size]) -> next line from the file, as a string.\n"
1509"\n"
1510"Retain newline. A non-negative size argument limits the maximum\n"
1511"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001512"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001514PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001515"read([size]) -> read at most size bytes, returned as a string.\n"
1516"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001517"If the size argument is negative or omitted, read until EOF is reached.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001518
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001519PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001520"write(str) -> None. Write string str to file.\n"
1521"\n"
1522"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001523"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001524
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001525PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001526"fileno() -> integer \"file descriptor\".\n"
1527"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001528"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001530PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001531"seek(offset[, whence]) -> None. Move to new file position.\n"
1532"\n"
1533"Argument offset is a byte count. Optional argument whence defaults to\n"
1534"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1535"(move relative to current position, positive or negative), and 2 (move\n"
1536"relative to end of file, usually negative, although many platforms allow\n"
1537"seeking beyond the end of a file).\n"
1538"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001539"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001540
Guido van Rossumd7047b31995-01-02 19:07:15 +00001541#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001542PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001543"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1544"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001545"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001546#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001547
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001548PyDoc_STRVAR(tell_doc,
1549"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001551PyDoc_STRVAR(readinto_doc,
1552"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001554PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001555"readlines([size]) -> list of strings, each a line from the file.\n"
1556"\n"
1557"Call readline() repeatedly and return a list of the lines so read.\n"
1558"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001559"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001561PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001562"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001563"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001564"For backward compatibility. File objects now include the performance\n"
1565"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001566
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001567PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001568"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001569"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001570"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001571"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001572
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001573PyDoc_STRVAR(flush_doc,
1574"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001576PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001577"close() -> None or (perhaps) an integer. Close the file.\n"
1578"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001579"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001580"further I/O operations. close() may be called more than once without\n"
1581"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001582"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001584PyDoc_STRVAR(isatty_doc,
1585"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001586
1587static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001588 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1589 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1590 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1591 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1592 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001593#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001594 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001595#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001596 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1597 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1598 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1599 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1600 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1601 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1602 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1603 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1604 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001605};
1606
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001607#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001608
Guido van Rossum6f799372001-09-20 20:46:19 +00001609static PyMemberDef file_memberlist[] = {
1610 {"softspace", T_INT, OFF(f_softspace), 0,
1611 "flag indicating that a space needs to be printed; used by print"},
1612 {"mode", T_OBJECT, OFF(f_mode), RO,
1613 "file mode ('r', 'w', 'a', possibly with 'b' or '+' added)"},
1614 {"name", T_OBJECT, OFF(f_name), RO,
1615 "file name"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001616 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001617 {NULL} /* Sentinel */
1618};
1619
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001620static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001621get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001622{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001623 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001624}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001625#ifdef WITH_UNIVERSAL_NEWLINES
1626static PyObject *
1627get_newlines(PyFileObject *f, void *closure)
1628{
1629 switch (f->f_newlinetypes) {
1630 case NEWLINE_UNKNOWN:
1631 Py_INCREF(Py_None);
1632 return Py_None;
1633 case NEWLINE_CR:
1634 return PyString_FromString("\r");
1635 case NEWLINE_LF:
1636 return PyString_FromString("\n");
1637 case NEWLINE_CR|NEWLINE_LF:
1638 return Py_BuildValue("(ss)", "\r", "\n");
1639 case NEWLINE_CRLF:
1640 return PyString_FromString("\r\n");
1641 case NEWLINE_CR|NEWLINE_CRLF:
1642 return Py_BuildValue("(ss)", "\r", "\r\n");
1643 case NEWLINE_LF|NEWLINE_CRLF:
1644 return Py_BuildValue("(ss)", "\n", "\r\n");
1645 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1646 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1647 default:
Jeremy Hylton8b735422002-08-14 21:01:41 +00001648 PyErr_Format(PyExc_SystemError,
1649 "Unknown newlines value 0x%x\n",
1650 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001651 return NULL;
1652 }
1653}
1654#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +00001655
Guido van Rossum32d34c82001-09-20 21:45:26 +00001656static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001657 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001658#ifdef WITH_UNIVERSAL_NEWLINES
Jeremy Hylton8b735422002-08-14 21:01:41 +00001659 {"newlines", (getter)get_newlines, NULL,
1660 "end-of-line convention used in this file"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001661#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662 {0},
1663};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001664
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001665static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001666drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001667{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001668 if (f->f_buf != NULL) {
1669 PyMem_Free(f->f_buf);
1670 f->f_buf = NULL;
1671 }
Guido van Rossum65967252001-04-21 13:20:18 +00001672}
1673
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001674/* Make sure that file has a readahead buffer with at least one byte
1675 (unless at EOF) and no more than bufsize. Returns negative value on
1676 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001677static int
1678readahead(PyFileObject *f, int bufsize)
1679{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001680 int chunksize;
1681
1682 if (f->f_buf != NULL) {
1683 if( (f->f_bufend - f->f_bufptr) >= 1)
1684 return 0;
1685 else
1686 drop_readahead(f);
1687 }
1688 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1689 return -1;
1690 }
1691 Py_BEGIN_ALLOW_THREADS
1692 errno = 0;
1693 chunksize = Py_UniversalNewlineFread(
1694 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1695 Py_END_ALLOW_THREADS
1696 if (chunksize == 0) {
1697 if (ferror(f->f_fp)) {
1698 PyErr_SetFromErrno(PyExc_IOError);
1699 clearerr(f->f_fp);
1700 drop_readahead(f);
1701 return -1;
1702 }
1703 }
1704 f->f_bufptr = f->f_buf;
1705 f->f_bufend = f->f_buf + chunksize;
1706 return 0;
1707}
1708
1709/* Used by file_iternext. The returned string will start with 'skip'
1710 uninitialized bytes followed by the remainder of the line. Don't be
1711 horrified by the recursive call: maximum recursion depth is limited by
1712 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1713
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001714static PyStringObject *
1715readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1716{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001717 PyStringObject* s;
1718 char *bufptr;
1719 char *buf;
1720 int len;
1721
1722 if (f->f_buf == NULL)
1723 if (readahead(f, bufsize) < 0)
1724 return NULL;
1725
1726 len = f->f_bufend - f->f_bufptr;
1727 if (len == 0)
1728 return (PyStringObject *)
1729 PyString_FromStringAndSize(NULL, skip);
1730 bufptr = memchr(f->f_bufptr, '\n', len);
1731 if (bufptr != NULL) {
1732 bufptr++; /* Count the '\n' */
1733 len = bufptr - f->f_bufptr;
1734 s = (PyStringObject *)
1735 PyString_FromStringAndSize(NULL, skip+len);
1736 if (s == NULL)
1737 return NULL;
1738 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1739 f->f_bufptr = bufptr;
1740 if (bufptr == f->f_bufend)
1741 drop_readahead(f);
1742 } else {
1743 bufptr = f->f_bufptr;
1744 buf = f->f_buf;
1745 f->f_buf = NULL; /* Force new readahead buffer */
1746 s = readahead_get_line_skip(
1747 f, skip+len, bufsize + (bufsize>>2) );
1748 if (s == NULL) {
1749 PyMem_Free(buf);
1750 return NULL;
1751 }
1752 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1753 PyMem_Free(buf);
1754 }
1755 return s;
1756}
1757
1758/* A larger buffer size may actually decrease performance. */
1759#define READAHEAD_BUFSIZE 8192
1760
1761static PyObject *
1762file_iternext(PyFileObject *f)
1763{
1764 PyStringObject* l;
1765
1766 int i;
1767
1768 if (f->f_fp == NULL)
1769 return err_closed();
1770
1771 i = f->f_softspace;
1772
1773 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1774 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1775 Py_XDECREF(l);
1776 return NULL;
1777 }
1778 return (PyObject *)l;
1779}
1780
1781
Tim Peters59c9a642001-09-13 05:38:56 +00001782static PyObject *
1783file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1784{
Tim Peters44410012001-09-14 03:26:08 +00001785 PyObject *self;
1786 static PyObject *not_yet_string;
1787
1788 assert(type != NULL && type->tp_alloc != NULL);
1789
1790 if (not_yet_string == NULL) {
1791 not_yet_string = PyString_FromString("<uninitialized file>");
1792 if (not_yet_string == NULL)
1793 return NULL;
1794 }
1795
1796 self = type->tp_alloc(type, 0);
1797 if (self != NULL) {
1798 /* Always fill in the name and mode, so that nobody else
1799 needs to special-case NULLs there. */
1800 Py_INCREF(not_yet_string);
1801 ((PyFileObject *)self)->f_name = not_yet_string;
1802 Py_INCREF(not_yet_string);
1803 ((PyFileObject *)self)->f_mode = not_yet_string;
1804 }
1805 return self;
1806}
1807
1808static int
1809file_init(PyObject *self, PyObject *args, PyObject *kwds)
1810{
1811 PyFileObject *foself = (PyFileObject *)self;
1812 int ret = 0;
Tim Peters59c9a642001-09-13 05:38:56 +00001813 static char *kwlist[] = {"name", "mode", "buffering", 0};
1814 char *name = NULL;
1815 char *mode = "r";
1816 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001817 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001818
1819 assert(PyFile_Check(self));
1820 if (foself->f_fp != NULL) {
1821 /* Have to close the existing file first. */
1822 PyObject *closeresult = file_close(foself);
1823 if (closeresult == NULL)
1824 return -1;
1825 Py_DECREF(closeresult);
1826 }
Tim Peters59c9a642001-09-13 05:38:56 +00001827
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001828#ifdef Py_WIN_WIDE_FILENAMES
1829 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1830 PyObject *po;
1831 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1832 kwlist, &po, &mode, &bufsize)) {
1833 wideargument = 1;
1834 if (fill_file_fields(foself, NULL, name, mode,
1835 fclose, po) == NULL)
1836 goto Error;
1837 } else {
1838 /* Drop the argument parsing error as narrow
1839 strings are also valid. */
1840 PyErr_Clear();
1841 }
1842 }
1843#endif
1844
1845 if (!wideargument) {
1846 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1847 Py_FileSystemDefaultEncoding,
1848 &name,
1849 &mode, &bufsize))
1850 return -1;
1851 if (fill_file_fields(foself, NULL, name, mode,
1852 fclose, NULL) == NULL)
1853 goto Error;
1854 }
Tim Peters44410012001-09-14 03:26:08 +00001855 if (open_the_file(foself, name, mode) == NULL)
1856 goto Error;
1857 PyFile_SetBufSize(self, bufsize);
1858 goto Done;
1859
1860Error:
1861 ret = -1;
1862 /* fall through */
1863Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001864 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001865 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001866}
1867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001868PyDoc_VAR(file_doc) =
1869PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001870"file(name[, mode[, buffering]]) -> file object\n"
1871"\n"
1872"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1873"writing or appending. The file will be created if it doesn't exist\n"
1874"when opened for writing or appending; it will be truncated when\n"
1875"opened for writing. Add a 'b' to the mode for binary files.\n"
1876"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1877"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001878"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001879)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001880#ifdef WITH_UNIVERSAL_NEWLINES
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001881PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001882"Add a 'U' to mode to open the file for input with universal newline\n"
1883"support. Any line ending in the input file will be seen as a '\\n'\n"
1884"in Python. Also, a file so opened gains the attribute 'newlines';\n"
1885"the value for this attribute is one of None (no newline read yet),\n"
1886"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
1887"\n"
1888"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001889)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001890#endif /* WITH_UNIVERSAL_NEWLINES */
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001892"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001893"Note: open() is an alias for file()."
1894);
Tim Peters59c9a642001-09-13 05:38:56 +00001895
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001896PyTypeObject PyFile_Type = {
1897 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001898 0,
1899 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001900 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001901 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001902 (destructor)file_dealloc, /* tp_dealloc */
1903 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001904 0, /* tp_getattr */
1905 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001906 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001907 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001908 0, /* tp_as_number */
1909 0, /* tp_as_sequence */
1910 0, /* tp_as_mapping */
1911 0, /* tp_hash */
1912 0, /* tp_call */
1913 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65967252001-04-21 13:20:18 +00001915 0, /* tp_setattro */
1916 0, /* tp_as_buffer */
Guido van Rossum9475a232001-10-05 20:51:39 +00001917 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00001918 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001919 0, /* tp_traverse */
1920 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00001921 0, /* tp_richcompare */
1922 0, /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001923 (getiterfunc)file_getiter, /* tp_iter */
1924 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925 file_methods, /* tp_methods */
1926 file_memberlist, /* tp_members */
1927 file_getsetlist, /* tp_getset */
1928 0, /* tp_base */
1929 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00001930 0, /* tp_descr_get */
1931 0, /* tp_descr_set */
1932 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00001933 (initproc)file_init, /* tp_init */
1934 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00001935 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00001936 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001937};
Guido van Rossumeb183da1991-04-04 10:44:06 +00001938
1939/* Interface for the 'soft space' between print items. */
1940
1941int
Fred Drakefd99de62000-07-09 05:02:18 +00001942PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00001943{
1944 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001945 if (f == NULL) {
1946 /* Do nothing */
1947 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001948 else if (PyFile_Check(f)) {
1949 oldflag = ((PyFileObject *)f)->f_softspace;
1950 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001951 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001952 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001953 PyObject *v;
1954 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001955 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001956 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00001957 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001958 if (PyInt_Check(v))
1959 oldflag = PyInt_AsLong(v);
1960 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001961 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001962 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001963 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001964 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00001965 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001966 if (PyObject_SetAttrString(f, "softspace", v) != 0)
1967 PyErr_Clear();
1968 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001969 }
1970 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00001971 return oldflag;
1972}
Guido van Rossum3165fe61992-09-25 21:59:05 +00001973
1974/* Interfaces to write objects/strings to file-like objects */
1975
1976int
Fred Drakefd99de62000-07-09 05:02:18 +00001977PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00001978{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001979 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001980 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001981 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001982 return -1;
1983 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001984 else if (PyFile_Check(f)) {
1985 FILE *fp = PyFile_AsFile(f);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001986 if (fp == NULL) {
1987 err_closed();
1988 return -1;
1989 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001990 return PyObject_Print(v, fp, flags);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001991 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001992 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001993 if (writer == NULL)
1994 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00001995 if (flags & Py_PRINT_RAW) {
1996 if (PyUnicode_Check(v)) {
1997 value = v;
1998 Py_INCREF(value);
1999 } else
2000 value = PyObject_Str(v);
2001 }
2002 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002004 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002005 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002006 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002007 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008 args = Py_BuildValue("(O)", value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002009 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002010 Py_DECREF(value);
2011 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002012 return -1;
2013 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002014 result = PyEval_CallObject(writer, args);
2015 Py_DECREF(args);
2016 Py_DECREF(value);
2017 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002018 if (result == NULL)
2019 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002020 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002021 return 0;
2022}
2023
Guido van Rossum27a60b11997-05-22 22:25:11 +00002024int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002025PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002026{
2027 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002028 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002029 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002030 PyErr_SetString(PyExc_SystemError,
2031 "null file for PyFile_WriteString");
2032 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002033 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034 else if (PyFile_Check(f)) {
2035 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002036 if (fp == NULL) {
2037 err_closed();
2038 return -1;
2039 }
2040 fputs(s, fp);
2041 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002042 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043 else if (!PyErr_Occurred()) {
2044 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002045 int err;
2046 if (v == NULL)
2047 return -1;
2048 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2049 Py_DECREF(v);
2050 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002051 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002052 else
2053 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002054}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002055
2056/* Try to get a file-descriptor from a Python object. If the object
2057 is an integer or long integer, its value is returned. If not, the
2058 object's fileno() method is called if it exists; the method must return
2059 an integer or long integer, which is returned as the file descriptor value.
2060 -1 is returned on failure.
2061*/
2062
2063int PyObject_AsFileDescriptor(PyObject *o)
2064{
2065 int fd;
2066 PyObject *meth;
2067
2068 if (PyInt_Check(o)) {
2069 fd = PyInt_AsLong(o);
2070 }
2071 else if (PyLong_Check(o)) {
2072 fd = PyLong_AsLong(o);
2073 }
2074 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2075 {
2076 PyObject *fno = PyEval_CallObject(meth, NULL);
2077 Py_DECREF(meth);
2078 if (fno == NULL)
2079 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002080
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002081 if (PyInt_Check(fno)) {
2082 fd = PyInt_AsLong(fno);
2083 Py_DECREF(fno);
2084 }
2085 else if (PyLong_Check(fno)) {
2086 fd = PyLong_AsLong(fno);
2087 Py_DECREF(fno);
2088 }
2089 else {
2090 PyErr_SetString(PyExc_TypeError,
2091 "fileno() returned a non-integer");
2092 Py_DECREF(fno);
2093 return -1;
2094 }
2095 }
2096 else {
2097 PyErr_SetString(PyExc_TypeError,
2098 "argument must be an int, or have a fileno() method.");
2099 return -1;
2100 }
2101
2102 if (fd < 0) {
2103 PyErr_Format(PyExc_ValueError,
2104 "file descriptor cannot be a negative integer (%i)",
2105 fd);
2106 return -1;
2107 }
2108 return fd;
2109}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002110
2111#ifdef WITH_UNIVERSAL_NEWLINES
2112/* From here on we need access to the real fgets and fread */
2113#undef fgets
2114#undef fread
2115
2116/*
2117** Py_UniversalNewlineFgets is an fgets variation that understands
2118** all of \r, \n and \r\n conventions.
2119** The stream should be opened in binary mode.
2120** If fobj is NULL the routine always does newline conversion, and
2121** it may peek one char ahead to gobble the second char in \r\n.
2122** If fobj is non-NULL it must be a PyFileObject. In this case there
2123** is no readahead but in stead a flag is used to skip a following
2124** \n on the next read. Also, if the file is open in binary mode
2125** the whole conversion is skipped. Finally, the routine keeps track of
2126** the different types of newlines seen.
2127** Note that we need no error handling: fgets() treats error and eof
2128** identically.
2129*/
2130char *
2131Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2132{
2133 char *p = buf;
2134 int c;
2135 int newlinetypes = 0;
2136 int skipnextlf = 0;
2137 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002138
Jack Jansen7b8c7542002-04-14 20:12:41 +00002139 if (fobj) {
2140 if (!PyFile_Check(fobj)) {
2141 errno = ENXIO; /* What can you do... */
2142 return NULL;
2143 }
2144 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2145 if ( !univ_newline )
2146 return fgets(buf, n, stream);
2147 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2148 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2149 }
2150 FLOCKFILE(stream);
2151 c = 'x'; /* Shut up gcc warning */
2152 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2153 if (skipnextlf ) {
2154 skipnextlf = 0;
2155 if (c == '\n') {
2156 /* Seeing a \n here with skipnextlf true
2157 ** means we saw a \r before.
2158 */
2159 newlinetypes |= NEWLINE_CRLF;
2160 c = GETC(stream);
2161 if (c == EOF) break;
2162 } else {
2163 /*
2164 ** Note that c == EOF also brings us here,
2165 ** so we're okay if the last char in the file
2166 ** is a CR.
2167 */
2168 newlinetypes |= NEWLINE_CR;
2169 }
2170 }
2171 if (c == '\r') {
2172 /* A \r is translated into a \n, and we skip
2173 ** an adjacent \n, if any. We don't set the
2174 ** newlinetypes flag until we've seen the next char.
2175 */
2176 skipnextlf = 1;
2177 c = '\n';
2178 } else if ( c == '\n') {
2179 newlinetypes |= NEWLINE_LF;
2180 }
2181 *p++ = c;
2182 if (c == '\n') break;
2183 }
2184 if ( c == EOF && skipnextlf )
2185 newlinetypes |= NEWLINE_CR;
2186 FUNLOCKFILE(stream);
2187 *p = '\0';
2188 if (fobj) {
2189 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2190 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2191 } else if ( skipnextlf ) {
2192 /* If we have no file object we cannot save the
2193 ** skipnextlf flag. We have to readahead, which
2194 ** will cause a pause if we're reading from an
2195 ** interactive stream, but that is very unlikely
2196 ** unless we're doing something silly like
2197 ** execfile("/dev/tty").
2198 */
2199 c = GETC(stream);
2200 if ( c != '\n' )
2201 ungetc(c, stream);
2202 }
2203 if (p == buf)
2204 return NULL;
2205 return buf;
2206}
2207
2208/*
2209** Py_UniversalNewlineFread is an fread variation that understands
2210** all of \r, \n and \r\n conventions.
2211** The stream should be opened in binary mode.
2212** fobj must be a PyFileObject. In this case there
2213** is no readahead but in stead a flag is used to skip a following
2214** \n on the next read. Also, if the file is open in binary mode
2215** the whole conversion is skipped. Finally, the routine keeps track of
2216** the different types of newlines seen.
2217*/
2218size_t
Tim Peters058b1412002-04-21 07:29:14 +00002219Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002220 FILE *stream, PyObject *fobj)
2221{
Tim Peters058b1412002-04-21 07:29:14 +00002222 char *dst = buf;
2223 PyFileObject *f = (PyFileObject *)fobj;
2224 int newlinetypes, skipnextlf;
2225
2226 assert(buf != NULL);
2227 assert(stream != NULL);
2228
Jack Jansen7b8c7542002-04-14 20:12:41 +00002229 if (!fobj || !PyFile_Check(fobj)) {
2230 errno = ENXIO; /* What can you do... */
2231 return -1;
2232 }
Tim Peters058b1412002-04-21 07:29:14 +00002233 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002234 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002235 newlinetypes = f->f_newlinetypes;
2236 skipnextlf = f->f_skipnextlf;
2237 /* Invariant: n is the number of bytes remaining to be filled
2238 * in the buffer.
2239 */
2240 while (n) {
2241 size_t nread;
2242 int shortread;
2243 char *src = dst;
2244
2245 nread = fread(dst, 1, n, stream);
2246 assert(nread <= n);
Tim Peterse1682a82002-04-21 18:15:20 +00002247 n -= nread; /* assuming 1 byte out for each in; will adjust */
2248 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002249 while (nread--) {
2250 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002251 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002252 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002253 *dst++ = '\n';
2254 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002255 }
2256 else if (skipnextlf && c == '\n') {
2257 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002258 skipnextlf = 0;
2259 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002260 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002261 }
2262 else {
2263 /* Normal char to be stored in buffer. Also
2264 * update the newlinetypes flag if either this
2265 * is an LF or the previous char was a CR.
2266 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002267 if (c == '\n')
2268 newlinetypes |= NEWLINE_LF;
2269 else if (skipnextlf)
2270 newlinetypes |= NEWLINE_CR;
2271 *dst++ = c;
2272 skipnextlf = 0;
2273 }
2274 }
Tim Peters058b1412002-04-21 07:29:14 +00002275 if (shortread) {
2276 /* If this is EOF, update type flags. */
2277 if (skipnextlf && feof(stream))
2278 newlinetypes |= NEWLINE_CR;
2279 break;
2280 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002281 }
Tim Peters058b1412002-04-21 07:29:14 +00002282 f->f_newlinetypes = newlinetypes;
2283 f->f_skipnextlf = skipnextlf;
2284 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002285}
2286#endif