blob: 1cc6def62cd6fadb52d20e880265e7e9b8cdd7f1 [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öwis5467d4c2003-05-10 07:10:12 +0000119 Py_DECREF(f->f_encoding);
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000120#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000121 if (wname)
122 f->f_name = PyUnicode_FromObject(wname);
123 else
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000124#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000125 f->f_name = PyString_FromString(name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000127
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000128 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000129 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000130 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000131 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000132#ifdef WITH_UNIVERSAL_NEWLINES
133 f->f_univ_newline = (strchr(mode, 'U') != NULL);
134 f->f_newlinetypes = NEWLINE_UNKNOWN;
135 f->f_skipnextlf = 0;
136#endif
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000137 Py_INCREF(Py_None);
138 f->f_encoding = Py_None;
139
Tim Peters59c9a642001-09-13 05:38:56 +0000140 if (f->f_name == NULL || f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000143 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145}
146
Tim Peters59c9a642001-09-13 05:38:56 +0000147static PyObject *
148open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Tim Peters59c9a642001-09-13 05:38:56 +0000150 assert(f != NULL);
151 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000152#ifdef MS_WINDOWS
153 /* windows ignores the passed name in order to support Unicode */
154 assert(f->f_name != NULL);
155#else
Tim Peters59c9a642001-09-13 05:38:56 +0000156 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000157#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000158 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000159 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000160
Tim Peters8fa45672001-09-13 21:01:29 +0000161 /* rexec.py can't stop a user from getting the file() constructor --
162 all they have to do is get *any* file object f, and then do
163 type(f). Here we prevent them from doing damage with it. */
164 if (PyEval_GetRestricted()) {
165 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000166 "file() constructor not accessible in restricted mode");
Tim Peters8fa45672001-09-13 21:01:29 +0000167 return NULL;
168 }
Tim Petersa27a1502001-11-09 20:59:14 +0000169 errno = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000170#ifdef HAVE_FOPENRF
Guido van Rossuma08095a1991-02-13 23:25:27 +0000171 if (*mode == '*') {
172 FILE *fopenRF();
173 f->f_fp = fopenRF(name, mode+1);
174 }
175 else
176#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000177 {
Jack Jansen7b8c7542002-04-14 20:12:41 +0000178#ifdef WITH_UNIVERSAL_NEWLINES
179 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
180 mode = "rb";
181#else
182 /* Compatibility: specifying U in a Python without universal
183 ** newlines is allowed, and the file is opened as a normal text
184 ** file.
185 */
186 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0)
187 mode = "r";
188#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000189#ifdef MS_WINDOWS
190 if (PyUnicode_Check(f->f_name)) {
191 PyObject *wmode;
192 wmode = PyUnicode_DecodeASCII(mode, strlen(mode), NULL);
193 if (f->f_name && wmode) {
194 Py_BEGIN_ALLOW_THREADS
195 /* PyUnicode_AS_UNICODE OK without thread
196 lock as it is a simple dereference. */
197 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
198 PyUnicode_AS_UNICODE(wmode));
199 Py_END_ALLOW_THREADS
200 }
201 Py_XDECREF(wmode);
202 }
203#endif
204 if (NULL == f->f_fp && NULL != name) {
205 Py_BEGIN_ALLOW_THREADS
206 f->f_fp = fopen(name, mode);
207 Py_END_ALLOW_THREADS
208 }
Guido van Rossumff4949e1992-08-05 19:58:53 +0000209 }
Guido van Rossuma08095a1991-02-13 23:25:27 +0000210 if (f->f_fp == NULL) {
Jack Jansene08dea191995-04-23 22:12:47 +0000211#ifdef NO_FOPEN_ERRNO
Jack Jansenb3be2162001-11-30 14:16:36 +0000212 /* Metroworks only, wich does not always sets errno */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000213 if (errno == 0) {
Jack Jansenb3be2162001-11-30 14:16:36 +0000214 PyObject *v;
215 v = Py_BuildValue("(is)", 0, "Cannot open file");
216 if (v != NULL) {
217 PyErr_SetObject(PyExc_IOError, v);
218 Py_DECREF(v);
219 }
Jack Jansene08dea191995-04-23 22:12:47 +0000220 return NULL;
221 }
222#endif
Tim Peters2ea91112002-04-08 04:13:12 +0000223#ifdef _MSC_VER
224 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
225 * across all Windows flavors. When it sets EINVAL varies
226 * across Windows flavors, the exact conditions aren't
227 * documented, and the answer lies in the OS's implementation
228 * of Win32's CreateFile function (whose source is secret).
229 * Seems the best we can do is map EINVAL to ENOENT.
230 */
231 if (errno == 0) /* bad mode string */
232 errno = EINVAL;
233 else if (errno == EINVAL) /* unknown, but not a mode string */
234 errno = ENOENT;
235#endif
Jeremy Hylton41c83212001-11-09 16:17:24 +0000236 if (errno == EINVAL)
Tim Peters2ea91112002-04-08 04:13:12 +0000237 PyErr_Format(PyExc_IOError, "invalid mode: %s",
Jeremy Hylton41c83212001-11-09 16:17:24 +0000238 mode);
239 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000240#ifdef MS_WINDOWS
241 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
242#else
Jeremy Hylton41c83212001-11-09 16:17:24 +0000243 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000244#endif /* MS_WINDOWS */
Tim Peters59c9a642001-09-13 05:38:56 +0000245 f = NULL;
246 }
Tim Peters2ea91112002-04-08 04:13:12 +0000247 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000248 f = dircheck(f);
Tim Peters59c9a642001-09-13 05:38:56 +0000249 return (PyObject *)f;
250}
251
252PyObject *
253PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
254{
Tim Peters44410012001-09-14 03:26:08 +0000255 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
256 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000257 if (f != NULL) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000258 if (fill_file_fields(f, fp, name, mode, close, NULL) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000259 Py_DECREF(f);
260 f = NULL;
261 }
262 }
263 return (PyObject *) f;
264}
265
266PyObject *
267PyFile_FromString(char *name, char *mode)
268{
269 extern int fclose(FILE *);
270 PyFileObject *f;
271
272 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
273 if (f != NULL) {
274 if (open_the_file(f, name, mode) == NULL) {
275 Py_DECREF(f);
276 f = NULL;
277 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000278 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280}
281
Guido van Rossumb6775db1994-08-01 11:34:53 +0000282void
Fred Drakefd99de62000-07-09 05:02:18 +0000283PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000284{
285 if (bufsize >= 0) {
286#ifdef HAVE_SETVBUF
287 int type;
288 switch (bufsize) {
289 case 0:
290 type = _IONBF;
291 break;
292 case 1:
293 type = _IOLBF;
294 bufsize = BUFSIZ;
295 break;
296 default:
297 type = _IOFBF;
298 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
300 type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000301#else /* !HAVE_SETVBUF */
302 if (bufsize <= 1)
303 setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
304#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305 }
306}
307
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000308/* Set the encoding used to output Unicode strings.
309 Returh 1 on success, 0 on failure. */
310
311int
312PyFile_SetEncoding(PyObject *f, const char *enc)
313{
314 PyFileObject *file = (PyFileObject*)f;
315 PyObject *str = PyString_FromString(enc);
316 if (!str)
317 return 0;
318 Py_DECREF(file->f_encoding);
319 file->f_encoding = str;
320 return 1;
321}
322
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000324err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000325{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000327 return NULL;
328}
329
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000330static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000331
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332/* Methods */
333
334static void
Fred Drakefd99de62000-07-09 05:02:18 +0000335file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000337 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 Py_BEGIN_ALLOW_THREADS
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000339 (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000341 }
Tim Peters44410012001-09-14 03:26:08 +0000342 Py_XDECREF(f->f_name);
343 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000344 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000345 drop_readahead(f);
Guido van Rossum9475a232001-10-05 20:51:39 +0000346 f->ob_type->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347}
348
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000349static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000350file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000352 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000353#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000354 PyObject *ret = NULL;
355 PyObject *name;
356 name = PyUnicode_AsUnicodeEscapeString(f->f_name);
357 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
358 f->f_fp == NULL ? "closed" : "open",
359 PyString_AsString(name),
360 PyString_AsString(f->f_mode),
361 f);
362 Py_XDECREF(name);
363 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000364#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000365 } else {
366 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000367 f->f_fp == NULL ? "closed" : "open",
368 PyString_AsString(f->f_name),
369 PyString_AsString(f->f_mode),
370 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000371 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000375file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000377 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000379 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000381 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000382 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000383 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000384 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385 f->f_fp = NULL;
386 }
Guido van Rossumfebd5511992-03-04 16:39:24 +0000387 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000389 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000390 return PyInt_FromLong((long)sts);
391 Py_INCREF(Py_None);
392 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393}
394
Trent Mickf29f47b2000-08-11 19:02:59 +0000395
Guido van Rossumb8552162001-09-05 14:58:11 +0000396/* Our very own off_t-like type, 64-bit if possible */
397#if !defined(HAVE_LARGEFILE_SUPPORT)
398typedef off_t Py_off_t;
399#elif SIZEOF_OFF_T >= 8
400typedef off_t Py_off_t;
401#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000402typedef fpos_t Py_off_t;
403#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000404#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000405#endif
406
407
Trent Mickf29f47b2000-08-11 19:02:59 +0000408/* a portable fseek() function
409 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000410static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000411_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000412{
Guido van Rossumb8552162001-09-05 14:58:11 +0000413#if !defined(HAVE_LARGEFILE_SUPPORT)
414 return fseek(fp, offset, whence);
415#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000416 return fseeko(fp, offset, whence);
417#elif defined(HAVE_FSEEK64)
418 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000419#elif defined(__BEOS__)
420 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000421#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000422 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
423 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000424 fpos_t pos;
425 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000426 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000427#ifdef MS_WINDOWS
428 fflush(fp);
429 if (_lseeki64(fileno(fp), 0, 2) == -1)
430 return -1;
431#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000432 if (fseek(fp, 0, SEEK_END) != 0)
433 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000434#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000435 /* fall through */
436 case SEEK_CUR:
437 if (fgetpos(fp, &pos) != 0)
438 return -1;
439 offset += pos;
440 break;
441 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000442 }
443 return fsetpos(fp, &offset);
444#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000445#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000446#endif
447}
448
449
450/* a portable ftell() function
451 Return -1 on failure with errno set appropriately, current file
452 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000453static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000454_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000455{
Guido van Rossumb8552162001-09-05 14:58:11 +0000456#if !defined(HAVE_LARGEFILE_SUPPORT)
457 return ftell(fp);
458#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
459 return ftello(fp);
460#elif defined(HAVE_FTELL64)
461 return ftell64(fp);
462#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000463 fpos_t pos;
464 if (fgetpos(fp, &pos) != 0)
465 return -1;
466 return pos;
467#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000468#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000469#endif
470}
471
472
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000474file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000476 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000477 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000478 Py_off_t offset;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000479 PyObject *offobj;
Tim Peters86821b22001-01-07 21:19:34 +0000480
Guido van Rossumd7297e61992-07-06 14:19:26 +0000481 if (f->f_fp == NULL)
482 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000483 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000484 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000485 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000486 return NULL;
487#if !defined(HAVE_LARGEFILE_SUPPORT)
488 offset = PyInt_AsLong(offobj);
489#else
490 offset = PyLong_Check(offobj) ?
491 PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
492#endif
493 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000494 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000495
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000497 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000498 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000500
Guido van Rossumff4949e1992-08-05 19:58:53 +0000501 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000503 clearerr(f->f_fp);
504 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000505 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000506#ifdef WITH_UNIVERSAL_NEWLINES
507 f->f_skipnextlf = 0;
508#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509 Py_INCREF(Py_None);
510 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000511}
512
Trent Mickf29f47b2000-08-11 19:02:59 +0000513
Guido van Rossumd7047b31995-01-02 19:07:15 +0000514#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000515static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000516file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000517{
Guido van Rossumd7047b31995-01-02 19:07:15 +0000518 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000519 Py_off_t newsize;
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000520 PyObject *newsizeobj;
Tim Peters86821b22001-01-07 21:19:34 +0000521
Guido van Rossumd7047b31995-01-02 19:07:15 +0000522 if (f->f_fp == NULL)
523 return err_closed();
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000524 newsizeobj = NULL;
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000525 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000526 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000527
528 /* Set newsize to current postion if newsizeobj NULL, else to the
529 specified value. */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000530 if (newsizeobj != NULL) {
531#if !defined(HAVE_LARGEFILE_SUPPORT)
532 newsize = PyInt_AsLong(newsizeobj);
533#else
534 newsize = PyLong_Check(newsizeobj) ?
535 PyLong_AsLongLong(newsizeobj) :
536 PyInt_AsLong(newsizeobj);
537#endif
538 if (PyErr_Occurred())
539 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000540 }
541 else {
542 /* Default to current position. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000544 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000545 newsize = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000546 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000547 if (newsize == -1)
548 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000549 }
Tim Petersfb05db22002-03-11 00:24:00 +0000550
551 /* Flush the file. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000553 errno = 0;
554 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000556 if (ret != 0)
557 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000558
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000559#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000560 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000561 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000562 {
Tim Peters8f01b682002-03-12 03:04:44 +0000563 Py_off_t current; /* current file position */
Tim Petersfb05db22002-03-11 00:24:00 +0000564 HANDLE hFile;
565 int error;
566
Tim Peters8f01b682002-03-12 03:04:44 +0000567 /* current <- current file postion. */
568 if (newsizeobj == NULL)
569 current = newsize;
570 else {
Tim Petersfb05db22002-03-11 00:24:00 +0000571 Py_BEGIN_ALLOW_THREADS
572 errno = 0;
Tim Peters8f01b682002-03-12 03:04:44 +0000573 current = _portable_ftell(f->f_fp);
574 Py_END_ALLOW_THREADS
575 if (current == -1)
576 goto onioerror;
577 }
578
579 /* Move to newsize. */
580 if (current != newsize) {
581 Py_BEGIN_ALLOW_THREADS
582 errno = 0;
583 error = _portable_fseek(f->f_fp, newsize, SEEK_SET)
584 != 0;
Tim Petersfb05db22002-03-11 00:24:00 +0000585 Py_END_ALLOW_THREADS
586 if (error)
587 goto onioerror;
588 }
589
Tim Peters8f01b682002-03-12 03:04:44 +0000590 /* Truncate. Note that this may grow the file! */
591 Py_BEGIN_ALLOW_THREADS
592 errno = 0;
593 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
594 error = hFile == (HANDLE)-1;
595 if (!error) {
596 error = SetEndOfFile(hFile) == 0;
597 if (error)
598 errno = EACCES;
599 }
600 Py_END_ALLOW_THREADS
601 if (error)
602 goto onioerror;
603
604 /* Restore original file position. */
605 if (current != newsize) {
606 Py_BEGIN_ALLOW_THREADS
607 errno = 0;
608 error = _portable_fseek(f->f_fp, current, SEEK_SET)
609 != 0;
610 Py_END_ALLOW_THREADS
611 if (error)
612 goto onioerror;
613 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000614 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000615#else
616 Py_BEGIN_ALLOW_THREADS
617 errno = 0;
618 ret = ftruncate(fileno(f->f_fp), newsize);
619 Py_END_ALLOW_THREADS
620 if (ret != 0) goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000621#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000622
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623 Py_INCREF(Py_None);
624 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000625
626onioerror:
627 PyErr_SetFromErrno(PyExc_IOError);
628 clearerr(f->f_fp);
629 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000630}
631#endif /* HAVE_FTRUNCATE */
632
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000634file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000635{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000636 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000637
Guido van Rossumd7297e61992-07-06 14:19:26 +0000638 if (f->f_fp == NULL)
639 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000641 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000642 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000644 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000645 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000646 clearerr(f->f_fp);
647 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000648 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000649#ifdef WITH_UNIVERSAL_NEWLINES
650 if (f->f_skipnextlf) {
651 int c;
652 c = GETC(f->f_fp);
653 if (c == '\n') {
654 pos++;
655 f->f_skipnextlf = 0;
656 } else if (c != EOF) ungetc(c, f->f_fp);
657 }
658#endif
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000659#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000660 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000661#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000662 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000663#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000667file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000668{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000669 if (f->f_fp == NULL)
670 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000672}
673
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000675file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000676{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000677 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000678
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 Rossumce5ba841991-03-06 13:06:18 +0000682 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000683 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000684 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000685 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000687 clearerr(f->f_fp);
688 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000689 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000690 Py_INCREF(Py_None);
691 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000692}
693
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000695file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000696{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000697 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000698 if (f->f_fp == NULL)
699 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000700 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000701 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000702 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000703 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000704}
705
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000706
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000707#if BUFSIZ < 8192
708#define SMALLCHUNK 8192
709#else
710#define SMALLCHUNK BUFSIZ
711#endif
712
Guido van Rossum3c259041999-01-14 19:00:14 +0000713#if SIZEOF_INT < 4
714#define BIGCHUNK (512 * 32)
715#else
716#define BIGCHUNK (512 * 1024)
717#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000718
719static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000720new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000721{
722#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000723 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000724 struct stat st;
725 if (fstat(fileno(f->f_fp), &st) == 0) {
726 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000727 /* The following is not a bug: we really need to call lseek()
728 *and* ftell(). The reason is that some stdio libraries
729 mistakenly flush their buffer when ftell() is called and
730 the lseek() call it makes fails, thereby throwing away
731 data that cannot be recovered in any way. To avoid this,
732 we first test lseek(), and only call ftell() if lseek()
733 works. We can't use the lseek() value either, because we
734 need to take the amount of buffered data into account.
735 (Yet another reason why stdio stinks. :-) */
Jack Jansen2771b5b2001-10-10 22:03:27 +0000736#ifdef USE_GUSI2
737 pos = lseek(fileno(f->f_fp), 1L, SEEK_CUR);
738 pos = lseek(fileno(f->f_fp), -1L, SEEK_CUR);
739#else
Guido van Rossum91aaa921998-05-05 22:21:35 +0000740 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000741#endif
742 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000743 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000744 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000745 if (pos < 0)
746 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000747 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000748 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000749 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000750 }
751#endif
752 if (currentsize > SMALLCHUNK) {
753 /* Keep doubling until we reach BIGCHUNK;
754 then keep adding BIGCHUNK. */
755 if (currentsize <= BIGCHUNK)
756 return currentsize + currentsize;
757 else
758 return currentsize + BIGCHUNK;
759 }
760 return currentsize + SMALLCHUNK;
761}
762
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000763#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
764#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
765#else
766#ifdef EWOULDBLOCK
767#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
768#else
769#ifdef EAGAIN
770#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
771#else
772#define BLOCKED_ERRNO(x) 0
773#endif
774#endif
775#endif
776
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000777static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000778file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000779{
Guido van Rossum789a1611997-05-10 22:33:55 +0000780 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000781 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000782 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000783
Guido van Rossumd7297e61992-07-06 14:19:26 +0000784 if (f->f_fp == NULL)
785 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +0000786 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000787 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000788 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000789 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000790 else
791 buffersize = bytesrequested;
Trent Mickf29f47b2000-08-11 19:02:59 +0000792 if (buffersize > INT_MAX) {
793 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000794 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000795 return NULL;
796 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000797 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000798 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000800 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000801 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000802 Py_BEGIN_ALLOW_THREADS
803 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000804 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000805 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000806 Py_END_ALLOW_THREADS
807 if (chunksize == 0) {
808 if (!ferror(f->f_fp))
809 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000810 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000811 /* When in non-blocking mode, data shouldn't
812 * be discarded if a blocking signal was
813 * received. That will also happen if
814 * chunksize != 0, but bytesread < buffersize. */
815 if (bytesread > 0 && BLOCKED_ERRNO(errno))
816 break;
817 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000818 Py_DECREF(v);
819 return NULL;
820 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000821 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000822 if (bytesread < buffersize) {
823 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000824 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000825 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000826 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000827 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000828 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000829 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000830 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000831 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000832 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000833 }
834 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000835 if (bytesread != buffersize)
836 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837 return v;
838}
839
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000840static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000841file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000842{
843 char *ptr;
Guido van Rossum00ebd462001-10-23 21:25:24 +0000844 int ntodo;
845 size_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000846
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000847 if (f->f_fp == NULL)
848 return err_closed();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000849 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000850 return NULL;
851 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000852 while (ntodo > 0) {
853 Py_BEGIN_ALLOW_THREADS
854 errno = 0;
Jeremy Hylton8b735422002-08-14 21:01:41 +0000855 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
856 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000857 Py_END_ALLOW_THREADS
858 if (nnow == 0) {
859 if (!ferror(f->f_fp))
860 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000861 PyErr_SetFromErrno(PyExc_IOError);
862 clearerr(f->f_fp);
863 return NULL;
864 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000865 ndone += nnow;
866 ntodo -= nnow;
867 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000868 return PyInt_FromLong((long)ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000869}
870
Tim Peters86821b22001-01-07 21:19:34 +0000871/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000872Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000873
874Under MSVC 6:
875
Tim Peters1c733232001-01-08 04:02:07 +0000876+ MS threadsafe getc is very slow (multiple layers of function calls before+
877 after each character, to lock+unlock the stream).
878+ The stream-locking functions are MS-internal -- can't access them from user
879 code.
880+ There's nothing Tim could find in the MS C or platform SDK libraries that
881 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000882+ MS fgets locks/unlocks only once per line; it's the only hook we have.
883
884So we use fgets for speed(!), despite that it's painful.
885
886MS realloc is also slow.
887
Tim Petersf29b64d2001-01-15 06:33:19 +0000888Reports from other platforms on this method vs getc_unlocked (which MS doesn't
889have):
890 Linux a wash
891 Solaris a wash
892 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000893
Tim Petersf29b64d2001-01-15 06:33:19 +0000894CAUTION: The C std isn't clear about this: in those cases where fgets
895writes something into the buffer, can it write into any position beyond the
896required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
897known on which it does; and it would be a strange way to code fgets. Still,
898getline_via_fgets may not work correctly if it does. The std test
899test_bufio.py should fail if platform fgets() routinely writes beyond the
900trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000901**************************************************************************/
902
Tim Petersf29b64d2001-01-15 06:33:19 +0000903/* Use this routine if told to, or by default on non-get_unlocked()
904 * platforms unless told not to. Yikes! Let's spell that out:
905 * On a platform with getc_unlocked():
906 * By default, use getc_unlocked().
907 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
908 * On a platform without getc_unlocked():
909 * By default, use fgets().
910 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
911 */
912#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
913#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000914#endif
915
Tim Petersf29b64d2001-01-15 06:33:19 +0000916#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
917#undef USE_FGETS_IN_GETLINE
918#endif
919
920#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000921static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000922getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000923{
Tim Peters15b83852001-01-08 00:53:12 +0000924/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000925 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
926 * to fill this much of the buffer with a known value in order to figure out
927 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
928 * than "most" lines, we waste time filling unused buffer slots. 100 is
929 * surely adequate for most peoples' email archives, chewing over source code,
930 * etc -- "regular old text files".
931 * MAXBUFSIZE is the maximum line length that lets us get away with the less
932 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
933 * cautions about boosting that. 300 was chosen because the worst real-life
934 * text-crunching job reported on Python-Dev was a mail-log crawler where over
935 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +0000936 */
Tim Peters142297a2001-01-15 10:36:56 +0000937#define INITBUFSIZE 100
938#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +0000939 char* p; /* temp */
940 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +0000941 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +0000942 char* pvfree; /* address of next free slot */
943 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +0000944 size_t nfree; /* # of free buffer slots; pvend-pvfree */
945 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +0000946 size_t increment; /* amount to increment the buffer */
Tim Peters86821b22001-01-07 21:19:34 +0000947
Tim Peters15b83852001-01-08 00:53:12 +0000948 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +0000949 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +0000950 */
Tim Peters142297a2001-01-15 10:36:56 +0000951 total_v_size = INITBUFSIZE; /* start small and pray */
952 pvfree = buf;
953 for (;;) {
954 Py_BEGIN_ALLOW_THREADS
955 pvend = buf + total_v_size;
956 nfree = pvend - pvfree;
957 memset(pvfree, '\n', nfree);
958 p = fgets(pvfree, nfree, fp);
959 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +0000960
Tim Peters142297a2001-01-15 10:36:56 +0000961 if (p == NULL) {
962 clearerr(fp);
963 if (PyErr_CheckSignals())
964 return NULL;
965 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +0000966 return v;
967 }
Tim Peters142297a2001-01-15 10:36:56 +0000968 /* fgets read *something* */
969 p = memchr(pvfree, '\n', nfree);
970 if (p != NULL) {
971 /* Did the \n come from fgets or from us?
972 * Since fgets stops at the first \n, and then writes
973 * \0, if it's from fgets a \0 must be next. But if
974 * that's so, it could not have come from us, since
975 * the \n's we filled the buffer with have only more
976 * \n's to the right.
977 */
978 if (p+1 < pvend && *(p+1) == '\0') {
979 /* It's from fgets: we win! In particular,
980 * we haven't done any mallocs yet, and can
981 * build the final result on the first try.
982 */
983 ++p; /* include \n from fgets */
984 }
985 else {
986 /* Must be from us: fgets didn't fill the
987 * buffer and didn't find a newline, so it
988 * must be the last and newline-free line of
989 * the file.
990 */
991 assert(p > pvfree && *(p-1) == '\0');
992 --p; /* don't include \0 from fgets */
993 }
994 v = PyString_FromStringAndSize(buf, p - buf);
995 return v;
996 }
997 /* yuck: fgets overwrote all the newlines, i.e. the entire
998 * buffer. So this line isn't over yet, or maybe it is but
999 * we're exactly at EOF. If we haven't already, try using the
1000 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001001 */
Tim Peters142297a2001-01-15 10:36:56 +00001002 assert(*(pvend-1) == '\0');
1003 if (pvfree == buf) {
1004 pvfree = pvend - 1; /* overwrite trailing null */
1005 total_v_size = MAXBUFSIZE;
1006 }
1007 else
1008 break;
Tim Peters86821b22001-01-07 21:19:34 +00001009 }
Tim Peters142297a2001-01-15 10:36:56 +00001010
1011 /* The stack buffer isn't big enough; malloc a string object and read
1012 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001013 */
Tim Petersddea2082002-03-23 10:03:50 +00001014 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001015 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001016 if (v == NULL)
1017 return v;
1018 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001019 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1020 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001021
1022 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001023 * after setting p one beyond the end of the line. The code here is
1024 * very much like the code above, except reads into v's buffer; see
1025 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001026 */
1027 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001028 Py_BEGIN_ALLOW_THREADS
1029 pvend = BUF(v) + total_v_size;
1030 nfree = pvend - pvfree;
1031 memset(pvfree, '\n', nfree);
1032 p = fgets(pvfree, nfree, fp);
1033 Py_END_ALLOW_THREADS
1034
1035 if (p == NULL) {
1036 clearerr(fp);
1037 if (PyErr_CheckSignals()) {
1038 Py_DECREF(v);
1039 return NULL;
1040 }
1041 p = pvfree;
1042 break;
1043 }
Tim Peters86821b22001-01-07 21:19:34 +00001044 p = memchr(pvfree, '\n', nfree);
1045 if (p != NULL) {
1046 if (p+1 < pvend && *(p+1) == '\0') {
1047 /* \n came from fgets */
1048 ++p;
1049 break;
1050 }
1051 /* \n came from us; last line of file, no newline */
1052 assert(p > pvfree && *(p-1) == '\0');
1053 --p;
1054 break;
1055 }
1056 /* expand buffer and try again */
1057 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001058 increment = total_v_size >> 2; /* mild exponential growth */
1059 total_v_size += increment;
Tim Peters86821b22001-01-07 21:19:34 +00001060 if (total_v_size > INT_MAX) {
1061 PyErr_SetString(PyExc_OverflowError,
1062 "line is longer than a Python string can hold");
1063 Py_DECREF(v);
1064 return NULL;
1065 }
1066 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1067 return NULL;
1068 /* overwrite the trailing null byte */
Tim Petersddea2082002-03-23 10:03:50 +00001069 pvfree = BUF(v) + (total_v_size - increment - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001070 }
1071 if (BUF(v) + total_v_size != p)
1072 _PyString_Resize(&v, p - BUF(v));
1073 return v;
1074#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001075#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001076}
Tim Petersf29b64d2001-01-15 06:33:19 +00001077#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001078
Guido van Rossum0bd24411991-04-04 15:21:57 +00001079/* Internal routine to get a line.
1080 Size argument interpretation:
1081 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001082 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001083*/
1084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001086get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001087{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001088 FILE *fp = f->f_fp;
1089 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001090 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001091 size_t total_v_size; /* total # of slots in buffer */
1092 size_t used_v_size; /* # used slots in buffer */
1093 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001094 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001095#ifdef WITH_UNIVERSAL_NEWLINES
1096 int newlinetypes = f->f_newlinetypes;
1097 int skipnextlf = f->f_skipnextlf;
1098 int univ_newline = f->f_univ_newline;
1099#endif
Guido van Rossum0bd24411991-04-04 15:21:57 +00001100
Jack Jansen7b8c7542002-04-14 20:12:41 +00001101#if defined(USE_FGETS_IN_GETLINE)
1102#ifdef WITH_UNIVERSAL_NEWLINES
1103 if (n <= 0 && !univ_newline )
1104#else
Guido van Rossum86282062001-01-08 01:26:47 +00001105 if (n <= 0)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001106#endif
Tim Petersf29b64d2001-01-15 06:33:19 +00001107 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001108#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001109 total_v_size = n > 0 ? n : 100;
1110 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001111 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001112 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001113 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001114 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001115
Guido van Rossumce5ba841991-03-06 13:06:18 +00001116 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001117 Py_BEGIN_ALLOW_THREADS
1118 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001119#ifdef WITH_UNIVERSAL_NEWLINES
1120 if (univ_newline) {
1121 c = 'x'; /* Shut up gcc warning */
1122 while ( buf != end && (c = GETC(fp)) != EOF ) {
1123 if (skipnextlf ) {
1124 skipnextlf = 0;
1125 if (c == '\n') {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001126 /* Seeing a \n here with
1127 * skipnextlf true means we
1128 * saw a \r before.
1129 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001130 newlinetypes |= NEWLINE_CRLF;
1131 c = GETC(fp);
1132 if (c == EOF) break;
1133 } else {
1134 newlinetypes |= NEWLINE_CR;
1135 }
1136 }
1137 if (c == '\r') {
1138 skipnextlf = 1;
1139 c = '\n';
1140 } else if ( c == '\n')
1141 newlinetypes |= NEWLINE_LF;
1142 *buf++ = c;
1143 if (c == '\n') break;
1144 }
1145 if ( c == EOF && skipnextlf )
1146 newlinetypes |= NEWLINE_CR;
1147 } else /* If not universal newlines use the normal loop */
1148#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001149 while ((c = GETC(fp)) != EOF &&
1150 (*buf++ = c) != '\n' &&
1151 buf != end)
1152 ;
1153 FUNLOCKFILE(fp);
1154 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001155#ifdef WITH_UNIVERSAL_NEWLINES
1156 f->f_newlinetypes = newlinetypes;
1157 f->f_skipnextlf = skipnextlf;
1158#endif
Guido van Rossum1187aa42001-01-05 14:43:05 +00001159 if (c == '\n')
1160 break;
1161 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001162 if (ferror(fp)) {
1163 PyErr_SetFromErrno(PyExc_IOError);
1164 clearerr(fp);
1165 Py_DECREF(v);
1166 return NULL;
1167 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001168 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001169 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001170 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001171 return NULL;
1172 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001173 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001174 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001175 /* Must be because buf == end */
1176 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001177 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001178 used_v_size = total_v_size;
1179 increment = total_v_size >> 2; /* mild exponential growth */
1180 total_v_size += increment;
1181 if (total_v_size > INT_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001182 PyErr_SetString(PyExc_OverflowError,
1183 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001184 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001185 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001186 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001187 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001188 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001189 buf = BUF(v) + used_v_size;
1190 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001191 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001193 used_v_size = buf - BUF(v);
1194 if (used_v_size != total_v_size)
1195 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001196 return v;
1197}
1198
Guido van Rossum0bd24411991-04-04 15:21:57 +00001199/* External C interface */
1200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001201PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001202PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001203{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001204 PyObject *result;
1205
Guido van Rossum3165fe61992-09-25 21:59:05 +00001206 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001207 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001208 return NULL;
1209 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001210
1211 if (PyFile_Check(f)) {
1212 if (((PyFileObject*)f)->f_fp == NULL)
1213 return err_closed();
1214 result = get_line((PyFileObject *)f, n);
1215 }
1216 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001217 PyObject *reader;
1218 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001219
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001220 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001221 if (reader == NULL)
1222 return NULL;
1223 if (n <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001224 args = Py_BuildValue("()");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001225 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001226 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001227 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001228 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001229 return NULL;
1230 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001231 result = PyEval_CallObject(reader, args);
1232 Py_DECREF(reader);
1233 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001234 if (result != NULL && !PyString_Check(result) &&
1235 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001236 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001237 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001238 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001239 "object.readline() returned non-string");
1240 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001241 }
1242
1243 if (n < 0 && result != NULL && PyString_Check(result)) {
1244 char *s = PyString_AS_STRING(result);
1245 int len = PyString_GET_SIZE(result);
1246 if (len == 0) {
1247 Py_DECREF(result);
1248 result = NULL;
1249 PyErr_SetString(PyExc_EOFError,
1250 "EOF when reading a line");
1251 }
1252 else if (s[len-1] == '\n') {
1253 if (result->ob_refcnt == 1)
1254 _PyString_Resize(&result, len-1);
1255 else {
1256 PyObject *v;
1257 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001258 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001259 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001260 }
1261 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001262 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001263#ifdef Py_USING_UNICODE
1264 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1265 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
1266 int len = PyUnicode_GET_SIZE(result);
1267 if (len == 0) {
1268 Py_DECREF(result);
1269 result = NULL;
1270 PyErr_SetString(PyExc_EOFError,
1271 "EOF when reading a line");
1272 }
1273 else if (s[len-1] == '\n') {
1274 if (result->ob_refcnt == 1)
1275 PyUnicode_Resize(&result, len-1);
1276 else {
1277 PyObject *v;
1278 v = PyUnicode_FromUnicode(s, len-1);
1279 Py_DECREF(result);
1280 result = v;
1281 }
1282 }
1283 }
1284#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001285 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001286}
1287
1288/* Python method */
1289
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001290static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001291file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001292{
Guido van Rossum789a1611997-05-10 22:33:55 +00001293 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001294
Guido van Rossumd7297e61992-07-06 14:19:26 +00001295 if (f->f_fp == NULL)
1296 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001297 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001298 return NULL;
1299 if (n == 0)
1300 return PyString_FromString("");
1301 if (n < 0)
1302 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001303 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001304}
1305
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001306static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001307file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001308{
Guido van Rossum789a1611997-05-10 22:33:55 +00001309 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001310 PyObject *list;
1311 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001312 char small_buffer[SMALLCHUNK];
1313 char *buffer = small_buffer;
1314 size_t buffersize = SMALLCHUNK;
1315 PyObject *big_buffer = NULL;
1316 size_t nfilled = 0;
1317 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001318 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001319 char *p, *q, *end;
1320 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001321 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001322
Guido van Rossumd7297e61992-07-06 14:19:26 +00001323 if (f->f_fp == NULL)
1324 return err_closed();
Guido van Rossum43713e52000-02-29 13:59:29 +00001325 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001326 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001327 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001328 return NULL;
1329 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001330 if (shortread)
1331 nread = 0;
1332 else {
1333 Py_BEGIN_ALLOW_THREADS
1334 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001335 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001336 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001337 Py_END_ALLOW_THREADS
1338 shortread = (nread < buffersize-nfilled);
1339 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001340 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001341 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001342 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001343 break;
1344 PyErr_SetFromErrno(PyExc_IOError);
1345 clearerr(f->f_fp);
1346 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001347 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001348 list = NULL;
1349 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001350 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001351 totalread += nread;
Guido van Rossum6263d541997-05-10 22:07:25 +00001352 p = memchr(buffer+nfilled, '\n', nread);
1353 if (p == NULL) {
1354 /* Need a larger buffer to fit this line */
1355 nfilled += nread;
1356 buffersize *= 2;
Trent Mickf29f47b2000-08-11 19:02:59 +00001357 if (buffersize > INT_MAX) {
1358 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001359 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001360 goto error;
1361 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001362 if (big_buffer == NULL) {
1363 /* Create the big buffer */
1364 big_buffer = PyString_FromStringAndSize(
1365 NULL, buffersize);
1366 if (big_buffer == NULL)
1367 goto error;
1368 buffer = PyString_AS_STRING(big_buffer);
1369 memcpy(buffer, small_buffer, nfilled);
1370 }
1371 else {
1372 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001373 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1374 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001375 buffer = PyString_AS_STRING(big_buffer);
1376 }
1377 continue;
1378 }
1379 end = buffer+nfilled+nread;
1380 q = buffer;
1381 do {
1382 /* Process complete lines */
1383 p++;
1384 line = PyString_FromStringAndSize(q, p-q);
1385 if (line == NULL)
1386 goto error;
1387 err = PyList_Append(list, line);
1388 Py_DECREF(line);
1389 if (err != 0)
1390 goto error;
1391 q = p;
1392 p = memchr(q, '\n', end-q);
1393 } while (p != NULL);
1394 /* Move the remaining incomplete line to the start */
1395 nfilled = end-q;
1396 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001397 if (sizehint > 0)
1398 if (totalread >= (size_t)sizehint)
1399 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001400 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001401 if (nfilled != 0) {
1402 /* Partial last line */
1403 line = PyString_FromStringAndSize(buffer, nfilled);
1404 if (line == NULL)
1405 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001406 if (sizehint > 0) {
1407 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001408 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001409 if (rest == NULL) {
1410 Py_DECREF(line);
1411 goto error;
1412 }
1413 PyString_Concat(&line, rest);
1414 Py_DECREF(rest);
1415 if (line == NULL)
1416 goto error;
1417 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001418 err = PyList_Append(list, line);
1419 Py_DECREF(line);
1420 if (err != 0)
1421 goto error;
1422 }
1423 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001424 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001425 return list;
1426}
1427
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001428static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001429file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001430{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001431 char *s;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001432 int n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001433 if (f->f_fp == NULL)
1434 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001435 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001436 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001437 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001438 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001439 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001440 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001442 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001443 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001444 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001445 return NULL;
1446 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001447 Py_INCREF(Py_None);
1448 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001449}
1450
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001451static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001452file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001453{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001454#define CHUNKSIZE 1000
1455 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001456 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001457 PyObject *result;
1458 int i, j, index, len, nwritten, islist;
1459
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001460 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001461 if (f->f_fp == NULL)
1462 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001463
1464 result = NULL;
1465 list = NULL;
1466 islist = PyList_Check(seq);
1467 if (islist)
1468 it = NULL;
1469 else {
1470 it = PyObject_GetIter(seq);
1471 if (it == NULL) {
1472 PyErr_SetString(PyExc_TypeError,
1473 "writelines() requires an iterable argument");
1474 return NULL;
1475 }
1476 /* From here on, fail by going to error, to reclaim "it". */
1477 list = PyList_New(CHUNKSIZE);
1478 if (list == NULL)
1479 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001480 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001481
1482 /* Strategy: slurp CHUNKSIZE lines into a private list,
1483 checking that they are all strings, then write that list
1484 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001485 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001486 if (islist) {
1487 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001488 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001489 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001490 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001491 j = PyList_GET_SIZE(list);
1492 }
1493 else {
1494 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001495 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001496 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001497 if (PyErr_Occurred())
1498 goto error;
1499 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001500 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001501 PyList_SetItem(list, j, line);
1502 }
1503 }
1504 if (j == 0)
1505 break;
1506
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001507 /* Check that all entries are indeed strings. If not,
1508 apply the same rules as for file.write() and
1509 convert the results to strings. This is slow, but
1510 seems to be the only way since all conversion APIs
1511 could potentially execute Python code. */
1512 for (i = 0; i < j; i++) {
1513 PyObject *v = PyList_GET_ITEM(list, i);
1514 if (!PyString_Check(v)) {
1515 const char *buffer;
1516 int len;
Tim Peters86821b22001-01-07 21:19:34 +00001517 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001518 PyObject_AsReadBuffer(v,
1519 (const void**)&buffer,
1520 &len)) ||
1521 PyObject_AsCharBuffer(v,
1522 &buffer,
1523 &len))) {
1524 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001525 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001526 goto error;
1527 }
1528 line = PyString_FromStringAndSize(buffer,
1529 len);
1530 if (line == NULL)
1531 goto error;
1532 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001533 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001534 }
1535 }
1536
1537 /* Since we are releasing the global lock, the
1538 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539 Py_BEGIN_ALLOW_THREADS
1540 f->f_softspace = 0;
1541 errno = 0;
1542 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001543 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001544 len = PyString_GET_SIZE(line);
1545 nwritten = fwrite(PyString_AS_STRING(line),
1546 1, len, f->f_fp);
1547 if (nwritten != len) {
1548 Py_BLOCK_THREADS
1549 PyErr_SetFromErrno(PyExc_IOError);
1550 clearerr(f->f_fp);
1551 goto error;
1552 }
1553 }
1554 Py_END_ALLOW_THREADS
1555
1556 if (j < CHUNKSIZE)
1557 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001558 }
1559
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001560 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001561 result = Py_None;
1562 error:
1563 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001564 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001565 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001566#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001567}
1568
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001569static PyObject *
1570file_getiter(PyFileObject *f)
1571{
1572 if (f->f_fp == NULL)
1573 return err_closed();
1574 Py_INCREF(f);
1575 return (PyObject *)f;
1576}
1577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001578PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001579"readline([size]) -> next line from the file, as a string.\n"
1580"\n"
1581"Retain newline. A non-negative size argument limits the maximum\n"
1582"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001583"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001585PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001586"read([size]) -> read at most size bytes, returned as a string.\n"
1587"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001588"If the size argument is negative or omitted, read until EOF is reached.\n"
1589"Notice that when in non-blocking mode, less data than what was requested\n"
1590"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001592PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001593"write(str) -> None. Write string str to file.\n"
1594"\n"
1595"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001596"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001598PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001599"fileno() -> integer \"file descriptor\".\n"
1600"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001601"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001603PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001604"seek(offset[, whence]) -> None. Move to new file position.\n"
1605"\n"
1606"Argument offset is a byte count. Optional argument whence defaults to\n"
1607"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1608"(move relative to current position, positive or negative), and 2 (move\n"
1609"relative to end of file, usually negative, although many platforms allow\n"
1610"seeking beyond the end of a file).\n"
1611"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001612"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001613
Guido van Rossumd7047b31995-01-02 19:07:15 +00001614#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001615PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001616"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1617"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001618"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001619#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621PyDoc_STRVAR(tell_doc,
1622"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001624PyDoc_STRVAR(readinto_doc,
1625"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001627PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001628"readlines([size]) -> list of strings, each a line from the file.\n"
1629"\n"
1630"Call readline() repeatedly and return a list of the lines so read.\n"
1631"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001632"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001634PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001635"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001636"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001637"For backward compatibility. File objects now include the performance\n"
1638"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001640PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001641"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001642"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001643"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001644"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001646PyDoc_STRVAR(flush_doc,
1647"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001649PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001650"close() -> None or (perhaps) an integer. Close the file.\n"
1651"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001652"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001653"further I/O operations. close() may be called more than once without\n"
1654"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001655"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001657PyDoc_STRVAR(isatty_doc,
1658"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001659
1660static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001661 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1662 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1663 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1664 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1665 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001666#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001667 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001668#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001669 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1670 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1671 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
1672 {"xreadlines",(PyCFunction)file_getiter, METH_NOARGS, xreadlines_doc},
1673 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1674 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1675 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1676 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
1677 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001678};
1679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001680#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001681
Guido van Rossum6f799372001-09-20 20:46:19 +00001682static PyMemberDef file_memberlist[] = {
1683 {"softspace", T_INT, OFF(f_softspace), 0,
1684 "flag indicating that a space needs to be printed; used by print"},
1685 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001686 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001687 {"name", T_OBJECT, OFF(f_name), RO,
1688 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001689 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1690 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001691 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001692 {NULL} /* Sentinel */
1693};
1694
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001695static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001696get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001697{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001698 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001699}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001700#ifdef WITH_UNIVERSAL_NEWLINES
1701static PyObject *
1702get_newlines(PyFileObject *f, void *closure)
1703{
1704 switch (f->f_newlinetypes) {
1705 case NEWLINE_UNKNOWN:
1706 Py_INCREF(Py_None);
1707 return Py_None;
1708 case NEWLINE_CR:
1709 return PyString_FromString("\r");
1710 case NEWLINE_LF:
1711 return PyString_FromString("\n");
1712 case NEWLINE_CR|NEWLINE_LF:
1713 return Py_BuildValue("(ss)", "\r", "\n");
1714 case NEWLINE_CRLF:
1715 return PyString_FromString("\r\n");
1716 case NEWLINE_CR|NEWLINE_CRLF:
1717 return Py_BuildValue("(ss)", "\r", "\r\n");
1718 case NEWLINE_LF|NEWLINE_CRLF:
1719 return Py_BuildValue("(ss)", "\n", "\r\n");
1720 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1721 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1722 default:
Jeremy Hylton8b735422002-08-14 21:01:41 +00001723 PyErr_Format(PyExc_SystemError,
1724 "Unknown newlines value 0x%x\n",
1725 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001726 return NULL;
1727 }
1728}
1729#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +00001730
Guido van Rossum32d34c82001-09-20 21:45:26 +00001731static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001732 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001733#ifdef WITH_UNIVERSAL_NEWLINES
Jeremy Hylton8b735422002-08-14 21:01:41 +00001734 {"newlines", (getter)get_newlines, NULL,
1735 "end-of-line convention used in this file"},
Jack Jansen7b8c7542002-04-14 20:12:41 +00001736#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737 {0},
1738};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001739
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001740static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001741drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001742{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001743 if (f->f_buf != NULL) {
1744 PyMem_Free(f->f_buf);
1745 f->f_buf = NULL;
1746 }
Guido van Rossum65967252001-04-21 13:20:18 +00001747}
1748
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001749/* Make sure that file has a readahead buffer with at least one byte
1750 (unless at EOF) and no more than bufsize. Returns negative value on
1751 error */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001752static int
1753readahead(PyFileObject *f, int bufsize)
1754{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001755 int chunksize;
1756
1757 if (f->f_buf != NULL) {
1758 if( (f->f_bufend - f->f_bufptr) >= 1)
1759 return 0;
1760 else
1761 drop_readahead(f);
1762 }
1763 if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
1764 return -1;
1765 }
1766 Py_BEGIN_ALLOW_THREADS
1767 errno = 0;
1768 chunksize = Py_UniversalNewlineFread(
1769 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1770 Py_END_ALLOW_THREADS
1771 if (chunksize == 0) {
1772 if (ferror(f->f_fp)) {
1773 PyErr_SetFromErrno(PyExc_IOError);
1774 clearerr(f->f_fp);
1775 drop_readahead(f);
1776 return -1;
1777 }
1778 }
1779 f->f_bufptr = f->f_buf;
1780 f->f_bufend = f->f_buf + chunksize;
1781 return 0;
1782}
1783
1784/* Used by file_iternext. The returned string will start with 'skip'
1785 uninitialized bytes followed by the remainder of the line. Don't be
1786 horrified by the recursive call: maximum recursion depth is limited by
1787 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1788
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001789static PyStringObject *
1790readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1791{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001792 PyStringObject* s;
1793 char *bufptr;
1794 char *buf;
1795 int len;
1796
1797 if (f->f_buf == NULL)
1798 if (readahead(f, bufsize) < 0)
1799 return NULL;
1800
1801 len = f->f_bufend - f->f_bufptr;
1802 if (len == 0)
1803 return (PyStringObject *)
1804 PyString_FromStringAndSize(NULL, skip);
1805 bufptr = memchr(f->f_bufptr, '\n', len);
1806 if (bufptr != NULL) {
1807 bufptr++; /* Count the '\n' */
1808 len = bufptr - f->f_bufptr;
1809 s = (PyStringObject *)
1810 PyString_FromStringAndSize(NULL, skip+len);
1811 if (s == NULL)
1812 return NULL;
1813 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1814 f->f_bufptr = bufptr;
1815 if (bufptr == f->f_bufend)
1816 drop_readahead(f);
1817 } else {
1818 bufptr = f->f_bufptr;
1819 buf = f->f_buf;
1820 f->f_buf = NULL; /* Force new readahead buffer */
1821 s = readahead_get_line_skip(
1822 f, skip+len, bufsize + (bufsize>>2) );
1823 if (s == NULL) {
1824 PyMem_Free(buf);
1825 return NULL;
1826 }
1827 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1828 PyMem_Free(buf);
1829 }
1830 return s;
1831}
1832
1833/* A larger buffer size may actually decrease performance. */
1834#define READAHEAD_BUFSIZE 8192
1835
1836static PyObject *
1837file_iternext(PyFileObject *f)
1838{
1839 PyStringObject* l;
1840
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001841 if (f->f_fp == NULL)
1842 return err_closed();
1843
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001844 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1845 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1846 Py_XDECREF(l);
1847 return NULL;
1848 }
1849 return (PyObject *)l;
1850}
1851
1852
Tim Peters59c9a642001-09-13 05:38:56 +00001853static PyObject *
1854file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1855{
Tim Peters44410012001-09-14 03:26:08 +00001856 PyObject *self;
1857 static PyObject *not_yet_string;
1858
1859 assert(type != NULL && type->tp_alloc != NULL);
1860
1861 if (not_yet_string == NULL) {
1862 not_yet_string = PyString_FromString("<uninitialized file>");
1863 if (not_yet_string == NULL)
1864 return NULL;
1865 }
1866
1867 self = type->tp_alloc(type, 0);
1868 if (self != NULL) {
1869 /* Always fill in the name and mode, so that nobody else
1870 needs to special-case NULLs there. */
1871 Py_INCREF(not_yet_string);
1872 ((PyFileObject *)self)->f_name = not_yet_string;
1873 Py_INCREF(not_yet_string);
1874 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001875 Py_INCREF(Py_None);
1876 ((PyFileObject *)self)->f_encoding = Py_None;
Tim Peters44410012001-09-14 03:26:08 +00001877 }
1878 return self;
1879}
1880
1881static int
1882file_init(PyObject *self, PyObject *args, PyObject *kwds)
1883{
1884 PyFileObject *foself = (PyFileObject *)self;
1885 int ret = 0;
Tim Peters59c9a642001-09-13 05:38:56 +00001886 static char *kwlist[] = {"name", "mode", "buffering", 0};
1887 char *name = NULL;
1888 char *mode = "r";
1889 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001890 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001891
1892 assert(PyFile_Check(self));
1893 if (foself->f_fp != NULL) {
1894 /* Have to close the existing file first. */
1895 PyObject *closeresult = file_close(foself);
1896 if (closeresult == NULL)
1897 return -1;
1898 Py_DECREF(closeresult);
1899 }
Tim Peters59c9a642001-09-13 05:38:56 +00001900
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001901#ifdef Py_WIN_WIDE_FILENAMES
1902 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
1903 PyObject *po;
1904 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
1905 kwlist, &po, &mode, &bufsize)) {
1906 wideargument = 1;
1907 if (fill_file_fields(foself, NULL, name, mode,
1908 fclose, po) == NULL)
1909 goto Error;
1910 } else {
1911 /* Drop the argument parsing error as narrow
1912 strings are also valid. */
1913 PyErr_Clear();
1914 }
1915 }
1916#endif
1917
1918 if (!wideargument) {
1919 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
1920 Py_FileSystemDefaultEncoding,
1921 &name,
1922 &mode, &bufsize))
1923 return -1;
1924 if (fill_file_fields(foself, NULL, name, mode,
1925 fclose, NULL) == NULL)
1926 goto Error;
1927 }
Tim Peters44410012001-09-14 03:26:08 +00001928 if (open_the_file(foself, name, mode) == NULL)
1929 goto Error;
1930 PyFile_SetBufSize(self, bufsize);
1931 goto Done;
1932
1933Error:
1934 ret = -1;
1935 /* fall through */
1936Done:
Tim Peters59c9a642001-09-13 05:38:56 +00001937 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00001938 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00001939}
1940
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001941PyDoc_VAR(file_doc) =
1942PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00001943"file(name[, mode[, buffering]]) -> file object\n"
1944"\n"
1945"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
1946"writing or appending. The file will be created if it doesn't exist\n"
1947"when opened for writing or appending; it will be truncated when\n"
1948"opened for writing. Add a 'b' to the mode for binary files.\n"
1949"Add a '+' to the mode to allow simultaneous reading and writing.\n"
1950"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Tim Peters742dfd62001-09-13 21:49:44 +00001951"buffered, and larger numbers specify the buffer size.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001952)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001953#ifdef WITH_UNIVERSAL_NEWLINES
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001954PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001955"Add a 'U' to mode to open the file for input with universal newline\n"
1956"support. Any line ending in the input file will be seen as a '\\n'\n"
1957"in Python. Also, a file so opened gains the attribute 'newlines';\n"
1958"the value for this attribute is one of None (no newline read yet),\n"
1959"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
1960"\n"
1961"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001962)
Barry Warsaw4be55b52002-05-22 20:37:53 +00001963#endif /* WITH_UNIVERSAL_NEWLINES */
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001964PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00001965"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001966"Note: open() is an alias for file()."
1967);
Tim Peters59c9a642001-09-13 05:38:56 +00001968
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001969PyTypeObject PyFile_Type = {
1970 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001971 0,
1972 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001973 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001974 0,
Guido van Rossum65967252001-04-21 13:20:18 +00001975 (destructor)file_dealloc, /* tp_dealloc */
1976 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001977 0, /* tp_getattr */
1978 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00001979 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00001981 0, /* tp_as_number */
1982 0, /* tp_as_sequence */
1983 0, /* tp_as_mapping */
1984 0, /* tp_hash */
1985 0, /* tp_call */
1986 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00001988 /* softspace is writable: we must supply tp_setattro */
1989 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00001990 0, /* tp_as_buffer */
Guido van Rossum9475a232001-10-05 20:51:39 +00001991 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00001992 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993 0, /* tp_traverse */
1994 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00001995 0, /* tp_richcompare */
1996 0, /* tp_weaklistoffset */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001997 (getiterfunc)file_getiter, /* tp_iter */
1998 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 file_methods, /* tp_methods */
2000 file_memberlist, /* tp_members */
2001 file_getsetlist, /* tp_getset */
2002 0, /* tp_base */
2003 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002004 0, /* tp_descr_get */
2005 0, /* tp_descr_set */
2006 0, /* tp_dictoffset */
Tim Peters44410012001-09-14 03:26:08 +00002007 (initproc)file_init, /* tp_init */
2008 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002009 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002010 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002011};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002012
2013/* Interface for the 'soft space' between print items. */
2014
2015int
Fred Drakefd99de62000-07-09 05:02:18 +00002016PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002017{
2018 int oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002019 if (f == NULL) {
2020 /* Do nothing */
2021 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002022 else if (PyFile_Check(f)) {
2023 oldflag = ((PyFileObject *)f)->f_softspace;
2024 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002025 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002026 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002027 PyObject *v;
2028 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002029 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002031 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002032 if (PyInt_Check(v))
2033 oldflag = PyInt_AsLong(v);
2034 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002035 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002036 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002037 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002038 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002039 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002040 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2041 PyErr_Clear();
2042 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002043 }
2044 }
Guido van Rossumeb183da1991-04-04 10:44:06 +00002045 return oldflag;
2046}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002047
2048/* Interfaces to write objects/strings to file-like objects */
2049
2050int
Fred Drakefd99de62000-07-09 05:02:18 +00002051PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002052{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002053 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002054 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002055 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002056 return -1;
2057 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002058 else if (PyFile_Check(f)) {
2059 FILE *fp = PyFile_AsFile(f);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002060 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2061 int result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002062 if (fp == NULL) {
2063 err_closed();
2064 return -1;
2065 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002066#ifdef Py_USING_UNICODE
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002067 if ((flags & Py_PRINT_RAW) &&
2068 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002069 char *cenc = PyString_AS_STRING(enc);
2070 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2071 if (value == NULL)
2072 return -1;
2073 } else {
2074 value = v;
2075 Py_INCREF(value);
2076 }
2077 result = PyObject_Print(value, fp, flags);
2078 Py_DECREF(value);
2079 return result;
2080#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002081 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002082#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002083 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002084 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002085 if (writer == NULL)
2086 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002087 if (flags & Py_PRINT_RAW) {
2088 if (PyUnicode_Check(v)) {
2089 value = v;
2090 Py_INCREF(value);
2091 } else
2092 value = PyObject_Str(v);
2093 }
2094 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002095 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002096 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002097 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002098 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002099 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 args = Py_BuildValue("(O)", value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002101 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 Py_DECREF(value);
2103 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002104 return -1;
2105 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 result = PyEval_CallObject(writer, args);
2107 Py_DECREF(args);
2108 Py_DECREF(value);
2109 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002110 if (result == NULL)
2111 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002112 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002113 return 0;
2114}
2115
Guido van Rossum27a60b11997-05-22 22:25:11 +00002116int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002117PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002118{
2119 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002120 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002121 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002122 PyErr_SetString(PyExc_SystemError,
2123 "null file for PyFile_WriteString");
2124 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002125 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126 else if (PyFile_Check(f)) {
2127 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002128 if (fp == NULL) {
2129 err_closed();
2130 return -1;
2131 }
2132 fputs(s, fp);
2133 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002134 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002135 else if (!PyErr_Occurred()) {
2136 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002137 int err;
2138 if (v == NULL)
2139 return -1;
2140 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2141 Py_DECREF(v);
2142 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002143 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002144 else
2145 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002146}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002147
2148/* Try to get a file-descriptor from a Python object. If the object
2149 is an integer or long integer, its value is returned. If not, the
2150 object's fileno() method is called if it exists; the method must return
2151 an integer or long integer, which is returned as the file descriptor value.
2152 -1 is returned on failure.
2153*/
2154
2155int PyObject_AsFileDescriptor(PyObject *o)
2156{
2157 int fd;
2158 PyObject *meth;
2159
2160 if (PyInt_Check(o)) {
2161 fd = PyInt_AsLong(o);
2162 }
2163 else if (PyLong_Check(o)) {
2164 fd = PyLong_AsLong(o);
2165 }
2166 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2167 {
2168 PyObject *fno = PyEval_CallObject(meth, NULL);
2169 Py_DECREF(meth);
2170 if (fno == NULL)
2171 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002172
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002173 if (PyInt_Check(fno)) {
2174 fd = PyInt_AsLong(fno);
2175 Py_DECREF(fno);
2176 }
2177 else if (PyLong_Check(fno)) {
2178 fd = PyLong_AsLong(fno);
2179 Py_DECREF(fno);
2180 }
2181 else {
2182 PyErr_SetString(PyExc_TypeError,
2183 "fileno() returned a non-integer");
2184 Py_DECREF(fno);
2185 return -1;
2186 }
2187 }
2188 else {
2189 PyErr_SetString(PyExc_TypeError,
2190 "argument must be an int, or have a fileno() method.");
2191 return -1;
2192 }
2193
2194 if (fd < 0) {
2195 PyErr_Format(PyExc_ValueError,
2196 "file descriptor cannot be a negative integer (%i)",
2197 fd);
2198 return -1;
2199 }
2200 return fd;
2201}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002202
2203#ifdef WITH_UNIVERSAL_NEWLINES
2204/* From here on we need access to the real fgets and fread */
2205#undef fgets
2206#undef fread
2207
2208/*
2209** Py_UniversalNewlineFgets is an fgets variation that understands
2210** all of \r, \n and \r\n conventions.
2211** The stream should be opened in binary mode.
2212** If fobj is NULL the routine always does newline conversion, and
2213** it may peek one char ahead to gobble the second char in \r\n.
2214** If fobj is non-NULL it must be a PyFileObject. In this case there
2215** is no readahead but in stead a flag is used to skip a following
2216** \n on the next read. Also, if the file is open in binary mode
2217** the whole conversion is skipped. Finally, the routine keeps track of
2218** the different types of newlines seen.
2219** Note that we need no error handling: fgets() treats error and eof
2220** identically.
2221*/
2222char *
2223Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2224{
2225 char *p = buf;
2226 int c;
2227 int newlinetypes = 0;
2228 int skipnextlf = 0;
2229 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002230
Jack Jansen7b8c7542002-04-14 20:12:41 +00002231 if (fobj) {
2232 if (!PyFile_Check(fobj)) {
2233 errno = ENXIO; /* What can you do... */
2234 return NULL;
2235 }
2236 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2237 if ( !univ_newline )
2238 return fgets(buf, n, stream);
2239 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2240 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2241 }
2242 FLOCKFILE(stream);
2243 c = 'x'; /* Shut up gcc warning */
2244 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2245 if (skipnextlf ) {
2246 skipnextlf = 0;
2247 if (c == '\n') {
2248 /* Seeing a \n here with skipnextlf true
2249 ** means we saw a \r before.
2250 */
2251 newlinetypes |= NEWLINE_CRLF;
2252 c = GETC(stream);
2253 if (c == EOF) break;
2254 } else {
2255 /*
2256 ** Note that c == EOF also brings us here,
2257 ** so we're okay if the last char in the file
2258 ** is a CR.
2259 */
2260 newlinetypes |= NEWLINE_CR;
2261 }
2262 }
2263 if (c == '\r') {
2264 /* A \r is translated into a \n, and we skip
2265 ** an adjacent \n, if any. We don't set the
2266 ** newlinetypes flag until we've seen the next char.
2267 */
2268 skipnextlf = 1;
2269 c = '\n';
2270 } else if ( c == '\n') {
2271 newlinetypes |= NEWLINE_LF;
2272 }
2273 *p++ = c;
2274 if (c == '\n') break;
2275 }
2276 if ( c == EOF && skipnextlf )
2277 newlinetypes |= NEWLINE_CR;
2278 FUNLOCKFILE(stream);
2279 *p = '\0';
2280 if (fobj) {
2281 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2282 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2283 } else if ( skipnextlf ) {
2284 /* If we have no file object we cannot save the
2285 ** skipnextlf flag. We have to readahead, which
2286 ** will cause a pause if we're reading from an
2287 ** interactive stream, but that is very unlikely
2288 ** unless we're doing something silly like
2289 ** execfile("/dev/tty").
2290 */
2291 c = GETC(stream);
2292 if ( c != '\n' )
2293 ungetc(c, stream);
2294 }
2295 if (p == buf)
2296 return NULL;
2297 return buf;
2298}
2299
2300/*
2301** Py_UniversalNewlineFread is an fread variation that understands
2302** all of \r, \n and \r\n conventions.
2303** The stream should be opened in binary mode.
2304** fobj must be a PyFileObject. In this case there
2305** is no readahead but in stead a flag is used to skip a following
2306** \n on the next read. Also, if the file is open in binary mode
2307** the whole conversion is skipped. Finally, the routine keeps track of
2308** the different types of newlines seen.
2309*/
2310size_t
Tim Peters058b1412002-04-21 07:29:14 +00002311Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002312 FILE *stream, PyObject *fobj)
2313{
Tim Peters058b1412002-04-21 07:29:14 +00002314 char *dst = buf;
2315 PyFileObject *f = (PyFileObject *)fobj;
2316 int newlinetypes, skipnextlf;
2317
2318 assert(buf != NULL);
2319 assert(stream != NULL);
2320
Jack Jansen7b8c7542002-04-14 20:12:41 +00002321 if (!fobj || !PyFile_Check(fobj)) {
2322 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002323 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002324 }
Tim Peters058b1412002-04-21 07:29:14 +00002325 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002326 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002327 newlinetypes = f->f_newlinetypes;
2328 skipnextlf = f->f_skipnextlf;
2329 /* Invariant: n is the number of bytes remaining to be filled
2330 * in the buffer.
2331 */
2332 while (n) {
2333 size_t nread;
2334 int shortread;
2335 char *src = dst;
2336
2337 nread = fread(dst, 1, n, stream);
2338 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002339 if (nread == 0)
2340 break;
2341
Tim Peterse1682a82002-04-21 18:15:20 +00002342 n -= nread; /* assuming 1 byte out for each in; will adjust */
2343 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002344 while (nread--) {
2345 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002346 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002347 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002348 *dst++ = '\n';
2349 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002350 }
2351 else if (skipnextlf && c == '\n') {
2352 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002353 skipnextlf = 0;
2354 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002355 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002356 }
2357 else {
2358 /* Normal char to be stored in buffer. Also
2359 * update the newlinetypes flag if either this
2360 * is an LF or the previous char was a CR.
2361 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002362 if (c == '\n')
2363 newlinetypes |= NEWLINE_LF;
2364 else if (skipnextlf)
2365 newlinetypes |= NEWLINE_CR;
2366 *dst++ = c;
2367 skipnextlf = 0;
2368 }
2369 }
Tim Peters058b1412002-04-21 07:29:14 +00002370 if (shortread) {
2371 /* If this is EOF, update type flags. */
2372 if (skipnextlf && feof(stream))
2373 newlinetypes |= NEWLINE_CR;
2374 break;
2375 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002376 }
Tim Peters058b1412002-04-21 07:29:14 +00002377 f->f_newlinetypes = newlinetypes;
2378 f->f_skipnextlf = skipnextlf;
2379 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002380}
2381#endif