blob: 86620ff867ed6e2ec970aea49b63a46a5204e4fe [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);
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000119#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000120 if (wname)
121 f->f_name = PyUnicode_FromObject(wname);
122 else
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000123#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000124 f->f_name = PyString_FromString(name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000126
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000127 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000128 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000129 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000130 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000131#ifdef WITH_UNIVERSAL_NEWLINES
132 f->f_univ_newline = (strchr(mode, 'U') != NULL);
133 f->f_newlinetypes = NEWLINE_UNKNOWN;
134 f->f_skipnextlf = 0;
135#endif
Tim Peters44410012001-09-14 03:26:08 +0000136
Tim Peters59c9a642001-09-13 05:38:56 +0000137 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000140 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142}
143
Tim Peters59c9a642001-09-13 05:38:56 +0000144static PyObject *
145open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146{
Tim Peters59c9a642001-09-13 05:38:56 +0000147 assert(f != NULL);
148 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000149#ifdef MS_WINDOWS
150 /* windows ignores the passed name in order to support Unicode */
151 assert(f->f_name != NULL);
152#else
Tim Peters59c9a642001-09-13 05:38:56 +0000153 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000154#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000155 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000156 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000157
Tim Peters8fa45672001-09-13 21:01:29 +0000158 /* rexec.py can't stop a user from getting the file() constructor --
159 all they have to do is get *any* file object f, and then do
160 type(f). Here we prevent them from doing damage with it. */
161 if (PyEval_GetRestricted()) {
162 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000163 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000164 return NULL;
165 }
Tim Petersa27a1502001-11-09 20:59:14 +0000166 errno = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000167#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000168 if (*mode == '*') {
169 FILE *fopenRF();
170 f->f_fp = fopenRF(name, mode+1);
171 }
172 else
173#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000174 {
Jack Jansen7b8c7542002-04-14 20:12:41 +0000175#ifdef WITH_UNIVERSAL_NEWLINES
176 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
177 mode = "rb";
178#else
179 /* Compatibility: specifying U in a Python without universal
180 ** newlines is allowed, and the file is opened as a normal text
181 ** file.
182 */
183 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
184 mode = "r";
185#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000186#ifdef MS_WINDOWS
187 if (PyUnicode_Check(f->f_name)) {
188 PyObject *wmode;
189 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
190 if (f->f_name && wmode) {
191 Py_BEGIN_ALLOW_THREADS
192 /* PyUnicode_AS_UNICODE OK without thread
193 lock as it is a simple dereference. */
194 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
195 PyUnicode_AS_UNICODE(wmode));
196 Py_END_ALLOW_THREADS
197 }
198 Py_XDECREF(wmode);
199 }
200#endif
201 if (NULL == f->f_fp && NULL != name) {
202 Py_BEGIN_ALLOW_THREADS
203 f->f_fp = fopen(name, mode);
204 Py_END_ALLOW_THREADS
205 }
Guido van Rossumff4949e1992-08-05 19:58:53 +0000206 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000207 if (f->f_fp == NULL) {
Jack Jansene08dea191995-04-23 22:12:47 +0000208#ifdef NO_FOPEN_ERRNO
Jack Jansenb3be2162001-11-30 14:16:36 +0000209 /* Metroworks only, wich does not always sets errno */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000210 if (errno == 0) {
Jack Jansenb3be2162001-11-30 14:16:36 +0000211 PyObject *v;
212 v = Py_BuildValue("(is)", 0, "Cannot open file");
213 if (v != NULL) {
214 PyErr_SetObject(PyExc_IOError, v);
215 Py_DECREF(v);
216 }
Jack Jansene08dea191995-04-23 22:12:47 +0000217 return NULL;
218 }
219#endif
Tim Peters2ea91112002-04-08 04:13:12 +0000220#ifdef _MSC_VER
221 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
222 * across all Windows flavors. When it sets EINVAL varies
223 * across Windows flavors, the exact conditions aren't
224 * documented, and the answer lies in the OS's implementation
225 * of Win32's CreateFile function (whose source is secret).
226 * Seems the best we can do is map EINVAL to ENOENT.
227 */
228 if (errno == 0) /* bad mode string */
229 errno = EINVAL;
230 else if (errno == EINVAL) /* unknown, but not a mode string */
231 errno = ENOENT;
232#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000233 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000234 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000235 mode);
236 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000237#ifdef MS_WINDOWS
238 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
239#else
Jeremy Hylton41c83212001-11-09 16:17:24 +0000240 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000241#endif /* MS_WINDOWS */
Tim Peters59c9a642001-09-13 05:38:56 +0000242 f = NULL;
243 }
Tim Peters2ea91112002-04-08 04:13:12 +0000244 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000245 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000246 return (PyObject *)f;
247}
248
249PyObject *
250PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
251{
Tim Peters44410012001-09-14 03:26:08 +0000252 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
253 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000254 if (f != NULL) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000255 if (fill_file_fields(f, fp, name, mode, close, NULL) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000256 Py_DECREF(f);
257 f = NULL;
258 }
259 }
260 return (PyObject *) f;
261}
262
263PyObject *
264PyFile_FromString(char *name, char *mode)
265{
266 extern int fclose(FILE *);
267 PyFileObject *f;
268
269 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
270 if (f != NULL) {
271 if (open_the_file(f, name, mode) == NULL) {
272 Py_DECREF(f);
273 f = NULL;
274 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000276 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277}
278
Guido van Rossumb6775db1994-08-01 11:34:53 +0000279void
Fred Drakefd99de62000-07-09 05:02:18 +0000280PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000281{
282 if (bufsize >= 0) {
283#ifdef HAVE_SETVBUF
284 int type;
285 switch (bufsize) {
286 case 0:
287 type = _IONBF;
288 break;
289 case 1:
290 type = _IOLBF;
291 bufsize = BUFSIZ;
292 break;
293 default:
294 type = _IOFBF;
295 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296 setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
297 type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000298#else /* !HAVE_SETVBUF */
299 if (bufsize <= 1)
300 setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
301#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000302 }
303}
304
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000306err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000307{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000309 return NULL;
310}
311
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000312static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000313
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000314/* Methods */
315
316static void
Fred Drakefd99de62000-07-09 05:02:18 +0000317file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000319 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000321 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000323 }
Tim Peters44410012001-09-14 03:26:08 +0000324 Py_XDECREF(f->f_name);
325 Py_XDECREF(f->f_mode);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000326 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000327 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000328}
329
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000331file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000333 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000334#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000335 PyObject *ret = NULL;
336 PyObject *name;
337 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
338 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
339 f->f_fp == NULL ? "closed" : "open",
340 PyString_AsString(name),
341 PyString_AsString(f->f_mode),
342 f);
343 Py_XDECREF(name);
344 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000345#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000346 } else {
347 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000348 f->f_fp == NULL ? "closed" : "open",
349 PyString_AsString(f->f_name),
350 PyString_AsString(f->f_mode),
351 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000352 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353}
354
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000356file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000358 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000360 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000362 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000363 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000365 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 f->f_fp = NULL;
367 }
Guido van Rossumfebd5511992-03-04 16:39:24 +0000368 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000370 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371 return PyInt_FromLong((long)sts);
372 Py_INCREF(Py_None);
373 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374}
375
Trent Mickf29f47b2000-08-11 19:02:59 +0000376
Guido van Rossumb8552162001-09-05 14:58:11 +0000377/* Our very own off_t-like type, 64-bit if possible */
378#if !defined(HAVE_LARGEFILE_SUPPORT)
379typedef off_t Py_off_t;
380#elif SIZEOF_OFF_T >= 8
381typedef off_t Py_off_t;
382#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000383typedef fpos_t Py_off_t;
384#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000385#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000386#endif
387
388
Trent Mickf29f47b2000-08-11 19:02:59 +0000389/* a portable fseek() function
390 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000391static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000392_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000393{
Guido van Rossumb8552162001-09-05 14:58:11 +0000394#if !defined(HAVE_LARGEFILE_SUPPORT)
395 return fseek(fp, offset, whence);
396#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000397 return fseeko(fp, offset, whence);
398#elif defined(HAVE_FSEEK64)
399 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000400#elif defined(__BEOS__)
401 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000402#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000403 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
404 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000405 fpos_t pos;
406 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000407 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000408#ifdef MS_WINDOWS
409 fflush(fp);
410 if (_lseeki64(fileno(fp), 0, 2) == -1)
411 return -1;
412#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000413 if (fseek(fp, 0, SEEK_END) != 0)
414 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000415#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000416 /* fall through */
417 case SEEK_CUR:
418 if (fgetpos(fp, &pos) != 0)
419 return -1;
420 offset += pos;
421 break;
422 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000423 }
424 return fsetpos(fp, &offset);
425#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000426#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000427#endif
428}
429
430
431/* a portable ftell() function
432 Return -1 on failure with errno set appropriately, current file
433 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000434static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000435_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000436{
Guido van Rossumb8552162001-09-05 14:58:11 +0000437#if !defined(HAVE_LARGEFILE_SUPPORT)
438 return ftell(fp);
439#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
440 return ftello(fp);
441#elif defined(HAVE_FTELL64)
442 return ftell64(fp);
443#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000444 fpos_t pos;
445 if (fgetpos(fp, &pos) != 0)
446 return -1;
447 return pos;
448#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000449#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000450#endif
451}
452
453
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000455file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000457 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000458 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000459 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000460 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000461
Guido van Rossumd7297e61992-07-06 14:19:26 +0000462 if (f->f_fp == NULL)
463 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000464 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000465 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000466 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000467 return NULL;
468#if !defined(HAVE_LARGEFILE_SUPPORT)
469 offset = PyInt_AsLong(offobj);
470#else
471 offset = PyLong_Check(offobj) ?
472 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
473#endif
474 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000475 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000476
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000478 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000479 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000481
Guido van Rossumff4949e1992-08-05 19:58:53 +0000482 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000484 clearerr(f->f_fp);
485 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000486 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000487#ifdef WITH_UNIVERSAL_NEWLINES
488 f->f_skipnextlf = 0;
489#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 Py_INCREF(Py_None);
491 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000492}
493
Trent Mickf29f47b2000-08-11 19:02:59 +0000494
Guido van Rossumd7047b31995-01-02 19:07:15 +0000495#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000497file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000498{
Guido van Rossumd7047b31995-01-02 19:07:15 +0000499 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000500 Py_off_t newsize;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000501 PyObject *newsizeobj;
Tim Peters86821b22001-01-07 21:19:34 +0000502
Guido van Rossumd7047b31995-01-02 19:07:15 +0000503 if (f->f_fp == NULL)
504 return err_closed();
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000505 newsizeobj = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +0000506 if (!PyArg_ParseTuple(args, "|O:truncate", &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000507 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000508
509 /* Set newsize to current postion if newsizeobj NULL, else to the
510 specified value. */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000511 if (newsizeobj != NULL) {
512#if !defined(HAVE_LARGEFILE_SUPPORT)
513 newsize = PyInt_AsLong(newsizeobj);
514#else
515 newsize = PyLong_Check(newsizeobj) ?
516 PyLong_AsLongLong(newsizeobj) :
517 PyInt_AsLong(newsizeobj);
518#endif
519 if (PyErr_Occurred())
520 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000521 }
522 else {
523 /* Default to current position. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000525 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000526 newsize = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000527 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000528 if (newsize == -1)
529 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000530 }
Tim Petersfb05db22002-03-11 00:24:00 +0000531
532 /* Flush the file. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000534 errno = 0;
535 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000537 if (ret != 0)
538 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000539
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000540#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000541 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000542 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000543 {
Tim Peters8f01b682002-03-12 03:04:44 +0000544 Py_off_t current; /* current file position */
Tim Petersfb05db22002-03-11 00:24:00 +0000545 HANDLE hFile;
546 int error;
547
Tim Peters8f01b682002-03-12 03:04:44 +0000548 /* current <- current file postion. */
549 if (newsizeobj == NULL)
550 current = newsize;
551 else {
Tim Petersfb05db22002-03-11 00:24:00 +0000552 Py_BEGIN_ALLOW_THREADS
553 errno = 0;
Tim Peters8f01b682002-03-12 03:04:44 +0000554 current = _portable_ftell(f->f_fp);
555 Py_END_ALLOW_THREADS
556 if (current == -1)
557 goto onioerror;
558 }
559
560 /* Move to newsize. */
561 if (current != newsize) {
562 Py_BEGIN_ALLOW_THREADS
563 errno = 0;
564 error = _portable_fseek(f->f_fp, newsize, SEEK_SET)
565 != 0;
Tim Petersfb05db22002-03-11 00:24:00 +0000566 Py_END_ALLOW_THREADS
567 if (error)
568 goto onioerror;
569 }
570
Tim Peters8f01b682002-03-12 03:04:44 +0000571 /* Truncate. Note that this may grow the file! */
572 Py_BEGIN_ALLOW_THREADS
573 errno = 0;
574 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
575 error = hFile == (HANDLE)-1;
576 if (!error) {
577 error = SetEndOfFile(hFile) == 0;
578 if (error)
579 errno = EACCES;
580 }
581 Py_END_ALLOW_THREADS
582 if (error)
583 goto onioerror;
584
585 /* Restore original file position. */
586 if (current != newsize) {
587 Py_BEGIN_ALLOW_THREADS
588 errno = 0;
589 error = _portable_fseek(f->f_fp, current, SEEK_SET)
590 != 0;
591 Py_END_ALLOW_THREADS
592 if (error)
593 goto onioerror;
594 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000595 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000596#else
597 Py_BEGIN_ALLOW_THREADS
598 errno = 0;
599 ret = ftruncate(fileno(f->f_fp), newsize);
600 Py_END_ALLOW_THREADS
601 if (ret != 0) goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000602#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000603
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000604 Py_INCREF(Py_None);
605 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000606
607onioerror:
608 PyErr_SetFromErrno(PyExc_IOError);
609 clearerr(f->f_fp);
610 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000611}
612#endif /* HAVE_FTRUNCATE */
613
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000614static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000615file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000616{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000617 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000618
Guido van Rossumd7297e61992-07-06 14:19:26 +0000619 if (f->f_fp == NULL)
620 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000621 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000622 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000623 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000625 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000627 clearerr(f->f_fp);
628 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000629 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000630#ifdef WITH_UNIVERSAL_NEWLINES
631 if (f->f_skipnextlf) {
632 int c;
633 c = GETC(f->f_fp);
634 if (c == '\n') {
635 pos++;
636 f->f_skipnextlf = 0;
637 } else if (c != EOF) ungetc(c, f->f_fp);
638 }
639#endif
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000640#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000641 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000642#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000643 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000644#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000645}
646
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000648file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000649{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000650 if (f->f_fp == NULL)
651 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000653}
654
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000655static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000656file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000657{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000658 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000659
Guido van Rossumd7297e61992-07-06 14:19:26 +0000660 if (f->f_fp == NULL)
661 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000662 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000663 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000664 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000666 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000668 clearerr(f->f_fp);
669 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000670 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 Py_INCREF(Py_None);
672 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000673}
674
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000676file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000677{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000678 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000679 if (f->f_fp == NULL)
680 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000682 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000684 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000685}
686
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000687
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000688#if BUFSIZ < 8192
689#define SMALLCHUNK 8192
690#else
691#define SMALLCHUNK BUFSIZ
692#endif
693
Guido van Rossum3c259041999-01-14 19:00:14 +0000694#if SIZEOF_INT < 4
695#define BIGCHUNK (512 * 32)
696#else
697#define BIGCHUNK (512 * 1024)
698#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000699
700static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000701new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000702{
703#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000704 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000705 struct stat st;
706 if (fstat(fileno(f->f_fp), &st) == 0) {
707 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000708 /* The following is not a bug: we really need to call lseek()
709 *and* ftell(). The reason is that some stdio libraries
710 mistakenly flush their buffer when ftell() is called and
711 the lseek() call it makes fails, thereby throwing away
712 data that cannot be recovered in any way. To avoid this,
713 we first test lseek(), and only call ftell() if lseek()
714 works. We can't use the lseek() value either, because we
715 need to take the amount of buffered data into account.
716 (Yet another reason why stdio stinks. :-) */
Jack Jansen2771b5b2001-10-10 22:03:27 +0000717#ifdef USE_GUSI2
718 pos = lseek(fileno(f->f_fp), 1L, SEEK_CUR);
719 pos = lseek(fileno(f->f_fp), -1L, SEEK_CUR);
720#else
Guido van Rossum91aaa921998-05-05 22:21:35 +0000721 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000722#endif
723 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000724 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000725 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000726 if (pos < 0)
727 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000728 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000729 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000730 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000731 }
732#endif
733 if (currentsize > SMALLCHUNK) {
734 /* Keep doubling until we reach BIGCHUNK;
735 then keep adding BIGCHUNK. */
736 if (currentsize <= BIGCHUNK)
737 return currentsize + currentsize;
738 else
739 return currentsize + BIGCHUNK;
740 }
741 return currentsize + SMALLCHUNK;
742}
743
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000745file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000746{
Guido van Rossum789a1611997-05-10 22:33:55 +0000747 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000748 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000749 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000750
Guido van Rossumd7297e61992-07-06 14:19:26 +0000751 if (f->f_fp == NULL)
752 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000753 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000754 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000755 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000756 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000757 else
758 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000759 if (buffersize > INT_MAX) {
760 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000761 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000762 return NULL;
763 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000764 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000765 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000767 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000768 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000769 Py_BEGIN_ALLOW_THREADS
770 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000771 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000772 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000773 Py_END_ALLOW_THREADS
774 if (chunksize == 0) {
775 if (!ferror(f->f_fp))
776 break;
777 PyErr_SetFromErrno(PyExc_IOError);
778 clearerr(f->f_fp);
779 Py_DECREF(v);
780 return NULL;
781 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000782 bytesread += chunksize;
783 if (bytesread < buffersize)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000784 break;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000785 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000786 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000787 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000788 return NULL;
789 }
790 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000791 if (bytesread != buffersize)
792 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000793 return v;
794}
795
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000796static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000797file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000798{
799 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000800 int ntodo;
801 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000802
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000803 if (f->f_fp == NULL)
804 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000805 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000806 return NULL;
807 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000808 while (ntodo > 0) {
809 Py_BEGIN_ALLOW_THREADS
810 errno = 0;
Jeremy Hylton8b735422002-08-14 21:01:41 +0000811 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
812 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000813 Py_END_ALLOW_THREADS
814 if (nnow == 0) {
815 if (!ferror(f->f_fp))
816 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000817 PyErr_SetFromErrno(PyExc_IOError);
818 clearerr(f->f_fp);
819 return NULL;
820 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000821 ndone += nnow;
822 ntodo -= nnow;
823 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000824 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000825}
826
Tim Peters86821b22001-01-07 21:19:34 +0000827/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000828Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000829
830Under MSVC 6:
831
Tim Peters1c733232001-01-08 04:02:07 +0000832+ MS threadsafe getc is very slow (multiple layers of function calls before+
833 after each character, to lock+unlock the stream).
834+ The stream-locking functions are MS-internal -- can't access them from user
835 code.
836+ There's nothing Tim could find in the MS C or platform SDK libraries that
837 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000838+ MS fgets locks/unlocks only once per line; it's the only hook we have.
839
840So we use fgets for speed(!), despite that it's painful.
841
842MS realloc is also slow.
843
Tim Petersf29b64d2001-01-15 06:33:19 +0000844Reports from other platforms on this method vs getc_unlocked (which MS doesn't
845have):
846 Linux a wash
847 Solaris a wash
848 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000849
Tim Petersf29b64d2001-01-15 06:33:19 +0000850CAUTION: The C std isn't clear about this: in those cases where fgets
851writes something into the buffer, can it write into any position beyond the
852required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
853known on which it does; and it would be a strange way to code fgets. Still,
854getline_via_fgets may not work correctly if it does. The std test
855test_bufio.py should fail if platform fgets() routinely writes beyond the
856trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000857**************************************************************************/
858
Tim Petersf29b64d2001-01-15 06:33:19 +0000859/* Use this routine if told to, or by default on non-get_unlocked()
860 * platforms unless told not to. Yikes! Let's spell that out:
861 * On a platform with getc_unlocked():
862 * By default, use getc_unlocked().
863 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
864 * On a platform without getc_unlocked():
865 * By default, use fgets().
866 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
867 */
868#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
869#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000870#endif
871
Tim Petersf29b64d2001-01-15 06:33:19 +0000872#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
873#undef USE_FGETS_IN_GETLINE
874#endif
875
876#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000877static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000878getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000879{
Tim Peters15b83852001-01-08 00:53:12 +0000880/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000881 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
882 * to fill this much of the buffer with a known value in order to figure out
883 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
884 * than "most" lines, we waste time filling unused buffer slots. 100 is
885 * surely adequate for most peoples' email archives, chewing over source code,
886 * etc -- "regular old text files".
887 * MAXBUFSIZE is the maximum line length that lets us get away with the less
888 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
889 * cautions about boosting that. 300 was chosen because the worst real-life
890 * text-crunching job reported on Python-Dev was a mail-log crawler where over
891 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000892 */
Tim Peters142297a2001-01-15 10:36:56 +0000893#define INITBUFSIZE 100
894#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000895 char* p; /* temp */
896 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000897 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000898 char* pvfree; /* address of next free slot */
899 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000900 size_t nfree; /* # of free buffer slots; pvend-pvfree */
901 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000902 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000903
Tim Peters15b83852001-01-08 00:53:12 +0000904 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000905 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000906 */
Tim Peters142297a2001-01-15 10:36:56 +0000907 total_v_size = INITBUFSIZE; /* start small and pray */
908 pvfree = buf;
909 for (;;) {
910 Py_BEGIN_ALLOW_THREADS
911 pvend = buf + total_v_size;
912 nfree = pvend - pvfree;
913 memset(pvfree, '\n', nfree);
914 p = fgets(pvfree, nfree, fp);
915 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000916
Tim Peters142297a2001-01-15 10:36:56 +0000917 if (p == NULL) {
918 clearerr(fp);
919 if (PyErr_CheckSignals())
920 return NULL;
921 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000922 return v;
923 }
Tim Peters142297a2001-01-15 10:36:56 +0000924 /* fgets read *something* */
925 p = memchr(pvfree, '\n', nfree);
926 if (p != NULL) {
927 /* Did the \n come from fgets or from us?
928 * Since fgets stops at the first \n, and then writes
929 * \0, if it's from fgets a \0 must be next. But if
930 * that's so, it could not have come from us, since
931 * the \n's we filled the buffer with have only more
932 * \n's to the right.
933 */
934 if (p+1 < pvend && *(p+1) == '\0') {
935 /* It's from fgets: we win! In particular,
936 * we haven't done any mallocs yet, and can
937 * build the final result on the first try.
938 */
939 ++p; /* include \n from fgets */
940 }
941 else {
942 /* Must be from us: fgets didn't fill the
943 * buffer and didn't find a newline, so it
944 * must be the last and newline-free line of
945 * the file.
946 */
947 assert(p > pvfree && *(p-1) == '\0');
948 --p; /* don't include \0 from fgets */
949 }
950 v = PyString_FromStringAndSize(buf, p - buf);
951 return v;
952 }
953 /* yuck: fgets overwrote all the newlines, i.e. the entire
954 * buffer. So this line isn't over yet, or maybe it is but
955 * we're exactly at EOF. If we haven't already, try using the
956 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +0000957 */
Tim Peters142297a2001-01-15 10:36:56 +0000958 assert(*(pvend-1) == '\0');
959 if (pvfree == buf) {
960 pvfree = pvend - 1; /* overwrite trailing null */
961 total_v_size = MAXBUFSIZE;
962 }
963 else
964 break;
Tim Peters86821b22001-01-07 21:19:34 +0000965 }
Tim Peters142297a2001-01-15 10:36:56 +0000966
967 /* The stack buffer isn't big enough; malloc a string object and read
968 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +0000969 */
Tim Petersddea2082002-03-23 10:03:50 +0000970 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +0000971 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +0000972 if (v == NULL)
973 return v;
974 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +0000975 memcpy(BUF(v), buf, MAXBUFSIZE-1);
976 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +0000977
978 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +0000979 * after setting p one beyond the end of the line. The code here is
980 * very much like the code above, except reads into v's buffer; see
981 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +0000982 */
983 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +0000984 Py_BEGIN_ALLOW_THREADS
985 pvend = BUF(v) + total_v_size;
986 nfree = pvend - pvfree;
987 memset(pvfree, '\n', nfree);
988 p = fgets(pvfree, nfree, fp);
989 Py_END_ALLOW_THREADS
990
991 if (p == NULL) {
992 clearerr(fp);
993 if (PyErr_CheckSignals()) {
994 Py_DECREF(v);
995 return NULL;
996 }
997 p = pvfree;
998 break;
999 }
Tim Peters86821b22001-01-07 21:19:34 +00001000 p = memchr(pvfree, '\n', nfree);
1001 if (p != NULL) {
1002 if (p+1 < pvend && *(p+1) == '\0') {
1003 /* \n came from fgets */
1004 ++p;
1005 break;
1006 }
1007 /* \n came from us; last line of file, no newline */
1008 assert(p > pvfree && *(p-1) == '\0');
1009 --p;
1010 break;
1011 }
1012 /* expand buffer and try again */
1013 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001014 increment = total_v_size >> 2; /* mild exponential growth */
1015 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001016 if (total_v_size > INT_MAX) {
1017 PyErr_SetString(PyExc_OverflowError,
1018 "line is longer than a Python string can hold");
1019 Py_DECREF(v);
1020 return NULL;
1021 }
1022 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1023 return NULL;
1024 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001025 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001026 }
1027 if (BUF(v) + total_v_size != p)
1028 _PyString_Resize(&v, p - BUF(v));
1029 return v;
1030#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001031#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001032}
Tim Petersf29b64d2001-01-15 06:33:19 +00001033#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001034
Guido van Rossum0bd24411991-04-04 15:21:57 +00001035/* Internal routine to get a line.
1036 Size argument interpretation:
1037 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001038 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001039*/
1040
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001041static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001042get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001043{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001044 FILE *fp = f->f_fp;
1045 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001046 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001047 size_t total_v_size; /* total # of slots in buffer */
1048 size_t used_v_size; /* # used slots in buffer */
1049 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001050 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001051#ifdef WITH_UNIVERSAL_NEWLINES
1052 int newlinetypes = f->f_newlinetypes;
1053 int skipnextlf = f->f_skipnextlf;
1054 int univ_newline = f->f_univ_newline;
1055#endif
Guido van Rossum0bd24411991-04-04 15:21:57 +00001056
Jack Jansen7b8c7542002-04-14 20:12:41 +00001057#if defined(USE_FGETS_IN_GETLINE)
1058#ifdef WITH_UNIVERSAL_NEWLINES
1059 if (n <= 0 && !univ_newline )
1060#else
Guido van Rossum86282062001-01-08 01:26:47 +00001061 if (n <= 0)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001062#endif
Tim Petersf29b64d2001-01-15 06:33:19 +00001063 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001064#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001065 total_v_size = n > 0 ? n : 100;
1066 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001067 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001068 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001069 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001070 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001071
Guido van Rossumce5ba841991-03-06 13:06:18 +00001072 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001073 Py_BEGIN_ALLOW_THREADS
1074 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001075#ifdef WITH_UNIVERSAL_NEWLINES
1076 if (univ_newline) {
1077 c = 'x'; /* Shut up gcc warning */
1078 while ( buf != end && (c = GETC(fp)) != EOF ) {
1079 if (skipnextlf ) {
1080 skipnextlf = 0;
1081 if (c == '\n') {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001082 /* Seeing a \n here with
1083 * skipnextlf true means we
1084 * saw a \r before.
1085 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001086 newlinetypes |= NEWLINE_CRLF;
1087 c = GETC(fp);
1088 if (c == EOF) break;
1089 } else {
1090 newlinetypes |= NEWLINE_CR;
1091 }
1092 }
1093 if (c == '\r') {
1094 skipnextlf = 1;
1095 c = '\n';
1096 } else if ( c == '\n')
1097 newlinetypes |= NEWLINE_LF;
1098 *buf++ = c;
1099 if (c == '\n') break;
1100 }
1101 if ( c == EOF && skipnextlf )
1102 newlinetypes |= NEWLINE_CR;
1103 } else /* If not universal newlines use the normal loop */
1104#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001105 while ((c = GETC(fp)) != EOF &&
1106 (*buf++ = c) != '\n' &&
1107 buf != end)
1108 ;
1109 FUNLOCKFILE(fp);
1110 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001111#ifdef WITH_UNIVERSAL_NEWLINES
1112 f->f_newlinetypes = newlinetypes;
1113 f->f_skipnextlf = skipnextlf;
1114#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001115 if (c == '\n')
1116 break;
1117 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001118 if (ferror(fp)) {
1119 PyErr_SetFromErrno(PyExc_IOError);
1120 clearerr(fp);
1121 Py_DECREF(v);
1122 return NULL;
1123 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001124 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001125 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001126 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001127 return NULL;
1128 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001129 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001130 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001131 /* Must be because buf == end */
1132 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001133 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001134 used_v_size = total_v_size;
1135 increment = total_v_size >> 2; /* mild exponential growth */
1136 total_v_size += increment;
1137 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001138 PyErr_SetString(PyExc_OverflowError,
1139 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001140 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001141 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001142 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001143 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001144 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001145 buf = BUF(v) + used_v_size;
1146 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001147 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001148
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001149 used_v_size = buf - BUF(v);
1150 if (used_v_size != total_v_size)
1151 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001152 return v;
1153}
1154
Guido van Rossum0bd24411991-04-04 15:21:57 +00001155/* External C interface */
1156
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001157PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001158PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001159{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001160 PyObject *result;
1161
Guido van Rossum3165fe61992-09-25 21:59:05 +00001162 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001163 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001164 return NULL;
1165 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001166
1167 if (PyFile_Check(f)) {
1168 if (((PyFileObject*)f)->f_fp == NULL)
1169 return err_closed();
1170 result = get_line((PyFileObject *)f, n);
1171 }
1172 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001173 PyObject *reader;
1174 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001176 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001177 if (reader == NULL)
1178 return NULL;
1179 if (n <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001180 args = Py_BuildValue("()");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001181 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001182 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001183 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001184 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001185 return NULL;
1186 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001187 result = PyEval_CallObject(reader, args);
1188 Py_DECREF(reader);
1189 Py_DECREF(args);
1190 if (result != NULL && !PyString_Check(result)) {
1191 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001192 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001193 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001194 "object.readline() returned non-string");
1195 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001196 }
1197
1198 if (n < 0 && result != NULL && PyString_Check(result)) {
1199 char *s = PyString_AS_STRING(result);
1200 int len = PyString_GET_SIZE(result);
1201 if (len == 0) {
1202 Py_DECREF(result);
1203 result = NULL;
1204 PyErr_SetString(PyExc_EOFError,
1205 "EOF when reading a line");
1206 }
1207 else if (s[len-1] == '\n') {
1208 if (result->ob_refcnt == 1)
1209 _PyString_Resize(&result, len-1);
1210 else {
1211 PyObject *v;
1212 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001213 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001214 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001215 }
1216 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001217 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001218 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001219}
1220
1221/* Python method */
1222
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001223static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001224file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001225{
Guido van Rossum789a1611997-05-10 22:33:55 +00001226 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001227
Guido van Rossumd7297e61992-07-06 14:19:26 +00001228 if (f->f_fp == NULL)
1229 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001230 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001231 return NULL;
1232 if (n == 0)
1233 return PyString_FromString("");
1234 if (n < 0)
1235 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001236 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001237}
1238
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001239static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001240file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001241{
Guido van Rossum789a1611997-05-10 22:33:55 +00001242 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001243 PyObject *list;
1244 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001245 char small_buffer[SMALLCHUNK];
1246 char *buffer = small_buffer;
1247 size_t buffersize = SMALLCHUNK;
1248 PyObject *big_buffer = NULL;
1249 size_t nfilled = 0;
1250 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001251 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001252 char *p, *q, *end;
1253 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001254 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001255
Guido van Rossumd7297e61992-07-06 14:19:26 +00001256 if (f->f_fp == NULL)
1257 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001258 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001259 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001260 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001261 return NULL;
1262 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001263 if (shortread)
1264 nread = 0;
1265 else {
1266 Py_BEGIN_ALLOW_THREADS
1267 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001268 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001269 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001270 Py_END_ALLOW_THREADS
1271 shortread = (nread < buffersize-nfilled);
1272 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001273 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001274 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001275 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001276 break;
1277 PyErr_SetFromErrno(PyExc_IOError);
1278 clearerr(f->f_fp);
1279 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001280 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001281 list = NULL;
1282 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001283 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001284 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001285 p = memchr(buffer+nfilled, '\n', nread);
1286 if (p == NULL) {
1287 /* Need a larger buffer to fit this line */
1288 nfilled += nread;
1289 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001290 if (buffersize > INT_MAX) {
1291 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001292 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001293 goto error;
1294 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001295 if (big_buffer == NULL) {
1296 /* Create the big buffer */
1297 big_buffer = PyString_FromStringAndSize(
1298 NULL, buffersize);
1299 if (big_buffer == NULL)
1300 goto error;
1301 buffer = PyString_AS_STRING(big_buffer);
1302 memcpy(buffer, small_buffer, nfilled);
1303 }
1304 else {
1305 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001306 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1307 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001308 buffer = PyString_AS_STRING(big_buffer);
1309 }
1310 continue;
1311 }
1312 end = buffer+nfilled+nread;
1313 q = buffer;
1314 do {
1315 /* Process complete lines */
1316 p++;
1317 line = PyString_FromStringAndSize(q, p-q);
1318 if (line == NULL)
1319 goto error;
1320 err = PyList_Append(list, line);
1321 Py_DECREF(line);
1322 if (err != 0)
1323 goto error;
1324 q = p;
1325 p = memchr(q, '\n', end-q);
1326 } while (p != NULL);
1327 /* Move the remaining incomplete line to the start */
1328 nfilled = end-q;
1329 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001330 if (sizehint > 0)
1331 if (totalread >= (size_t)sizehint)
1332 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001333 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001334 if (nfilled != 0) {
1335 /* Partial last line */
1336 line = PyString_FromStringAndSize(buffer, nfilled);
1337 if (line == NULL)
1338 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001339 if (sizehint > 0) {
1340 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001341 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001342 if (rest == NULL) {
1343 Py_DECREF(line);
1344 goto error;
1345 }
1346 PyString_Concat(&line, rest);
1347 Py_DECREF(rest);
1348 if (line == NULL)
1349 goto error;
1350 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001351 err = PyList_Append(list, line);
1352 Py_DECREF(line);
1353 if (err != 0)
1354 goto error;
1355 }
1356 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001357 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001358 return list;
1359}
1360
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001361static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001362file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001363{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001364 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001365 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001366 if (f->f_fp == NULL)
1367 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001368 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001369 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001370 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001371 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001372 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001373 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001374 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001375 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001377 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001378 return NULL;
1379 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001380 Py_INCREF(Py_None);
1381 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001382}
1383
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001384static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001385file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001386{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001387#define CHUNKSIZE 1000
1388 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001389 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001390 PyObject *result;
1391 int i, j, index, len, nwritten, islist;
1392
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001393 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001394 if (f->f_fp == NULL)
1395 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001396
1397 result = NULL;
1398 list = NULL;
1399 islist = PyList_Check(seq);
1400 if (islist)
1401 it = NULL;
1402 else {
1403 it = PyObject_GetIter(seq);
1404 if (it == NULL) {
1405 PyErr_SetString(PyExc_TypeError,
1406 "writelines() requires an iterable argument");
1407 return NULL;
1408 }
1409 /* From here on, fail by going to error, to reclaim "it". */
1410 list = PyList_New(CHUNKSIZE);
1411 if (list == NULL)
1412 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001413 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001414
1415 /* Strategy: slurp CHUNKSIZE lines into a private list,
1416 checking that they are all strings, then write that list
1417 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001418 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001419 if (islist) {
1420 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001421 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001422 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001423 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001424 j = PyList_GET_SIZE(list);
1425 }
1426 else {
1427 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001428 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001429 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001430 if (PyErr_Occurred())
1431 goto error;
1432 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001433 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001434 PyList_SetItem(list, j, line);
1435 }
1436 }
1437 if (j == 0)
1438 break;
1439
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001440 /* Check that all entries are indeed strings. If not,
1441 apply the same rules as for file.write() and
1442 convert the results to strings. This is slow, but
1443 seems to be the only way since all conversion APIs
1444 could potentially execute Python code. */
1445 for (i = 0; i < j; i++) {
1446 PyObject *v = PyList_GET_ITEM(list, i);
1447 if (!PyString_Check(v)) {
1448 const char *buffer;
1449 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001450 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001451 PyObject_AsReadBuffer(v,
1452 (const void**)&buffer,
1453 &len)) ||
1454 PyObject_AsCharBuffer(v,
1455 &buffer,
1456 &len))) {
1457 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001458 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001459 goto error;
1460 }
1461 line = PyString_FromStringAndSize(buffer,
1462 len);
1463 if (line == NULL)
1464 goto error;
1465 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001466 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001467 }
1468 }
1469
1470 /* Since we are releasing the global lock, the
1471 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001472 Py_BEGIN_ALLOW_THREADS
1473 f->f_softspace = 0;
1474 errno = 0;
1475 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001476 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001477 len = PyString_GET_SIZE(line);
1478 nwritten = fwrite(PyString_AS_STRING(line),
1479 1, len, f->f_fp);
1480 if (nwritten != len) {
1481 Py_BLOCK_THREADS
1482 PyErr_SetFromErrno(PyExc_IOError);
1483 clearerr(f->f_fp);
1484 goto error;
1485 }
1486 }
1487 Py_END_ALLOW_THREADS
1488
1489 if (j < CHUNKSIZE)
1490 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001491 }
1492
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001493 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001494 result = Py_None;
1495 error:
1496 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001497 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001498 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001499#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001500}
1501
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001502static PyObject *
1503file_getiter(PyFileObject *f)
1504{
1505 if (f->f_fp == NULL)
1506 return err_closed();
1507 Py_INCREF(f);
1508 return (PyObject *)f;
1509}
1510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001511PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001512"readline([size]) -> next line from the file, as a string.\n"
1513"\n"
1514"Retain newline. A non-negative size argument limits the maximum\n"
1515"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001516"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001518PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001519"read([size]) -> read at most size bytes, returned as a string.\n"
1520"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001521"If the size argument is negative or omitted, read until EOF is reached.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001522
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001523PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001524"write(str) -> None. Write string str to file.\n"
1525"\n"
1526"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001527"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001529PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001530"fileno() -> integer \"file descriptor\".\n"
1531"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001532"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001533
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001534PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001535"seek(offset[, whence]) -> None. Move to new file position.\n"
1536"\n"
1537"Argument offset is a byte count. Optional argument whence defaults to\n"
1538"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1539"(move relative to current position, positive or negative), and 2 (move\n"
1540"relative to end of file, usually negative, although many platforms allow\n"
1541"seeking beyond the end of a file).\n"
1542"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001543"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001544
Guido van Rossumd7047b31995-01-02 19:07:15 +00001545#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001546PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001547"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1548"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001550#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001552PyDoc_STRVAR(tell_doc,
1553"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001555PyDoc_STRVAR(readinto_doc,
1556"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001558PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001559"readlines([size]) -> list of strings, each a line from the file.\n"
1560"\n"
1561"Call readline() repeatedly and return a list of the lines so read.\n"
1562"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001563"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001565PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001566"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001567"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001568"For backward compatibility. File objects now include the performance\n"
1569"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001571PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001572"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001573"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001574"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001575"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001577PyDoc_STRVAR(flush_doc,
1578"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001580PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001581"close() -> None or (perhaps) an integer. Close the file.\n"
1582"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001583"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001584"further I/O operations. close() may be called more than once without\n"
1585"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001586"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001588PyDoc_STRVAR(isatty_doc,
1589"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001590
1591static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001592 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1593 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1594 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1595 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1596 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001597#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001598 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001599#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001600 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1601 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1602 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1603 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1604 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1605 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1606 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1607 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1608 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001609};
1610
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001611#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001612
Guido van Rossum6f799372001-09-20 20:46:19 +00001613static PyMemberDef file_memberlist[] = {
1614 {"softspace", T_INT, OFF(f_softspace), 0,
1615 "flag indicating that a space needs to be printed; used by print"},
1616 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001617 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001618 {"name", T_OBJECT, OFF(f_name), RO,
1619 "file name"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001620 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001621 {NULL} /* Sentinel */
1622};
1623
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001624static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001626{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001627 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001628}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001629#ifdef WITH_UNIVERSAL_NEWLINES
1630static PyObject *
1631get_newlines(PyFileObject *f, void *closure)
1632{
1633 switch (f->f_newlinetypes) {
1634 case NEWLINE_UNKNOWN:
1635 Py_INCREF(Py_None);
1636 return Py_None;
1637 case NEWLINE_CR:
1638 return PyString_FromString("\r");
1639 case NEWLINE_LF:
1640 return PyString_FromString("\n");
1641 case NEWLINE_CR|NEWLINE_LF:
1642 return Py_BuildValue("(ss)", "\r", "\n");
1643 case NEWLINE_CRLF:
1644 return PyString_FromString("\r\n");
1645 case NEWLINE_CR|NEWLINE_CRLF:
1646 return Py_BuildValue("(ss)", "\r", "\r\n");
1647 case NEWLINE_LF|NEWLINE_CRLF:
1648 return Py_BuildValue("(ss)", "\n", "\r\n");
1649 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1650 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1651 default:
Jeremy Hylton8b735422002-08-14 21:01:41 +00001652 PyErr_Format(PyExc_SystemError,
1653 "Unknown newlines value 0x%x\n",
1654 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001655 return NULL;
1656 }
1657}
1658#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +00001659
Guido van Rossum32d34c82001-09-20 21:45:26 +00001660static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001661 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001662#ifdef WITH_UNIVERSAL_NEWLINES
Jeremy Hylton8b735422002-08-14 21:01:41 +00001663 {"newlines", (getter)get_newlines, NULL,
1664 "end-of-line convention used in this file"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001665#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 {0},
1667};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001668
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001669static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001670drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001671{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001672 if (f->f_buf != NULL) {
1673 PyMem_Free(f->f_buf);
1674 f->f_buf = NULL;
1675 }
Guido van Rossum65967252001-04-21 13:20:18 +00001676}
1677
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001678/* Make sure that file has a readahead buffer with at least one byte
1679 (unless at EOF) and no more than bufsize. Returns negative value on
1680 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001681static int
1682readahead(PyFileObject *f, int bufsize)
1683{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001684 int chunksize;
1685
1686 if (f->f_buf != NULL) {
1687 if( (f->f_bufend - f->f_bufptr) >= 1)
1688 return 0;
1689 else
1690 drop_readahead(f);
1691 }
1692 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1693 return -1;
1694 }
1695 Py_BEGIN_ALLOW_THREADS
1696 errno = 0;
1697 chunksize = Py_UniversalNewlineFread(
1698 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1699 Py_END_ALLOW_THREADS
1700 if (chunksize == 0) {
1701 if (ferror(f->f_fp)) {
1702 PyErr_SetFromErrno(PyExc_IOError);
1703 clearerr(f->f_fp);
1704 drop_readahead(f);
1705 return -1;
1706 }
1707 }
1708 f->f_bufptr = f->f_buf;
1709 f->f_bufend = f->f_buf + chunksize;
1710 return 0;
1711}
1712
1713/* Used by file_iternext. The returned string will start with 'skip'
1714 uninitialized bytes followed by the remainder of the line. Don't be
1715 horrified by the recursive call: maximum recursion depth is limited by
1716 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1717
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001718static PyStringObject *
1719readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1720{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001721 PyStringObject* s;
1722 char *bufptr;
1723 char *buf;
1724 int len;
1725
1726 if (f->f_buf == NULL)
1727 if (readahead(f, bufsize) < 0)
1728 return NULL;
1729
1730 len = f->f_bufend - f->f_bufptr;
1731 if (len == 0)
1732 return (PyStringObject *)
1733 PyString_FromStringAndSize(NULL, skip);
1734 bufptr = memchr(f->f_bufptr, '\n', len);
1735 if (bufptr != NULL) {
1736 bufptr++; /* Count the '\n' */
1737 len = bufptr - f->f_bufptr;
1738 s = (PyStringObject *)
1739 PyString_FromStringAndSize(NULL, skip+len);
1740 if (s == NULL)
1741 return NULL;
1742 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1743 f->f_bufptr = bufptr;
1744 if (bufptr == f->f_bufend)
1745 drop_readahead(f);
1746 } else {
1747 bufptr = f->f_bufptr;
1748 buf = f->f_buf;
1749 f->f_buf = NULL; /* Force new readahead buffer */
1750 s = readahead_get_line_skip(
1751 f, skip+len, bufsize + (bufsize>>2) );
1752 if (s == NULL) {
1753 PyMem_Free(buf);
1754 return NULL;
1755 }
1756 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1757 PyMem_Free(buf);
1758 }
1759 return s;
1760}
1761
1762/* A larger buffer size may actually decrease performance. */
1763#define READAHEAD_BUFSIZE 8192
1764
1765static PyObject *
1766file_iternext(PyFileObject *f)
1767{
1768 PyStringObject* l;
1769
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001770 if (f->f_fp == NULL)
1771 return err_closed();
1772
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001773 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