blob: 9195a24ea113940acee78e6d18efdb4038555c29 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* File object implementation */
2
Martin v. Löwis18e16552006-02-15 17:27:45 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossumb6775db1994-08-01 11:34:53 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossum41498431999-01-07 22:09:51 +00008#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum41498431999-01-07 22:09:51 +000010
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011#ifdef MS_WINDOWS
Guido van Rossumb8199141997-05-06 15:23:24 +000012#define fileno _fileno
Tim Petersfb05db22002-03-11 00:24:00 +000013/* can simulate truncate with Win32 API functions; see file_truncate */
Guido van Rossumb8199141997-05-06 15:23:24 +000014#define HAVE_FTRUNCATE
Tim Peters7a1f9172002-07-14 22:14:19 +000015#define WIN32_LEAN_AND_MEAN
Tim Petersfb05db22002-03-11 00:24:00 +000016#include <windows.h>
Guido van Rossumb8199141997-05-06 15:23:24 +000017#endif
18
Mark Hammondc2e85bd2002-10-03 05:10:39 +000019#ifdef _MSC_VER
20/* Need GetVersion to see if on NT so safe to use _wfopen */
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#endif /* _MSC_VER */
24
Andrew MacIntyrec4874392002-02-26 11:36:35 +000025#if defined(PYOS_OS2) && defined(PYCC_GCC)
26#include <io.h>
27#endif
28
Guido van Rossumc0b618a1997-05-02 03:12:38 +000029#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
Guido van Rossumce5ba841991-03-06 13:06:18 +000030
Guido van Rossumff7e83d1999-08-27 20:39:37 +000031#ifndef DONT_HAVE_ERRNO_H
Guido van Rossumf1dc5661993-07-05 10:31:29 +000032#include <errno.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000033#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Jack Jansen7b8c7542002-04-14 20:12:41 +000035#ifdef HAVE_GETC_UNLOCKED
36#define GETC(f) getc_unlocked(f)
37#define FLOCKFILE(f) flockfile(f)
38#define FUNLOCKFILE(f) funlockfile(f)
39#else
40#define GETC(f) getc(f)
41#define FLOCKFILE(f)
42#define FUNLOCKFILE(f)
43#endif
44
Jack Jansen7b8c7542002-04-14 20:12:41 +000045/* Bits in f_newlinetypes */
46#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
47#define NEWLINE_CR 1 /* \r newline seen */
48#define NEWLINE_LF 2 /* \n newline seen */
49#define NEWLINE_CRLF 4 /* \r\n newline seen */
Trent Mickf29f47b2000-08-11 19:02:59 +000050
Anthony Baxterac6bd462006-04-13 02:06:09 +000051#ifdef __cplusplus
52extern "C" {
53#endif
54
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055FILE *
Fred Drakefd99de62000-07-09 05:02:18 +000056PyFile_AsFile(PyObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 if (f == NULL || !PyFile_Check(f))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
Guido van Rossum3165fe61992-09-25 21:59:05 +000060 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 return ((PyFileObject *)f)->f_fp;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062}
63
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000065PyFile_Name(PyObject *f)
Guido van Rossumdb3165e1993-10-18 17:06:59 +000066{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 if (f == NULL || !PyFile_Check(f))
Guido van Rossumdb3165e1993-10-18 17:06:59 +000068 return NULL;
69 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000070 return ((PyFileObject *)f)->f_name;
Guido van Rossumdb3165e1993-10-18 17:06:59 +000071}
72
Neil Schemenauered19b882002-03-23 02:06:50 +000073/* On Unix, fopen will succeed for directories.
74 In Python, there should be no file objects referring to
75 directories, so we need a check. */
76
77static PyFileObject*
78dircheck(PyFileObject* f)
79{
80#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
81 struct stat buf;
82 if (f->f_fp == NULL)
83 return f;
84 if (fstat(fileno(f->f_fp), &buf) == 0 &&
85 S_ISDIR(buf.st_mode)) {
Neil Schemenauered19b882002-03-23 02:06:50 +000086 char *msg = strerror(EISDIR);
Tim Petersf1827cf2003-09-07 03:30:18 +000087 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000088 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000089 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000090 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000091 return NULL;
92 }
93#endif
94 return f;
95}
96
Tim Peters59c9a642001-09-13 05:38:56 +000097
98static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +000099fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
100 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000102 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000103 assert(f != NULL);
104 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000105 assert(f->f_fp == NULL);
106
107 Py_DECREF(f->f_name);
108 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000109 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000110
Neal Norwitzb337bb52006-07-17 00:55:45 +0000111 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000112 f->f_name = name;
113
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000114 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000115
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000116 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000117 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000118 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000119 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000120 f->f_univ_newline = (strchr(mode, 'U') != NULL);
121 f->f_newlinetypes = NEWLINE_UNKNOWN;
122 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000123 Py_INCREF(Py_None);
124 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000125
Neal Norwitzb337bb52006-07-17 00:55:45 +0000126 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000129 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131}
132
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000133/* check for known incorrect mode strings - problem is, platforms are
134 free to accept any mode characters they like and are supposed to
135 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000136 universal newline support is expressly forbidden by PEP 278.
137 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000138 won't know what it is. Non-zero return signals an exception */
139int
140_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000141{
Georg Brandl7b90e162006-05-18 07:01:27 +0000142 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000143 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000144
Georg Brandl7b90e162006-05-18 07:01:27 +0000145 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000146 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000147 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000148 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000149
Georg Brandl7b90e162006-05-18 07:01:27 +0000150 upos = strchr(mode, 'U');
151 if (upos) {
152 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000153
Georg Brandl7b90e162006-05-18 07:01:27 +0000154 if (mode[0] == 'w' || mode[0] == 'a') {
155 PyErr_Format(PyExc_ValueError, "universal newline "
156 "mode can only be used with modes "
157 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000158 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000159 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000160
161 if (mode[0] != 'r') {
162 memmove(mode+1, mode, strlen(mode)+1);
163 mode[0] = 'r';
164 }
165
166 if (!strchr(mode, 'b')) {
167 memmove(mode+2, mode+1, strlen(mode));
168 mode[1] = 'b';
169 }
170 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
171 PyErr_Format(PyExc_ValueError, "mode string must begin with "
172 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000173 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000174 }
175
176 return 0;
177}
178
Tim Peters59c9a642001-09-13 05:38:56 +0000179static PyObject *
180open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181{
Georg Brandl7b90e162006-05-18 07:01:27 +0000182 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000183 assert(f != NULL);
184 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000185#ifdef MS_WINDOWS
186 /* windows ignores the passed name in order to support Unicode */
187 assert(f->f_name != NULL);
188#else
Tim Peters59c9a642001-09-13 05:38:56 +0000189 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000190#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000191 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000192 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000193
Georg Brandl7b90e162006-05-18 07:01:27 +0000194 /* probably need to replace 'U' by 'rb' */
195 newmode = PyMem_MALLOC(strlen(mode) + 3);
196 if (!newmode) {
197 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000198 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000199 }
200 strcpy(newmode, mode);
201
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000202 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000203 f = NULL;
204 goto cleanup;
205 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000206
Tim Peters8fa45672001-09-13 21:01:29 +0000207 /* rexec.py can't stop a user from getting the file() constructor --
208 all they have to do is get *any* file object f, and then do
209 type(f). Here we prevent them from doing damage with it. */
210 if (PyEval_GetRestricted()) {
211 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000212 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000213 f = NULL;
214 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000215 }
Tim Petersa27a1502001-11-09 20:59:14 +0000216 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000217
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000218#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000219 if (PyUnicode_Check(f->f_name)) {
220 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000221 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000222 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000223 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000224 /* PyUnicode_AS_UNICODE OK without thread
225 lock as it is a simple dereference. */
226 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
227 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000228 Py_END_ALLOW_THREADS
229 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000230 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000231 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000232#endif
233 if (NULL == f->f_fp && NULL != name) {
234 Py_BEGIN_ALLOW_THREADS
Georg Brandl7b90e162006-05-18 07:01:27 +0000235 f->f_fp = fopen(name, newmode);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000236 Py_END_ALLOW_THREADS
237 }
238
Guido van Rossuma08095a1991-02-13 23:25:27 +0000239 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000240#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000241 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
242 * across all Windows flavors. When it sets EINVAL varies
243 * across Windows flavors, the exact conditions aren't
244 * documented, and the answer lies in the OS's implementation
245 * of Win32's CreateFile function (whose source is secret).
246 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000247 * Starting with Visual Studio .NET 2005, EINVAL is correctly
248 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000249 */
250 if (errno == 0) /* bad mode string */
251 errno = EINVAL;
252 else if (errno == EINVAL) /* unknown, but not a mode string */
253 errno = ENOENT;
254#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000255 /* EINVAL is returned when an invalid filename or
256 * an invalid mode is supplied. */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000257 if (errno == EINVAL)
Gregory P. Smith887290d2008-03-18 00:20:01 +0000258 PyErr_Format(PyExc_IOError,
259 "invalid filename: %s or mode: %s",
260 name, mode);
Jeremy Hylton41c83212001-11-09 16:17:24 +0000261 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000262 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000263 f = NULL;
264 }
Tim Peters2ea91112002-04-08 04:13:12 +0000265 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000266 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000267
268cleanup:
269 PyMem_FREE(newmode);
270
Tim Peters59c9a642001-09-13 05:38:56 +0000271 return (PyObject *)f;
272}
273
274PyObject *
275PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
276{
Tim Peters44410012001-09-14 03:26:08 +0000277 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
278 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000279 if (f != NULL) {
Neal Norwitzb337bb52006-07-17 00:55:45 +0000280 PyObject *o_name = PyString_FromString(name);
281 if (o_name == NULL)
282 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000283 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000284 Py_DECREF(f);
285 f = NULL;
286 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000287 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000288 }
289 return (PyObject *) f;
290}
291
292PyObject *
293PyFile_FromString(char *name, char *mode)
294{
295 extern int fclose(FILE *);
296 PyFileObject *f;
297
298 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
299 if (f != NULL) {
300 if (open_the_file(f, name, mode) == NULL) {
301 Py_DECREF(f);
302 f = NULL;
303 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306}
307
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308void
Fred Drakefd99de62000-07-09 05:02:18 +0000309PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000311 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000312 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000313 int type;
314 switch (bufsize) {
315 case 0:
316 type = _IONBF;
317 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000318#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000319 case 1:
320 type = _IOLBF;
321 bufsize = BUFSIZ;
322 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000323#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000324 default:
325 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000326#ifndef HAVE_SETVBUF
327 bufsize = BUFSIZ;
328#endif
329 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000330 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000331 fflush(file->f_fp);
332 if (type == _IONBF) {
333 PyMem_Free(file->f_setbuf);
334 file->f_setbuf = NULL;
335 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000336 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
337 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000338 }
339#ifdef HAVE_SETVBUF
340 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000341#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000342 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000343#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000344 }
345}
346
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000347/* Set the encoding used to output Unicode strings.
348 Returh 1 on success, 0 on failure. */
349
350int
351PyFile_SetEncoding(PyObject *f, const char *enc)
352{
353 PyFileObject *file = (PyFileObject*)f;
354 PyObject *str = PyString_FromString(enc);
Thomas Woutersafea5292007-01-23 13:42:00 +0000355
356 assert(PyFile_Check(f));
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000357 if (!str)
358 return 0;
359 Py_DECREF(file->f_encoding);
360 file->f_encoding = str;
361 return 1;
362}
363
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000365err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000366{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000368 return NULL;
369}
370
Thomas Woutersc45251a2006-02-12 11:53:32 +0000371/* Refuse regular file I/O if there's data in the iteration-buffer.
372 * Mixing them would cause data to arrive out of order, as the read*
373 * methods don't use the iteration buffer. */
374static PyObject *
375err_iterbuffered(void)
376{
377 PyErr_SetString(PyExc_ValueError,
378 "Mixing iteration and read methods would lose data");
379 return NULL;
380}
381
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000382static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000383
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384/* Methods */
385
386static void
Fred Drakefd99de62000-07-09 05:02:18 +0000387file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000388{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000389 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000390 if (f->weakreflist != NULL)
391 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000392 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000394 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000396 if (sts == EOF)
Peter Astrandf8e74b12004-11-07 14:15:28 +0000397 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
Guido van Rossumff4949e1992-08-05 19:58:53 +0000398 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000399 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000400 Py_XDECREF(f->f_name);
401 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000402 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000403 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000404 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000405}
406
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000408file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000410 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000411#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000412 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000413 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
414 const char *name_str = name ? PyString_AsString(name) : "?";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000415 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
416 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000417 name_str,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000418 PyString_AsString(f->f_mode),
419 f);
420 Py_XDECREF(name);
421 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000422#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000423 } else {
424 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000425 f->f_fp == NULL ? "closed" : "open",
426 PyString_AsString(f->f_name),
427 PyString_AsString(f->f_mode),
428 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000429 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000430}
431
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000432static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000433file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000435 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000437 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000439 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000440 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000442 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443 f->f_fp = NULL;
444 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000445 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000446 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000447 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000449 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450 return PyInt_FromLong((long)sts);
451 Py_INCREF(Py_None);
452 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453}
454
Trent Mickf29f47b2000-08-11 19:02:59 +0000455
Guido van Rossumb8552162001-09-05 14:58:11 +0000456/* Our very own off_t-like type, 64-bit if possible */
457#if !defined(HAVE_LARGEFILE_SUPPORT)
458typedef off_t Py_off_t;
459#elif SIZEOF_OFF_T >= 8
460typedef off_t Py_off_t;
461#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000462typedef fpos_t Py_off_t;
463#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000464#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000465#endif
466
467
Trent Mickf29f47b2000-08-11 19:02:59 +0000468/* a portable fseek() function
469 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000470static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000471_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000472{
Guido van Rossumb8552162001-09-05 14:58:11 +0000473#if !defined(HAVE_LARGEFILE_SUPPORT)
474 return fseek(fp, offset, whence);
475#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000476 return fseeko(fp, offset, whence);
477#elif defined(HAVE_FSEEK64)
478 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000479#elif defined(__BEOS__)
480 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000481#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000482 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
483 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000484 fpos_t pos;
485 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000486 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000487#ifdef MS_WINDOWS
488 fflush(fp);
489 if (_lseeki64(fileno(fp), 0, 2) == -1)
490 return -1;
491#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000492 if (fseek(fp, 0, SEEK_END) != 0)
493 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000494#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000495 /* fall through */
496 case SEEK_CUR:
497 if (fgetpos(fp, &pos) != 0)
498 return -1;
499 offset += pos;
500 break;
501 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000502 }
503 return fsetpos(fp, &offset);
504#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000505#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000506#endif
507}
508
509
510/* a portable ftell() function
511 Return -1 on failure with errno set appropriately, current file
512 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000513static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000514_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000515{
Guido van Rossumb8552162001-09-05 14:58:11 +0000516#if !defined(HAVE_LARGEFILE_SUPPORT)
517 return ftell(fp);
518#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
519 return ftello(fp);
520#elif defined(HAVE_FTELL64)
521 return ftell64(fp);
522#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000523 fpos_t pos;
524 if (fgetpos(fp, &pos) != 0)
525 return -1;
526 return pos;
527#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000528#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000529#endif
530}
531
532
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000534file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000536 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000537 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000538 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000539 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000540
Guido van Rossumd7297e61992-07-06 14:19:26 +0000541 if (f->f_fp == NULL)
542 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000543 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000544 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000545 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000546 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000547 off_index = PyNumber_Index(offobj);
548 if (!off_index) {
549 if (!PyFloat_Check(offobj))
550 return NULL;
551 /* Deprecated in 2.6 */
552 PyErr_Clear();
553 if (PyErr_Warn(PyExc_DeprecationWarning,
554 "integer argument expected, got float"))
555 return NULL;
556 off_index = offobj;
557 Py_INCREF(offobj);
558 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000559#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000560 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000561#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000562 offset = PyLong_Check(off_index) ?
563 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000564#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000565 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000566 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000567 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000568
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000570 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000571 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000573
Guido van Rossumff4949e1992-08-05 19:58:53 +0000574 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000575 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000576 clearerr(f->f_fp);
577 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000578 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000579 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000580 Py_INCREF(Py_None);
581 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000582}
583
Trent Mickf29f47b2000-08-11 19:02:59 +0000584
Guido van Rossumd7047b31995-01-02 19:07:15 +0000585#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000587file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000588{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000589 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000590 PyObject *newsizeobj = NULL;
591 Py_off_t initialpos;
592 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000593
Guido van Rossumd7047b31995-01-02 19:07:15 +0000594 if (f->f_fp == NULL)
595 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000596 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000597 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000598
Tim Petersf1827cf2003-09-07 03:30:18 +0000599 /* Get current file position. If the file happens to be open for
600 * update and the last operation was an input operation, C doesn't
601 * define what the later fflush() will do, but we promise truncate()
602 * won't change the current position (and fflush() *does* change it
603 * then at least on Windows). The easiest thing is to capture
604 * current pos now and seek back to it at the end.
605 */
606 Py_BEGIN_ALLOW_THREADS
607 errno = 0;
608 initialpos = _portable_ftell(f->f_fp);
609 Py_END_ALLOW_THREADS
610 if (initialpos == -1)
611 goto onioerror;
612
Tim Petersfb05db22002-03-11 00:24:00 +0000613 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000614 * specified value.
615 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000616 if (newsizeobj != NULL) {
617#if !defined(HAVE_LARGEFILE_SUPPORT)
618 newsize = PyInt_AsLong(newsizeobj);
619#else
620 newsize = PyLong_Check(newsizeobj) ?
621 PyLong_AsLongLong(newsizeobj) :
622 PyInt_AsLong(newsizeobj);
623#endif
624 if (PyErr_Occurred())
625 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000626 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000627 else /* default to current position */
628 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000629
Tim Petersf1827cf2003-09-07 03:30:18 +0000630 /* Flush the stream. We're mixing stream-level I/O with lower-level
631 * I/O, and a flush may be necessary to synch both platform views
632 * of the current file state.
633 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000635 errno = 0;
636 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000638 if (ret != 0)
639 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000640
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000641#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000642 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000643 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000644 {
Tim Petersfb05db22002-03-11 00:24:00 +0000645 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000646
Tim Petersf1827cf2003-09-07 03:30:18 +0000647 /* Have to move current pos to desired endpoint on Windows. */
648 Py_BEGIN_ALLOW_THREADS
649 errno = 0;
650 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
651 Py_END_ALLOW_THREADS
652 if (ret)
653 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000654
Tim Peters8f01b682002-03-12 03:04:44 +0000655 /* Truncate. Note that this may grow the file! */
656 Py_BEGIN_ALLOW_THREADS
657 errno = 0;
658 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000659 ret = hFile == (HANDLE)-1;
660 if (ret == 0) {
661 ret = SetEndOfFile(hFile) == 0;
662 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000663 errno = EACCES;
664 }
665 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000666 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000667 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000668 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000669#else
670 Py_BEGIN_ALLOW_THREADS
671 errno = 0;
672 ret = ftruncate(fileno(f->f_fp), newsize);
673 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000674 if (ret != 0)
675 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000676#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000677
Tim Petersf1827cf2003-09-07 03:30:18 +0000678 /* Restore original file position. */
679 Py_BEGIN_ALLOW_THREADS
680 errno = 0;
681 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
682 Py_END_ALLOW_THREADS
683 if (ret)
684 goto onioerror;
685
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686 Py_INCREF(Py_None);
687 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000688
689onioerror:
690 PyErr_SetFromErrno(PyExc_IOError);
691 clearerr(f->f_fp);
692 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000693}
694#endif /* HAVE_FTRUNCATE */
695
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000696static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000697file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000698{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000699 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000700
Guido van Rossumd7297e61992-07-06 14:19:26 +0000701 if (f->f_fp == NULL)
702 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000703 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000704 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000705 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000706 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000707 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000709 clearerr(f->f_fp);
710 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000711 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000712 if (f->f_skipnextlf) {
713 int c;
714 c = GETC(f->f_fp);
715 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000716 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000717 pos++;
718 f->f_skipnextlf = 0;
719 } else if (c != EOF) ungetc(c, f->f_fp);
720 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000721#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000722 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000723#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000724 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000725#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000726}
727
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000729file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000730{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000731 if (f->f_fp == NULL)
732 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000733 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000734}
735
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000737file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000738{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000739 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000740
Guido van Rossumd7297e61992-07-06 14:19:26 +0000741 if (f->f_fp == NULL)
742 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000744 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000745 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000746 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000747 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000749 clearerr(f->f_fp);
750 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000751 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752 Py_INCREF(Py_None);
753 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000754}
755
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000756static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000757file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000758{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000759 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000760 if (f->f_fp == NULL)
761 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000762 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000763 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000765 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000766}
767
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000768
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000769#if BUFSIZ < 8192
770#define SMALLCHUNK 8192
771#else
772#define SMALLCHUNK BUFSIZ
773#endif
774
Guido van Rossum3c259041999-01-14 19:00:14 +0000775#if SIZEOF_INT < 4
776#define BIGCHUNK (512 * 32)
777#else
778#define BIGCHUNK (512 * 1024)
779#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000780
781static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000782new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000783{
784#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000785 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000786 struct stat st;
787 if (fstat(fileno(f->f_fp), &st) == 0) {
788 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000789 /* The following is not a bug: we really need to call lseek()
790 *and* ftell(). The reason is that some stdio libraries
791 mistakenly flush their buffer when ftell() is called and
792 the lseek() call it makes fails, thereby throwing away
793 data that cannot be recovered in any way. To avoid this,
794 we first test lseek(), and only call ftell() if lseek()
795 works. We can't use the lseek() value either, because we
796 need to take the amount of buffered data into account.
797 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000798 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000799 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000800 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000801 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000802 if (pos < 0)
803 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000804 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000805 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000806 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000807 }
808#endif
809 if (currentsize > SMALLCHUNK) {
810 /* Keep doubling until we reach BIGCHUNK;
811 then keep adding BIGCHUNK. */
812 if (currentsize <= BIGCHUNK)
813 return currentsize + currentsize;
814 else
815 return currentsize + BIGCHUNK;
816 }
817 return currentsize + SMALLCHUNK;
818}
819
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000820#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
821#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
822#else
823#ifdef EWOULDBLOCK
824#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
825#else
826#ifdef EAGAIN
827#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
828#else
829#define BLOCKED_ERRNO(x) 0
830#endif
831#endif
832#endif
833
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000834static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000835file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000836{
Guido van Rossum789a1611997-05-10 22:33:55 +0000837 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000838 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000839 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000840
Guido van Rossumd7297e61992-07-06 14:19:26 +0000841 if (f->f_fp == NULL)
842 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000843 /* refuse to mix with f.next() */
844 if (f->f_buf != NULL &&
845 (f->f_bufend - f->f_bufptr) > 0 &&
846 f->f_buf[0] != '\0')
847 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000848 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000849 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000850 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000851 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000852 else
853 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +0000854 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000855 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000856 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000857 return NULL;
858 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000859 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000860 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000861 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000862 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000863 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000864 Py_BEGIN_ALLOW_THREADS
865 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000866 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000867 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000868 Py_END_ALLOW_THREADS
869 if (chunksize == 0) {
870 if (!ferror(f->f_fp))
871 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000872 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000873 /* When in non-blocking mode, data shouldn't
874 * be discarded if a blocking signal was
875 * received. That will also happen if
876 * chunksize != 0, but bytesread < buffersize. */
877 if (bytesread > 0 && BLOCKED_ERRNO(errno))
878 break;
879 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000880 Py_DECREF(v);
881 return NULL;
882 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000883 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000884 if (bytesread < buffersize) {
885 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000886 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000887 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000888 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000889 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000890 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000891 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000892 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000893 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000894 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000895 }
896 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000897 if (bytesread != buffersize)
898 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000899 return v;
900}
901
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000902static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000903file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000904{
905 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000906 Py_ssize_t ntodo;
907 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000908
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000909 if (f->f_fp == NULL)
910 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000911 /* refuse to mix with f.next() */
912 if (f->f_buf != NULL &&
913 (f->f_bufend - f->f_bufptr) > 0 &&
914 f->f_buf[0] != '\0')
915 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000916 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000917 return NULL;
918 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000919 while (ntodo > 0) {
920 Py_BEGIN_ALLOW_THREADS
921 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000922 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000923 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000924 Py_END_ALLOW_THREADS
925 if (nnow == 0) {
926 if (!ferror(f->f_fp))
927 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000928 PyErr_SetFromErrno(PyExc_IOError);
929 clearerr(f->f_fp);
930 return NULL;
931 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000932 ndone += nnow;
933 ntodo -= nnow;
934 }
Neal Norwitz076d1e02006-08-21 18:20:10 +0000935 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000936}
937
Tim Peters86821b22001-01-07 21:19:34 +0000938/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000939Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000940
941Under MSVC 6:
942
Tim Peters1c733232001-01-08 04:02:07 +0000943+ MS threadsafe getc is very slow (multiple layers of function calls before+
944 after each character, to lock+unlock the stream).
945+ The stream-locking functions are MS-internal -- can't access them from user
946 code.
947+ There's nothing Tim could find in the MS C or platform SDK libraries that
948 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000949+ MS fgets locks/unlocks only once per line; it's the only hook we have.
950
951So we use fgets for speed(!), despite that it's painful.
952
953MS realloc is also slow.
954
Tim Petersf29b64d2001-01-15 06:33:19 +0000955Reports from other platforms on this method vs getc_unlocked (which MS doesn't
956have):
957 Linux a wash
958 Solaris a wash
959 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000960
Tim Petersf29b64d2001-01-15 06:33:19 +0000961CAUTION: The C std isn't clear about this: in those cases where fgets
962writes something into the buffer, can it write into any position beyond the
963required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
964known on which it does; and it would be a strange way to code fgets. Still,
965getline_via_fgets may not work correctly if it does. The std test
966test_bufio.py should fail if platform fgets() routinely writes beyond the
967trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000968**************************************************************************/
969
Tim Petersf29b64d2001-01-15 06:33:19 +0000970/* Use this routine if told to, or by default on non-get_unlocked()
971 * platforms unless told not to. Yikes! Let's spell that out:
972 * On a platform with getc_unlocked():
973 * By default, use getc_unlocked().
974 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
975 * On a platform without getc_unlocked():
976 * By default, use fgets().
977 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
978 */
979#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
980#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000981#endif
982
Tim Petersf29b64d2001-01-15 06:33:19 +0000983#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
984#undef USE_FGETS_IN_GETLINE
985#endif
986
987#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000988static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000989getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000990{
Tim Peters15b83852001-01-08 00:53:12 +0000991/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +0000992 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
993 * to fill this much of the buffer with a known value in order to figure out
994 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
995 * than "most" lines, we waste time filling unused buffer slots. 100 is
996 * surely adequate for most peoples' email archives, chewing over source code,
997 * etc -- "regular old text files".
998 * MAXBUFSIZE is the maximum line length that lets us get away with the less
999 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1000 * cautions about boosting that. 300 was chosen because the worst real-life
1001 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1002 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001003 */
Tim Peters142297a2001-01-15 10:36:56 +00001004#define INITBUFSIZE 100
1005#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001006 char* p; /* temp */
1007 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001008 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001009 char* pvfree; /* address of next free slot */
1010 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001011 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1012 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001013 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001014 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001015
Tim Peters15b83852001-01-08 00:53:12 +00001016 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001017 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001018 */
Tim Peters142297a2001-01-15 10:36:56 +00001019 total_v_size = INITBUFSIZE; /* start small and pray */
1020 pvfree = buf;
1021 for (;;) {
1022 Py_BEGIN_ALLOW_THREADS
1023 pvend = buf + total_v_size;
1024 nfree = pvend - pvfree;
1025 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001026 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1027 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +00001028 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001029
Tim Peters142297a2001-01-15 10:36:56 +00001030 if (p == NULL) {
1031 clearerr(fp);
1032 if (PyErr_CheckSignals())
1033 return NULL;
1034 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001035 return v;
1036 }
Tim Peters142297a2001-01-15 10:36:56 +00001037 /* fgets read *something* */
1038 p = memchr(pvfree, '\n', nfree);
1039 if (p != NULL) {
1040 /* Did the \n come from fgets or from us?
1041 * Since fgets stops at the first \n, and then writes
1042 * \0, if it's from fgets a \0 must be next. But if
1043 * that's so, it could not have come from us, since
1044 * the \n's we filled the buffer with have only more
1045 * \n's to the right.
1046 */
1047 if (p+1 < pvend && *(p+1) == '\0') {
1048 /* It's from fgets: we win! In particular,
1049 * we haven't done any mallocs yet, and can
1050 * build the final result on the first try.
1051 */
1052 ++p; /* include \n from fgets */
1053 }
1054 else {
1055 /* Must be from us: fgets didn't fill the
1056 * buffer and didn't find a newline, so it
1057 * must be the last and newline-free line of
1058 * the file.
1059 */
1060 assert(p > pvfree && *(p-1) == '\0');
1061 --p; /* don't include \0 from fgets */
1062 }
1063 v = PyString_FromStringAndSize(buf, p - buf);
1064 return v;
1065 }
1066 /* yuck: fgets overwrote all the newlines, i.e. the entire
1067 * buffer. So this line isn't over yet, or maybe it is but
1068 * we're exactly at EOF. If we haven't already, try using the
1069 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001070 */
Tim Peters142297a2001-01-15 10:36:56 +00001071 assert(*(pvend-1) == '\0');
1072 if (pvfree == buf) {
1073 pvfree = pvend - 1; /* overwrite trailing null */
1074 total_v_size = MAXBUFSIZE;
1075 }
1076 else
1077 break;
Tim Peters86821b22001-01-07 21:19:34 +00001078 }
Tim Peters142297a2001-01-15 10:36:56 +00001079
1080 /* The stack buffer isn't big enough; malloc a string object and read
1081 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001082 */
Tim Petersddea2082002-03-23 10:03:50 +00001083 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001084 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001085 if (v == NULL)
1086 return v;
1087 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001088 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1089 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001090
1091 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001092 * after setting p one beyond the end of the line. The code here is
1093 * very much like the code above, except reads into v's buffer; see
1094 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001095 */
1096 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001097 Py_BEGIN_ALLOW_THREADS
1098 pvend = BUF(v) + total_v_size;
1099 nfree = pvend - pvfree;
1100 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001101 assert(nfree < INT_MAX);
1102 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001103 Py_END_ALLOW_THREADS
1104
1105 if (p == NULL) {
1106 clearerr(fp);
1107 if (PyErr_CheckSignals()) {
1108 Py_DECREF(v);
1109 return NULL;
1110 }
1111 p = pvfree;
1112 break;
1113 }
Tim Peters86821b22001-01-07 21:19:34 +00001114 p = memchr(pvfree, '\n', nfree);
1115 if (p != NULL) {
1116 if (p+1 < pvend && *(p+1) == '\0') {
1117 /* \n came from fgets */
1118 ++p;
1119 break;
1120 }
1121 /* \n came from us; last line of file, no newline */
1122 assert(p > pvfree && *(p-1) == '\0');
1123 --p;
1124 break;
1125 }
1126 /* expand buffer and try again */
1127 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001128 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001129 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001130 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001131 /* check for overflow */
1132 if (total_v_size <= prev_v_size ||
1133 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001134 PyErr_SetString(PyExc_OverflowError,
1135 "line is longer than a Python string can hold");
1136 Py_DECREF(v);
1137 return NULL;
1138 }
1139 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1140 return NULL;
1141 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001142 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001143 }
1144 if (BUF(v) + total_v_size != p)
1145 _PyString_Resize(&v, p - BUF(v));
1146 return v;
1147#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001148#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001149}
Tim Petersf29b64d2001-01-15 06:33:19 +00001150#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001151
Guido van Rossum0bd24411991-04-04 15:21:57 +00001152/* Internal routine to get a line.
1153 Size argument interpretation:
1154 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001155 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001156*/
1157
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001158static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001159get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001160{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001161 FILE *fp = f->f_fp;
1162 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001163 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001164 size_t total_v_size; /* total # of slots in buffer */
1165 size_t used_v_size; /* # used slots in buffer */
1166 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001167 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001168 int newlinetypes = f->f_newlinetypes;
1169 int skipnextlf = f->f_skipnextlf;
1170 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001171
Jack Jansen7b8c7542002-04-14 20:12:41 +00001172#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001173 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001174 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001175#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001176 total_v_size = n > 0 ? n : 100;
1177 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001178 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001179 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001180 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001181 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001182
Guido van Rossumce5ba841991-03-06 13:06:18 +00001183 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001184 Py_BEGIN_ALLOW_THREADS
1185 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001186 if (univ_newline) {
1187 c = 'x'; /* Shut up gcc warning */
1188 while ( buf != end && (c = GETC(fp)) != EOF ) {
1189 if (skipnextlf ) {
1190 skipnextlf = 0;
1191 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001192 /* Seeing a \n here with
1193 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001194 * saw a \r before.
1195 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001196 newlinetypes |= NEWLINE_CRLF;
1197 c = GETC(fp);
1198 if (c == EOF) break;
1199 } else {
1200 newlinetypes |= NEWLINE_CR;
1201 }
1202 }
1203 if (c == '\r') {
1204 skipnextlf = 1;
1205 c = '\n';
1206 } else if ( c == '\n')
1207 newlinetypes |= NEWLINE_LF;
1208 *buf++ = c;
1209 if (c == '\n') break;
1210 }
1211 if ( c == EOF && skipnextlf )
1212 newlinetypes |= NEWLINE_CR;
1213 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001214 while ((c = GETC(fp)) != EOF &&
1215 (*buf++ = c) != '\n' &&
1216 buf != end)
1217 ;
1218 FUNLOCKFILE(fp);
1219 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001220 f->f_newlinetypes = newlinetypes;
1221 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001222 if (c == '\n')
1223 break;
1224 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001225 if (ferror(fp)) {
1226 PyErr_SetFromErrno(PyExc_IOError);
1227 clearerr(fp);
1228 Py_DECREF(v);
1229 return NULL;
1230 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001231 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001232 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001233 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001234 return NULL;
1235 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001236 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001237 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001238 /* Must be because buf == end */
1239 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001240 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001241 used_v_size = total_v_size;
1242 increment = total_v_size >> 2; /* mild exponential growth */
1243 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001244 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001245 PyErr_SetString(PyExc_OverflowError,
1246 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001247 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001248 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001249 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001250 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001251 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001252 buf = BUF(v) + used_v_size;
1253 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001254 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001255
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001256 used_v_size = buf - BUF(v);
1257 if (used_v_size != total_v_size)
1258 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001259 return v;
1260}
1261
Guido van Rossum0bd24411991-04-04 15:21:57 +00001262/* External C interface */
1263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001264PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001265PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001266{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001267 PyObject *result;
1268
Guido van Rossum3165fe61992-09-25 21:59:05 +00001269 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001270 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001271 return NULL;
1272 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001273
1274 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001275 PyFileObject *fo = (PyFileObject *)f;
1276 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001277 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001278 /* refuse to mix with f.next() */
1279 if (fo->f_buf != NULL &&
1280 (fo->f_bufend - fo->f_bufptr) > 0 &&
1281 fo->f_buf[0] != '\0')
1282 return err_iterbuffered();
1283 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001284 }
1285 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001286 PyObject *reader;
1287 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001288
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001289 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001290 if (reader == NULL)
1291 return NULL;
1292 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001293 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001294 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001295 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001296 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001297 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001298 return NULL;
1299 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001300 result = PyEval_CallObject(reader, args);
1301 Py_DECREF(reader);
1302 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001303 if (result != NULL && !PyString_Check(result) &&
1304 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001305 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001306 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001308 "object.readline() returned non-string");
1309 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001310 }
1311
1312 if (n < 0 && result != NULL && PyString_Check(result)) {
1313 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001314 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001315 if (len == 0) {
1316 Py_DECREF(result);
1317 result = NULL;
1318 PyErr_SetString(PyExc_EOFError,
1319 "EOF when reading a line");
1320 }
1321 else if (s[len-1] == '\n') {
1322 if (result->ob_refcnt == 1)
1323 _PyString_Resize(&result, len-1);
1324 else {
1325 PyObject *v;
1326 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001327 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001328 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001329 }
1330 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001331 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001332#ifdef Py_USING_UNICODE
1333 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1334 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001335 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001336 if (len == 0) {
1337 Py_DECREF(result);
1338 result = NULL;
1339 PyErr_SetString(PyExc_EOFError,
1340 "EOF when reading a line");
1341 }
1342 else if (s[len-1] == '\n') {
1343 if (result->ob_refcnt == 1)
1344 PyUnicode_Resize(&result, len-1);
1345 else {
1346 PyObject *v;
1347 v = PyUnicode_FromUnicode(s, len-1);
1348 Py_DECREF(result);
1349 result = v;
1350 }
1351 }
1352 }
1353#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001354 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001355}
1356
1357/* Python method */
1358
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001359static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001360file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001361{
Guido van Rossum789a1611997-05-10 22:33:55 +00001362 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001363
Guido van Rossumd7297e61992-07-06 14:19:26 +00001364 if (f->f_fp == NULL)
1365 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001366 /* refuse to mix with f.next() */
1367 if (f->f_buf != NULL &&
1368 (f->f_bufend - f->f_bufptr) > 0 &&
1369 f->f_buf[0] != '\0')
1370 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001371 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001372 return NULL;
1373 if (n == 0)
1374 return PyString_FromString("");
1375 if (n < 0)
1376 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001377 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001378}
1379
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001380static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001381file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001382{
Guido van Rossum789a1611997-05-10 22:33:55 +00001383 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001384 PyObject *list;
1385 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001386 char small_buffer[SMALLCHUNK];
1387 char *buffer = small_buffer;
1388 size_t buffersize = SMALLCHUNK;
1389 PyObject *big_buffer = NULL;
1390 size_t nfilled = 0;
1391 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001392 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001393 char *p, *q, *end;
1394 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001395 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001396
Guido van Rossumd7297e61992-07-06 14:19:26 +00001397 if (f->f_fp == NULL)
1398 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001399 /* refuse to mix with f.next() */
1400 if (f->f_buf != NULL &&
1401 (f->f_bufend - f->f_bufptr) > 0 &&
1402 f->f_buf[0] != '\0')
1403 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001404 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001405 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001406 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001407 return NULL;
1408 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001409 if (shortread)
1410 nread = 0;
1411 else {
1412 Py_BEGIN_ALLOW_THREADS
1413 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001414 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001415 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001416 Py_END_ALLOW_THREADS
1417 shortread = (nread < buffersize-nfilled);
1418 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001419 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001420 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001421 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001422 break;
1423 PyErr_SetFromErrno(PyExc_IOError);
1424 clearerr(f->f_fp);
1425 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001426 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001427 list = NULL;
1428 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001429 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001430 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001431 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001432 if (p == NULL) {
1433 /* Need a larger buffer to fit this line */
1434 nfilled += nread;
1435 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001436 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001437 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001438 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001439 goto error;
1440 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001441 if (big_buffer == NULL) {
1442 /* Create the big buffer */
1443 big_buffer = PyString_FromStringAndSize(
1444 NULL, buffersize);
1445 if (big_buffer == NULL)
1446 goto error;
1447 buffer = PyString_AS_STRING(big_buffer);
1448 memcpy(buffer, small_buffer, nfilled);
1449 }
1450 else {
1451 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001452 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1453 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001454 buffer = PyString_AS_STRING(big_buffer);
1455 }
1456 continue;
1457 }
1458 end = buffer+nfilled+nread;
1459 q = buffer;
1460 do {
1461 /* Process complete lines */
1462 p++;
1463 line = PyString_FromStringAndSize(q, p-q);
1464 if (line == NULL)
1465 goto error;
1466 err = PyList_Append(list, line);
1467 Py_DECREF(line);
1468 if (err != 0)
1469 goto error;
1470 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001471 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001472 } while (p != NULL);
1473 /* Move the remaining incomplete line to the start */
1474 nfilled = end-q;
1475 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001476 if (sizehint > 0)
1477 if (totalread >= (size_t)sizehint)
1478 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001479 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001480 if (nfilled != 0) {
1481 /* Partial last line */
1482 line = PyString_FromStringAndSize(buffer, nfilled);
1483 if (line == NULL)
1484 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001485 if (sizehint > 0) {
1486 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001487 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001488 if (rest == NULL) {
1489 Py_DECREF(line);
1490 goto error;
1491 }
1492 PyString_Concat(&line, rest);
1493 Py_DECREF(rest);
1494 if (line == NULL)
1495 goto error;
1496 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001497 err = PyList_Append(list, line);
1498 Py_DECREF(line);
1499 if (err != 0)
1500 goto error;
1501 }
1502 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001503 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001504 return list;
1505}
1506
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001507static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001508file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001509{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001510 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001511 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001512 if (f->f_fp == NULL)
1513 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001514 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001515 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001516 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001517 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001518 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001519 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001520 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001521 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001522 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001523 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001524 return NULL;
1525 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001526 Py_INCREF(Py_None);
1527 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001528}
1529
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001530static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001531file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001532{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001533#define CHUNKSIZE 1000
1534 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001535 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001536 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001537 int index, islist;
1538 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001539
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001540 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001541 if (f->f_fp == NULL)
1542 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001543
1544 result = NULL;
1545 list = NULL;
1546 islist = PyList_Check(seq);
1547 if (islist)
1548 it = NULL;
1549 else {
1550 it = PyObject_GetIter(seq);
1551 if (it == NULL) {
1552 PyErr_SetString(PyExc_TypeError,
1553 "writelines() requires an iterable argument");
1554 return NULL;
1555 }
1556 /* From here on, fail by going to error, to reclaim "it". */
1557 list = PyList_New(CHUNKSIZE);
1558 if (list == NULL)
1559 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001560 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001561
1562 /* Strategy: slurp CHUNKSIZE lines into a private list,
1563 checking that they are all strings, then write that list
1564 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001565 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001566 if (islist) {
1567 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001568 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001569 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001570 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001571 j = PyList_GET_SIZE(list);
1572 }
1573 else {
1574 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001575 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001576 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001577 if (PyErr_Occurred())
1578 goto error;
1579 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001580 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001581 PyList_SetItem(list, j, line);
1582 }
1583 }
1584 if (j == 0)
1585 break;
1586
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001587 /* Check that all entries are indeed strings. If not,
1588 apply the same rules as for file.write() and
1589 convert the results to strings. This is slow, but
1590 seems to be the only way since all conversion APIs
1591 could potentially execute Python code. */
1592 for (i = 0; i < j; i++) {
1593 PyObject *v = PyList_GET_ITEM(list, i);
1594 if (!PyString_Check(v)) {
1595 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001596 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001597 PyObject_AsReadBuffer(v,
1598 (const void**)&buffer,
1599 &len)) ||
1600 PyObject_AsCharBuffer(v,
1601 &buffer,
1602 &len))) {
1603 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001604 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001605 goto error;
1606 }
1607 line = PyString_FromStringAndSize(buffer,
1608 len);
1609 if (line == NULL)
1610 goto error;
1611 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001612 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001613 }
1614 }
1615
1616 /* Since we are releasing the global lock, the
1617 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001618 Py_BEGIN_ALLOW_THREADS
1619 f->f_softspace = 0;
1620 errno = 0;
1621 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001622 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001623 len = PyString_GET_SIZE(line);
1624 nwritten = fwrite(PyString_AS_STRING(line),
1625 1, len, f->f_fp);
1626 if (nwritten != len) {
1627 Py_BLOCK_THREADS
1628 PyErr_SetFromErrno(PyExc_IOError);
1629 clearerr(f->f_fp);
1630 goto error;
1631 }
1632 }
1633 Py_END_ALLOW_THREADS
1634
1635 if (j < CHUNKSIZE)
1636 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001637 }
1638
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001639 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001640 result = Py_None;
1641 error:
1642 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001643 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001644 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001645#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001646}
1647
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001648static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001649file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001650{
1651 if (f->f_fp == NULL)
1652 return err_closed();
1653 Py_INCREF(f);
1654 return (PyObject *)f;
1655}
1656
Georg Brandl98b40ad2006-06-08 14:50:21 +00001657static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001658file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001659{
Georg Brandlad61bc82008-02-23 15:11:18 +00001660 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001661 if (!ret)
1662 /* If error occurred, pass through */
1663 return NULL;
1664 Py_DECREF(ret);
1665 /* We cannot return the result of close since a true
1666 * value will be interpreted as "yes, swallow the
1667 * exception if one was raised inside the with block". */
1668 Py_RETURN_NONE;
1669}
1670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001671PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001672"readline([size]) -> next line from the file, as a string.\n"
1673"\n"
1674"Retain newline. A non-negative size argument limits the maximum\n"
1675"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001676"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001678PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001679"read([size]) -> read at most size bytes, returned as a string.\n"
1680"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001681"If the size argument is negative or omitted, read until EOF is reached.\n"
1682"Notice that when in non-blocking mode, less data than what was requested\n"
1683"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001684
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001685PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001686"write(str) -> None. Write string str to file.\n"
1687"\n"
1688"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001689"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001691PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001692"fileno() -> integer \"file descriptor\".\n"
1693"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001694"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001696PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001697"seek(offset[, whence]) -> None. Move to new file position.\n"
1698"\n"
1699"Argument offset is a byte count. Optional argument whence defaults to\n"
1700"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1701"(move relative to current position, positive or negative), and 2 (move\n"
1702"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001703"seeking beyond the end of a file). If the file is opened in text mode,\n"
1704"only offsets returned by tell() are legal. Use of other offsets causes\n"
1705"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001706"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001707"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001708
Guido van Rossumd7047b31995-01-02 19:07:15 +00001709#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001710PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001711"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1712"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001713"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001714#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001716PyDoc_STRVAR(tell_doc,
1717"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001719PyDoc_STRVAR(readinto_doc,
1720"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001722PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001723"readlines([size]) -> list of strings, each a line from the file.\n"
1724"\n"
1725"Call readline() repeatedly and return a list of the lines so read.\n"
1726"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001727"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001729PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001730"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001731"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001732"For backward compatibility. File objects now include the performance\n"
1733"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001734
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001736"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001737"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001738"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001739"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001741PyDoc_STRVAR(flush_doc,
1742"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001744PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001745"close() -> None or (perhaps) an integer. Close the file.\n"
1746"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001747"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001748"further I/O operations. close() may be called more than once without\n"
1749"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001750"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001752PyDoc_STRVAR(isatty_doc,
1753"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001754
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001755PyDoc_STRVAR(enter_doc,
1756 "__enter__() -> self.");
1757
Georg Brandl98b40ad2006-06-08 14:50:21 +00001758PyDoc_STRVAR(exit_doc,
1759 "__exit__(*excinfo) -> None. Closes the file.");
1760
Tim Petersefc3a3a2001-09-20 07:55:22 +00001761static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001762 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1763 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1764 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1765 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1766 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001767#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001768 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001769#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001770 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1771 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1772 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001773 {"xreadlines",(PyCFunction)file_self, METH_NOARGS, xreadlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001774 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1775 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1776 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1777 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001778 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00001779 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001780 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001781};
1782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001783#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001784
Guido van Rossum6f799372001-09-20 20:46:19 +00001785static PyMemberDef file_memberlist[] = {
1786 {"softspace", T_INT, OFF(f_softspace), 0,
1787 "flag indicating that a space needs to be printed; used by print"},
1788 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001789 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001790 {"name", T_OBJECT, OFF(f_name), RO,
1791 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001792 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1793 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001794 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001795 {NULL} /* Sentinel */
1796};
1797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001798static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001800{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001801 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001802}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001803static PyObject *
1804get_newlines(PyFileObject *f, void *closure)
1805{
1806 switch (f->f_newlinetypes) {
1807 case NEWLINE_UNKNOWN:
1808 Py_INCREF(Py_None);
1809 return Py_None;
1810 case NEWLINE_CR:
1811 return PyString_FromString("\r");
1812 case NEWLINE_LF:
1813 return PyString_FromString("\n");
1814 case NEWLINE_CR|NEWLINE_LF:
1815 return Py_BuildValue("(ss)", "\r", "\n");
1816 case NEWLINE_CRLF:
1817 return PyString_FromString("\r\n");
1818 case NEWLINE_CR|NEWLINE_CRLF:
1819 return Py_BuildValue("(ss)", "\r", "\r\n");
1820 case NEWLINE_LF|NEWLINE_CRLF:
1821 return Py_BuildValue("(ss)", "\n", "\r\n");
1822 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1823 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1824 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001825 PyErr_Format(PyExc_SystemError,
1826 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001827 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001828 return NULL;
1829 }
1830}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001831
Guido van Rossum32d34c82001-09-20 21:45:26 +00001832static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001833 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001834 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001835 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 {0},
1837};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001838
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001839static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001840drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001841{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001842 if (f->f_buf != NULL) {
1843 PyMem_Free(f->f_buf);
1844 f->f_buf = NULL;
1845 }
Guido van Rossum65967252001-04-21 13:20:18 +00001846}
1847
Tim Petersf1827cf2003-09-07 03:30:18 +00001848/* Make sure that file has a readahead buffer with at least one byte
1849 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00001850 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001851static int
1852readahead(PyFileObject *f, int bufsize)
1853{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001854 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001855
1856 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001857 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001858 return 0;
1859 else
1860 drop_readahead(f);
1861 }
Anthony Baxter377be112006-04-11 06:54:30 +00001862 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00001863 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001864 return -1;
1865 }
1866 Py_BEGIN_ALLOW_THREADS
1867 errno = 0;
1868 chunksize = Py_UniversalNewlineFread(
1869 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1870 Py_END_ALLOW_THREADS
1871 if (chunksize == 0) {
1872 if (ferror(f->f_fp)) {
1873 PyErr_SetFromErrno(PyExc_IOError);
1874 clearerr(f->f_fp);
1875 drop_readahead(f);
1876 return -1;
1877 }
1878 }
1879 f->f_bufptr = f->f_buf;
1880 f->f_bufend = f->f_buf + chunksize;
1881 return 0;
1882}
1883
1884/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001885 uninitialized bytes followed by the remainder of the line. Don't be
1886 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001887 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1888
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001889static PyStringObject *
1890readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1891{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001892 PyStringObject* s;
1893 char *bufptr;
1894 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001895 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001896
1897 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001898 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001899 return NULL;
1900
1901 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001902 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001903 return (PyStringObject *)
1904 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00001905 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001906 if (bufptr != NULL) {
1907 bufptr++; /* Count the '\n' */
1908 len = bufptr - f->f_bufptr;
1909 s = (PyStringObject *)
1910 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001911 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001912 return NULL;
1913 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1914 f->f_bufptr = bufptr;
1915 if (bufptr == f->f_bufend)
1916 drop_readahead(f);
1917 } else {
1918 bufptr = f->f_bufptr;
1919 buf = f->f_buf;
1920 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001921 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001922 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001923 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001924 if (s == NULL) {
1925 PyMem_Free(buf);
1926 return NULL;
1927 }
1928 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1929 PyMem_Free(buf);
1930 }
1931 return s;
1932}
1933
1934/* A larger buffer size may actually decrease performance. */
1935#define READAHEAD_BUFSIZE 8192
1936
1937static PyObject *
1938file_iternext(PyFileObject *f)
1939{
1940 PyStringObject* l;
1941
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001942 if (f->f_fp == NULL)
1943 return err_closed();
1944
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001945 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1946 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1947 Py_XDECREF(l);
1948 return NULL;
1949 }
1950 return (PyObject *)l;
1951}
1952
1953
Tim Peters59c9a642001-09-13 05:38:56 +00001954static PyObject *
1955file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1956{
Tim Peters44410012001-09-14 03:26:08 +00001957 PyObject *self;
1958 static PyObject *not_yet_string;
1959
1960 assert(type != NULL && type->tp_alloc != NULL);
1961
1962 if (not_yet_string == NULL) {
Christian Heimesd7e1b2b2008-01-28 02:07:53 +00001963 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00001964 if (not_yet_string == NULL)
1965 return NULL;
1966 }
1967
1968 self = type->tp_alloc(type, 0);
1969 if (self != NULL) {
1970 /* Always fill in the name and mode, so that nobody else
1971 needs to special-case NULLs there. */
1972 Py_INCREF(not_yet_string);
1973 ((PyFileObject *)self)->f_name = not_yet_string;
1974 Py_INCREF(not_yet_string);
1975 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001976 Py_INCREF(Py_None);
1977 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001978 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001979 }
1980 return self;
1981}
1982
1983static int
1984file_init(PyObject *self, PyObject *args, PyObject *kwds)
1985{
1986 PyFileObject *foself = (PyFileObject *)self;
1987 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001988 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001989 char *name = NULL;
1990 char *mode = "r";
1991 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001992 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00001993
1994 assert(PyFile_Check(self));
1995 if (foself->f_fp != NULL) {
1996 /* Have to close the existing file first. */
1997 PyObject *closeresult = file_close(foself);
1998 if (closeresult == NULL)
1999 return -1;
2000 Py_DECREF(closeresult);
2001 }
Tim Peters59c9a642001-09-13 05:38:56 +00002002
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002003#ifdef Py_WIN_WIDE_FILENAMES
2004 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2005 PyObject *po;
2006 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2007 kwlist, &po, &mode, &bufsize)) {
2008 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002009 if (fill_file_fields(foself, NULL, po, mode,
2010 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002011 goto Error;
2012 } else {
2013 /* Drop the argument parsing error as narrow
2014 strings are also valid. */
2015 PyErr_Clear();
2016 }
2017 }
2018#endif
2019
2020 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002021 PyObject *o_name;
2022
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002023 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2024 Py_FileSystemDefaultEncoding,
2025 &name,
2026 &mode, &bufsize))
2027 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002028
2029 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002030 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2031 kwlist, &o_name, &mode,
2032 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002033 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002034
2035 if (fill_file_fields(foself, NULL, o_name, mode,
2036 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002037 goto Error;
2038 }
Tim Peters44410012001-09-14 03:26:08 +00002039 if (open_the_file(foself, name, mode) == NULL)
2040 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002041 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002042 PyFile_SetBufSize(self, bufsize);
2043 goto Done;
2044
2045Error:
2046 ret = -1;
2047 /* fall through */
2048Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002049 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002050 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002051}
2052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002053PyDoc_VAR(file_doc) =
2054PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002055"file(name[, mode[, buffering]]) -> file object\n"
2056"\n"
2057"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2058"writing or appending. The file will be created if it doesn't exist\n"
2059"when opened for writing or appending; it will be truncated when\n"
2060"opened for writing. Add a 'b' to the mode for binary files.\n"
2061"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2062"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002063"buffered, and larger numbers specify the buffer size. The preferred way\n"
2064"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002065)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002066PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002067"Add a 'U' to mode to open the file for input with universal newline\n"
2068"support. Any line ending in the input file will be seen as a '\\n'\n"
2069"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2070"the value for this attribute is one of None (no newline read yet),\n"
2071"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2072"\n"
2073"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002074);
Tim Peters59c9a642001-09-13 05:38:56 +00002075
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002076PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002077 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002078 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002079 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002080 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002081 (destructor)file_dealloc, /* tp_dealloc */
2082 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 0, /* tp_getattr */
2084 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002085 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002087 0, /* tp_as_number */
2088 0, /* tp_as_sequence */
2089 0, /* tp_as_mapping */
2090 0, /* tp_hash */
2091 0, /* tp_call */
2092 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002093 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002094 /* softspace is writable: we must supply tp_setattro */
2095 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002096 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002097 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002098 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099 0, /* tp_traverse */
2100 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002101 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002102 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002103 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002104 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105 file_methods, /* tp_methods */
2106 file_memberlist, /* tp_members */
2107 file_getsetlist, /* tp_getset */
2108 0, /* tp_base */
2109 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002110 0, /* tp_descr_get */
2111 0, /* tp_descr_set */
2112 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002113 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002114 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002115 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002116 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002117};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002118
2119/* Interface for the 'soft space' between print items. */
2120
2121int
Fred Drakefd99de62000-07-09 05:02:18 +00002122PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002123{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002124 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002125 if (f == NULL) {
2126 /* Do nothing */
2127 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002128 else if (PyFile_Check(f)) {
2129 oldflag = ((PyFileObject *)f)->f_softspace;
2130 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002131 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002132 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002133 PyObject *v;
2134 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002135 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002137 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002138 if (PyInt_Check(v))
2139 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002140 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002142 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002143 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002144 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002145 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002146 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002147 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2148 PyErr_Clear();
2149 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002150 }
2151 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002152 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002153}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002154
2155/* Interfaces to write objects/strings to file-like objects */
2156
2157int
Fred Drakefd99de62000-07-09 05:02:18 +00002158PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002159{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002160 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002161 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002162 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002163 return -1;
2164 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002165 else if (PyFile_Check(f)) {
2166 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002167#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002168 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2169 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002170#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002171 if (fp == NULL) {
2172 err_closed();
2173 return -1;
2174 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002175#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002176 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002177 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002178 char *cenc = PyString_AS_STRING(enc);
2179 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2180 if (value == NULL)
2181 return -1;
2182 } else {
2183 value = v;
2184 Py_INCREF(value);
2185 }
2186 result = PyObject_Print(value, fp, flags);
2187 Py_DECREF(value);
2188 return result;
2189#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002190 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002191#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002192 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002193 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002194 if (writer == NULL)
2195 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002196 if (flags & Py_PRINT_RAW) {
2197 if (PyUnicode_Check(v)) {
2198 value = v;
2199 Py_INCREF(value);
2200 } else
2201 value = PyObject_Str(v);
2202 }
2203 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002204 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002205 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002206 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002207 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002208 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002209 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002210 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002211 Py_DECREF(value);
2212 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002213 return -1;
2214 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002215 result = PyEval_CallObject(writer, args);
2216 Py_DECREF(args);
2217 Py_DECREF(value);
2218 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002219 if (result == NULL)
2220 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002221 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002222 return 0;
2223}
2224
Guido van Rossum27a60b11997-05-22 22:25:11 +00002225int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002226PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002227{
2228 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002229 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002230 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002231 PyErr_SetString(PyExc_SystemError,
2232 "null file for PyFile_WriteString");
2233 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002234 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002235 else if (PyFile_Check(f)) {
2236 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002237 if (fp == NULL) {
2238 err_closed();
2239 return -1;
2240 }
Brett Cannon01531592007-09-17 03:28:34 +00002241 Py_BEGIN_ALLOW_THREADS
Guido van Rossum27a60b11997-05-22 22:25:11 +00002242 fputs(s, fp);
Brett Cannon01531592007-09-17 03:28:34 +00002243 Py_END_ALLOW_THREADS
Guido van Rossum27a60b11997-05-22 22:25:11 +00002244 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002245 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002246 else if (!PyErr_Occurred()) {
2247 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002248 int err;
2249 if (v == NULL)
2250 return -1;
2251 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2252 Py_DECREF(v);
2253 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002254 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002255 else
2256 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002257}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002258
2259/* Try to get a file-descriptor from a Python object. If the object
2260 is an integer or long integer, its value is returned. If not, the
2261 object's fileno() method is called if it exists; the method must return
2262 an integer or long integer, which is returned as the file descriptor value.
2263 -1 is returned on failure.
2264*/
2265
2266int PyObject_AsFileDescriptor(PyObject *o)
2267{
2268 int fd;
2269 PyObject *meth;
2270
2271 if (PyInt_Check(o)) {
2272 fd = PyInt_AsLong(o);
2273 }
2274 else if (PyLong_Check(o)) {
2275 fd = PyLong_AsLong(o);
2276 }
2277 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2278 {
2279 PyObject *fno = PyEval_CallObject(meth, NULL);
2280 Py_DECREF(meth);
2281 if (fno == NULL)
2282 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002283
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002284 if (PyInt_Check(fno)) {
2285 fd = PyInt_AsLong(fno);
2286 Py_DECREF(fno);
2287 }
2288 else if (PyLong_Check(fno)) {
2289 fd = PyLong_AsLong(fno);
2290 Py_DECREF(fno);
2291 }
2292 else {
2293 PyErr_SetString(PyExc_TypeError,
2294 "fileno() returned a non-integer");
2295 Py_DECREF(fno);
2296 return -1;
2297 }
2298 }
2299 else {
2300 PyErr_SetString(PyExc_TypeError,
2301 "argument must be an int, or have a fileno() method.");
2302 return -1;
2303 }
2304
2305 if (fd < 0) {
2306 PyErr_Format(PyExc_ValueError,
2307 "file descriptor cannot be a negative integer (%i)",
2308 fd);
2309 return -1;
2310 }
2311 return fd;
2312}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002313
Jack Jansen7b8c7542002-04-14 20:12:41 +00002314/* From here on we need access to the real fgets and fread */
2315#undef fgets
2316#undef fread
2317
2318/*
2319** Py_UniversalNewlineFgets is an fgets variation that understands
2320** all of \r, \n and \r\n conventions.
2321** The stream should be opened in binary mode.
2322** If fobj is NULL the routine always does newline conversion, and
2323** it may peek one char ahead to gobble the second char in \r\n.
2324** If fobj is non-NULL it must be a PyFileObject. In this case there
2325** is no readahead but in stead a flag is used to skip a following
2326** \n on the next read. Also, if the file is open in binary mode
2327** the whole conversion is skipped. Finally, the routine keeps track of
2328** the different types of newlines seen.
2329** Note that we need no error handling: fgets() treats error and eof
2330** identically.
2331*/
2332char *
2333Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2334{
2335 char *p = buf;
2336 int c;
2337 int newlinetypes = 0;
2338 int skipnextlf = 0;
2339 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002340
Jack Jansen7b8c7542002-04-14 20:12:41 +00002341 if (fobj) {
2342 if (!PyFile_Check(fobj)) {
2343 errno = ENXIO; /* What can you do... */
2344 return NULL;
2345 }
2346 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2347 if ( !univ_newline )
2348 return fgets(buf, n, stream);
2349 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2350 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2351 }
2352 FLOCKFILE(stream);
2353 c = 'x'; /* Shut up gcc warning */
2354 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2355 if (skipnextlf ) {
2356 skipnextlf = 0;
2357 if (c == '\n') {
2358 /* Seeing a \n here with skipnextlf true
2359 ** means we saw a \r before.
2360 */
2361 newlinetypes |= NEWLINE_CRLF;
2362 c = GETC(stream);
2363 if (c == EOF) break;
2364 } else {
2365 /*
2366 ** Note that c == EOF also brings us here,
2367 ** so we're okay if the last char in the file
2368 ** is a CR.
2369 */
2370 newlinetypes |= NEWLINE_CR;
2371 }
2372 }
2373 if (c == '\r') {
2374 /* A \r is translated into a \n, and we skip
2375 ** an adjacent \n, if any. We don't set the
2376 ** newlinetypes flag until we've seen the next char.
2377 */
2378 skipnextlf = 1;
2379 c = '\n';
2380 } else if ( c == '\n') {
2381 newlinetypes |= NEWLINE_LF;
2382 }
2383 *p++ = c;
2384 if (c == '\n') break;
2385 }
2386 if ( c == EOF && skipnextlf )
2387 newlinetypes |= NEWLINE_CR;
2388 FUNLOCKFILE(stream);
2389 *p = '\0';
2390 if (fobj) {
2391 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2392 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2393 } else if ( skipnextlf ) {
2394 /* If we have no file object we cannot save the
2395 ** skipnextlf flag. We have to readahead, which
2396 ** will cause a pause if we're reading from an
2397 ** interactive stream, but that is very unlikely
2398 ** unless we're doing something silly like
2399 ** execfile("/dev/tty").
2400 */
2401 c = GETC(stream);
2402 if ( c != '\n' )
2403 ungetc(c, stream);
2404 }
2405 if (p == buf)
2406 return NULL;
2407 return buf;
2408}
2409
2410/*
2411** Py_UniversalNewlineFread is an fread variation that understands
2412** all of \r, \n and \r\n conventions.
2413** The stream should be opened in binary mode.
2414** fobj must be a PyFileObject. In this case there
2415** is no readahead but in stead a flag is used to skip a following
2416** \n on the next read. Also, if the file is open in binary mode
2417** the whole conversion is skipped. Finally, the routine keeps track of
2418** the different types of newlines seen.
2419*/
2420size_t
Tim Peters058b1412002-04-21 07:29:14 +00002421Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002422 FILE *stream, PyObject *fobj)
2423{
Tim Peters058b1412002-04-21 07:29:14 +00002424 char *dst = buf;
2425 PyFileObject *f = (PyFileObject *)fobj;
2426 int newlinetypes, skipnextlf;
2427
2428 assert(buf != NULL);
2429 assert(stream != NULL);
2430
Jack Jansen7b8c7542002-04-14 20:12:41 +00002431 if (!fobj || !PyFile_Check(fobj)) {
2432 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002433 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002434 }
Tim Peters058b1412002-04-21 07:29:14 +00002435 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002436 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002437 newlinetypes = f->f_newlinetypes;
2438 skipnextlf = f->f_skipnextlf;
2439 /* Invariant: n is the number of bytes remaining to be filled
2440 * in the buffer.
2441 */
2442 while (n) {
2443 size_t nread;
2444 int shortread;
2445 char *src = dst;
2446
2447 nread = fread(dst, 1, n, stream);
2448 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002449 if (nread == 0)
2450 break;
2451
Tim Peterse1682a82002-04-21 18:15:20 +00002452 n -= nread; /* assuming 1 byte out for each in; will adjust */
2453 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002454 while (nread--) {
2455 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002456 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002457 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002458 *dst++ = '\n';
2459 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002460 }
2461 else if (skipnextlf && c == '\n') {
2462 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002463 skipnextlf = 0;
2464 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002465 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002466 }
2467 else {
2468 /* Normal char to be stored in buffer. Also
2469 * update the newlinetypes flag if either this
2470 * is an LF or the previous char was a CR.
2471 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002472 if (c == '\n')
2473 newlinetypes |= NEWLINE_LF;
2474 else if (skipnextlf)
2475 newlinetypes |= NEWLINE_CR;
2476 *dst++ = c;
2477 skipnextlf = 0;
2478 }
2479 }
Tim Peters058b1412002-04-21 07:29:14 +00002480 if (shortread) {
2481 /* If this is EOF, update type flags. */
2482 if (skipnextlf && feof(stream))
2483 newlinetypes |= NEWLINE_CR;
2484 break;
2485 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002486 }
Tim Peters058b1412002-04-21 07:29:14 +00002487 f->f_newlinetypes = newlinetypes;
2488 f->f_skipnextlf = skipnextlf;
2489 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002490}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002491
2492#ifdef __cplusplus
2493}
2494#endif