blob: 6f8eb7c65c678216b1bcbf62f88e802d14e55140 [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)) {
86#ifdef HAVE_STRERROR
87 char *msg = strerror(EISDIR);
88#else
89 char *msg = "Is a directory";
90#endif
Tim Petersf1827cf2003-09-07 03:30:18 +000091 PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
Jeremy Hylton8b735422002-08-14 21:01:41 +000092 EISDIR, msg);
Neil Schemenauered19b882002-03-23 02:06:50 +000093 PyErr_SetObject(PyExc_IOError, exc);
Neal Norwitz98cad482003-08-15 20:05:45 +000094 Py_XDECREF(exc);
Neil Schemenauered19b882002-03-23 02:06:50 +000095 return NULL;
96 }
97#endif
98 return f;
99}
100
Tim Peters59c9a642001-09-13 05:38:56 +0000101
102static PyObject *
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000103fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
104 int (*close)(FILE *))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105{
Neal Norwitzb337bb52006-07-17 00:55:45 +0000106 assert(name != NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000107 assert(f != NULL);
108 assert(PyFile_Check(f));
Tim Peters44410012001-09-14 03:26:08 +0000109 assert(f->f_fp == NULL);
110
111 Py_DECREF(f->f_name);
112 Py_DECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000113 Py_DECREF(f->f_encoding);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000114
Neal Norwitzb337bb52006-07-17 00:55:45 +0000115 Py_INCREF(name);
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000116 f->f_name = name;
117
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 f->f_mode = PyString_FromString(mode);
Tim Peters44410012001-09-14 03:26:08 +0000119
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000120 f->f_close = close;
Guido van Rossumeb183da1991-04-04 10:44:06 +0000121 f->f_softspace = 0;
Tim Peters59c9a642001-09-13 05:38:56 +0000122 f->f_binary = strchr(mode,'b') != NULL;
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000123 f->f_buf = NULL;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000124 f->f_univ_newline = (strchr(mode, 'U') != NULL);
125 f->f_newlinetypes = NEWLINE_UNKNOWN;
126 f->f_skipnextlf = 0;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000127 Py_INCREF(Py_None);
128 f->f_encoding = Py_None;
Tim Petersf1827cf2003-09-07 03:30:18 +0000129
Neal Norwitzb337bb52006-07-17 00:55:45 +0000130 if (f->f_mode == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 f->f_fp = fp;
Neil Schemenauered19b882002-03-23 02:06:50 +0000133 f = dircheck(f);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134 return (PyObject *) f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135}
136
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000137/* check for known incorrect mode strings - problem is, platforms are
138 free to accept any mode characters they like and are supposed to
139 ignore stuff they don't understand... write or append mode with
Georg Brandl7b90e162006-05-18 07:01:27 +0000140 universal newline support is expressly forbidden by PEP 278.
141 Additionally, remove the 'U' from the mode string as platforms
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000142 won't know what it is. Non-zero return signals an exception */
143int
144_PyFile_SanitizeMode(char *mode)
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000145{
Georg Brandl7b90e162006-05-18 07:01:27 +0000146 char *upos;
Neal Norwitz76dc0812006-01-08 06:13:13 +0000147 size_t len = strlen(mode);
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000148
Georg Brandl7b90e162006-05-18 07:01:27 +0000149 if (!len) {
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000150 PyErr_SetString(PyExc_ValueError, "empty mode string");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000151 return -1;
Georg Brandl7b90e162006-05-18 07:01:27 +0000152 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000153
Georg Brandl7b90e162006-05-18 07:01:27 +0000154 upos = strchr(mode, 'U');
155 if (upos) {
156 memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000157
Georg Brandl7b90e162006-05-18 07:01:27 +0000158 if (mode[0] == 'w' || mode[0] == 'a') {
159 PyErr_Format(PyExc_ValueError, "universal newline "
160 "mode can only be used with modes "
161 "starting with 'r'");
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000162 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000163 }
Georg Brandl7b90e162006-05-18 07:01:27 +0000164
165 if (mode[0] != 'r') {
166 memmove(mode+1, mode, strlen(mode)+1);
167 mode[0] = 'r';
168 }
169
170 if (!strchr(mode, 'b')) {
171 memmove(mode+2, mode+1, strlen(mode));
172 mode[1] = 'b';
173 }
174 } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
175 PyErr_Format(PyExc_ValueError, "mode string must begin with "
176 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000177 return -1;
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000178 }
179
180 return 0;
181}
182
Tim Peters59c9a642001-09-13 05:38:56 +0000183static PyObject *
184open_the_file(PyFileObject *f, char *name, char *mode)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Georg Brandl7b90e162006-05-18 07:01:27 +0000186 char *newmode;
Tim Peters59c9a642001-09-13 05:38:56 +0000187 assert(f != NULL);
188 assert(PyFile_Check(f));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000189#ifdef MS_WINDOWS
190 /* windows ignores the passed name in order to support Unicode */
191 assert(f->f_name != NULL);
192#else
Tim Peters59c9a642001-09-13 05:38:56 +0000193 assert(name != NULL);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000194#endif
Tim Peters59c9a642001-09-13 05:38:56 +0000195 assert(mode != NULL);
Tim Peters44410012001-09-14 03:26:08 +0000196 assert(f->f_fp == NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000197
Georg Brandl7b90e162006-05-18 07:01:27 +0000198 /* probably need to replace 'U' by 'rb' */
199 newmode = PyMem_MALLOC(strlen(mode) + 3);
200 if (!newmode) {
201 PyErr_NoMemory();
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000202 return NULL;
Georg Brandl7b90e162006-05-18 07:01:27 +0000203 }
204 strcpy(newmode, mode);
205
Kristján Valur Jónsson0a440d42007-04-26 09:15:08 +0000206 if (_PyFile_SanitizeMode(newmode)) {
Georg Brandl7b90e162006-05-18 07:01:27 +0000207 f = NULL;
208 goto cleanup;
209 }
Skip Montanarobbf12ba2005-05-20 03:07:06 +0000210
Tim Peters8fa45672001-09-13 21:01:29 +0000211 /* rexec.py can't stop a user from getting the file() constructor --
212 all they have to do is get *any* file object f, and then do
213 type(f). Here we prevent them from doing damage with it. */
214 if (PyEval_GetRestricted()) {
215 PyErr_SetString(PyExc_IOError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000216 "file() constructor not accessible in restricted mode");
Georg Brandl7b90e162006-05-18 07:01:27 +0000217 f = NULL;
218 goto cleanup;
Tim Peters8fa45672001-09-13 21:01:29 +0000219 }
Tim Petersa27a1502001-11-09 20:59:14 +0000220 errno = 0;
Skip Montanaro51ffac62004-06-11 04:49:03 +0000221
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000222#ifdef MS_WINDOWS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000223 if (PyUnicode_Check(f->f_name)) {
224 PyObject *wmode;
Georg Brandl7b90e162006-05-18 07:01:27 +0000225 wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000226 if (f->f_name && wmode) {
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000227 Py_BEGIN_ALLOW_THREADS
Skip Montanaro51ffac62004-06-11 04:49:03 +0000228 /* PyUnicode_AS_UNICODE OK without thread
229 lock as it is a simple dereference. */
230 f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
231 PyUnicode_AS_UNICODE(wmode));
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000232 Py_END_ALLOW_THREADS
233 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000234 Py_XDECREF(wmode);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000235 }
Skip Montanaro51ffac62004-06-11 04:49:03 +0000236#endif
237 if (NULL == f->f_fp && NULL != name) {
238 Py_BEGIN_ALLOW_THREADS
Georg Brandl7b90e162006-05-18 07:01:27 +0000239 f->f_fp = fopen(name, newmode);
Skip Montanaro51ffac62004-06-11 04:49:03 +0000240 Py_END_ALLOW_THREADS
241 }
242
Guido van Rossuma08095a1991-02-13 23:25:27 +0000243 if (f->f_fp == NULL) {
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000244#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
Tim Peters2ea91112002-04-08 04:13:12 +0000245 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
246 * across all Windows flavors. When it sets EINVAL varies
247 * across Windows flavors, the exact conditions aren't
248 * documented, and the answer lies in the OS's implementation
249 * of Win32's CreateFile function (whose source is secret).
250 * Seems the best we can do is map EINVAL to ENOENT.
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000251 * Starting with Visual Studio .NET 2005, EINVAL is correctly
252 * set by our CRT error handler (set in exceptions.c.)
Tim Peters2ea91112002-04-08 04:13:12 +0000253 */
254 if (errno == 0) /* bad mode string */
255 errno = EINVAL;
256 else if (errno == EINVAL) /* unknown, but not a mode string */
257 errno = ENOENT;
258#endif
Gregory P. Smith887290d2008-03-18 00:20:01 +0000259 /* EINVAL is returned when an invalid filename or
260 * an invalid mode is supplied. */
Jeremy Hylton41c83212001-11-09 16:17:24 +0000261 if (errno == EINVAL)
Gregory P. Smith887290d2008-03-18 00:20:01 +0000262 PyErr_Format(PyExc_IOError,
263 "invalid filename: %s or mode: %s",
264 name, mode);
Jeremy Hylton41c83212001-11-09 16:17:24 +0000265 else
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000266 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000267 f = NULL;
268 }
Tim Peters2ea91112002-04-08 04:13:12 +0000269 if (f != NULL)
Neil Schemenauered19b882002-03-23 02:06:50 +0000270 f = dircheck(f);
Georg Brandl7b90e162006-05-18 07:01:27 +0000271
272cleanup:
273 PyMem_FREE(newmode);
274
Tim Peters59c9a642001-09-13 05:38:56 +0000275 return (PyObject *)f;
276}
277
278PyObject *
279PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
280{
Tim Peters44410012001-09-14 03:26:08 +0000281 PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
282 NULL, NULL);
Tim Peters59c9a642001-09-13 05:38:56 +0000283 if (f != NULL) {
Neal Norwitzb337bb52006-07-17 00:55:45 +0000284 PyObject *o_name = PyString_FromString(name);
285 if (o_name == NULL)
286 return NULL;
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000287 if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
Tim Peters59c9a642001-09-13 05:38:56 +0000288 Py_DECREF(f);
289 f = NULL;
290 }
Nicholas Bastinabce8a62004-03-21 20:24:07 +0000291 Py_DECREF(o_name);
Tim Peters59c9a642001-09-13 05:38:56 +0000292 }
293 return (PyObject *) f;
294}
295
296PyObject *
297PyFile_FromString(char *name, char *mode)
298{
299 extern int fclose(FILE *);
300 PyFileObject *f;
301
302 f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
303 if (f != NULL) {
304 if (open_the_file(f, name, mode) == NULL) {
305 Py_DECREF(f);
306 f = NULL;
307 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 return (PyObject *)f;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000310}
311
Guido van Rossumb6775db1994-08-01 11:34:53 +0000312void
Fred Drakefd99de62000-07-09 05:02:18 +0000313PyFile_SetBufSize(PyObject *f, int bufsize)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314{
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000315 PyFileObject *file = (PyFileObject *)f;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000316 if (bufsize >= 0) {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000317 int type;
318 switch (bufsize) {
319 case 0:
320 type = _IONBF;
321 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000322#ifdef HAVE_SETVBUF
Guido van Rossumb6775db1994-08-01 11:34:53 +0000323 case 1:
324 type = _IOLBF;
325 bufsize = BUFSIZ;
326 break;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000327#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000328 default:
329 type = _IOFBF;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000330#ifndef HAVE_SETVBUF
331 bufsize = BUFSIZ;
332#endif
333 break;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000334 }
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000335 fflush(file->f_fp);
336 if (type == _IONBF) {
337 PyMem_Free(file->f_setbuf);
338 file->f_setbuf = NULL;
339 } else {
Anthony Baxter377be112006-04-11 06:54:30 +0000340 file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
341 bufsize);
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000342 }
343#ifdef HAVE_SETVBUF
344 setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000345#else /* !HAVE_SETVBUF */
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +0000346 setbuf(file->f_fp, file->f_setbuf);
Guido van Rossumf8b4de01998-03-06 15:32:40 +0000347#endif /* !HAVE_SETVBUF */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000348 }
349}
350
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000351/* Set the encoding used to output Unicode strings.
352 Returh 1 on success, 0 on failure. */
353
354int
355PyFile_SetEncoding(PyObject *f, const char *enc)
356{
357 PyFileObject *file = (PyFileObject*)f;
358 PyObject *str = PyString_FromString(enc);
Thomas Woutersafea5292007-01-23 13:42:00 +0000359
360 assert(PyFile_Check(f));
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000361 if (!str)
362 return 0;
363 Py_DECREF(file->f_encoding);
364 file->f_encoding = str;
365 return 1;
366}
367
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000369err_closed(void)
Guido van Rossumd7297e61992-07-06 14:19:26 +0000370{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
Guido van Rossumd7297e61992-07-06 14:19:26 +0000372 return NULL;
373}
374
Thomas Woutersc45251a2006-02-12 11:53:32 +0000375/* Refuse regular file I/O if there's data in the iteration-buffer.
376 * Mixing them would cause data to arrive out of order, as the read*
377 * methods don't use the iteration buffer. */
378static PyObject *
379err_iterbuffered(void)
380{
381 PyErr_SetString(PyExc_ValueError,
382 "Mixing iteration and read methods would lose data");
383 return NULL;
384}
385
Neal Norwitzd8b995f2002-08-06 21:50:54 +0000386static void drop_readahead(PyFileObject *);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000387
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000388/* Methods */
389
390static void
Fred Drakefd99de62000-07-09 05:02:18 +0000391file_dealloc(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392{
Peter Astrandf8e74b12004-11-07 14:15:28 +0000393 int sts = 0;
Raymond Hettingercb87bc82004-05-31 00:35:52 +0000394 if (f->weakreflist != NULL)
395 PyObject_ClearWeakRefs((PyObject *) f);
Guido van Rossumff4949e1992-08-05 19:58:53 +0000396 if (f->f_fp != NULL && f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 Py_BEGIN_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000398 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000399 Py_END_ALLOW_THREADS
Peter Astrandf8e74b12004-11-07 14:15:28 +0000400 if (sts == EOF)
401#ifdef HAVE_STRERROR
402 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
403#else
404 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
405#endif
Guido van Rossumff4949e1992-08-05 19:58:53 +0000406 }
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000407 PyMem_Free(f->f_setbuf);
Tim Peters44410012001-09-14 03:26:08 +0000408 Py_XDECREF(f->f_name);
409 Py_XDECREF(f->f_mode);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +0000410 Py_XDECREF(f->f_encoding);
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000411 drop_readahead(f);
Christian Heimese93237d2007-12-19 02:37:44 +0000412 Py_TYPE(f)->tp_free((PyObject *)f);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413}
414
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000416file_repr(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417{
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000418 if (PyUnicode_Check(f->f_name)) {
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000419#ifdef Py_USING_UNICODE
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000420 PyObject *ret = NULL;
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000421 PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
422 const char *name_str = name ? PyString_AsString(name) : "?";
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000423 ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
424 f->f_fp == NULL ? "closed" : "open",
Neal Norwitzfc28e0d2006-07-16 02:32:03 +0000425 name_str,
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000426 PyString_AsString(f->f_mode),
427 f);
428 Py_XDECREF(name);
429 return ret;
Martin v. Löwis0073f2e2002-11-21 23:52:35 +0000430#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000431 } else {
432 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000433 f->f_fp == NULL ? "closed" : "open",
434 PyString_AsString(f->f_name),
435 PyString_AsString(f->f_mode),
436 f);
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000437 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438}
439
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000441file_close(PyFileObject *f)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442{
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000443 int sts = 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000444 if (f->f_fp != NULL) {
Guido van Rossumff4949e1992-08-05 19:58:53 +0000445 if (f->f_close != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000447 errno = 0;
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000448 sts = (*f->f_close)(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000450 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000451 f->f_fp = NULL;
452 }
Martin v. Löwis7bbcde72003-09-07 20:42:29 +0000453 PyMem_Free(f->f_setbuf);
Andrew MacIntyre4e10ed32004-04-04 07:01:35 +0000454 f->f_setbuf = NULL;
Guido van Rossumfebd5511992-03-04 16:39:24 +0000455 if (sts == EOF)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000457 if (sts != 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458 return PyInt_FromLong((long)sts);
459 Py_INCREF(Py_None);
460 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461}
462
Trent Mickf29f47b2000-08-11 19:02:59 +0000463
Guido van Rossumb8552162001-09-05 14:58:11 +0000464/* Our very own off_t-like type, 64-bit if possible */
465#if !defined(HAVE_LARGEFILE_SUPPORT)
466typedef off_t Py_off_t;
467#elif SIZEOF_OFF_T >= 8
468typedef off_t Py_off_t;
469#elif SIZEOF_FPOS_T >= 8
Guido van Rossum4f53da02001-03-01 18:26:53 +0000470typedef fpos_t Py_off_t;
471#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000472#error "Large file support, but neither off_t nor fpos_t is large enough."
Guido van Rossum4f53da02001-03-01 18:26:53 +0000473#endif
474
475
Trent Mickf29f47b2000-08-11 19:02:59 +0000476/* a portable fseek() function
477 return 0 on success, non-zero on failure (with errno set) */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000478static int
Guido van Rossum4f53da02001-03-01 18:26:53 +0000479_portable_fseek(FILE *fp, Py_off_t offset, int whence)
Trent Mickf29f47b2000-08-11 19:02:59 +0000480{
Guido van Rossumb8552162001-09-05 14:58:11 +0000481#if !defined(HAVE_LARGEFILE_SUPPORT)
482 return fseek(fp, offset, whence);
483#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000484 return fseeko(fp, offset, whence);
485#elif defined(HAVE_FSEEK64)
486 return fseek64(fp, offset, whence);
Fred Drakedb810ac2000-10-06 20:42:33 +0000487#elif defined(__BEOS__)
488 return _fseek(fp, offset, whence);
Guido van Rossumb8552162001-09-05 14:58:11 +0000489#elif SIZEOF_FPOS_T >= 8
Guido van Rossume54e0be2001-01-16 20:53:31 +0000490 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
491 and fgetpos() to implement fseek()*/
Trent Mickf29f47b2000-08-11 19:02:59 +0000492 fpos_t pos;
493 switch (whence) {
Guido van Rossume54e0be2001-01-16 20:53:31 +0000494 case SEEK_END:
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000495#ifdef MS_WINDOWS
496 fflush(fp);
497 if (_lseeki64(fileno(fp), 0, 2) == -1)
498 return -1;
499#else
Guido van Rossume54e0be2001-01-16 20:53:31 +0000500 if (fseek(fp, 0, SEEK_END) != 0)
501 return -1;
Guido van Rossum8b4e43e2001-09-10 20:43:35 +0000502#endif
Guido van Rossume54e0be2001-01-16 20:53:31 +0000503 /* fall through */
504 case SEEK_CUR:
505 if (fgetpos(fp, &pos) != 0)
506 return -1;
507 offset += pos;
508 break;
509 /* case SEEK_SET: break; */
Trent Mickf29f47b2000-08-11 19:02:59 +0000510 }
511 return fsetpos(fp, &offset);
512#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000513#error "Large file support, but no way to fseek."
Trent Mickf29f47b2000-08-11 19:02:59 +0000514#endif
515}
516
517
518/* a portable ftell() function
519 Return -1 on failure with errno set appropriately, current file
520 position on success */
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000521static Py_off_t
Fred Drake8ce159a2000-08-31 05:18:54 +0000522_portable_ftell(FILE* fp)
Trent Mickf29f47b2000-08-11 19:02:59 +0000523{
Guido van Rossumb8552162001-09-05 14:58:11 +0000524#if !defined(HAVE_LARGEFILE_SUPPORT)
525 return ftell(fp);
526#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
527 return ftello(fp);
528#elif defined(HAVE_FTELL64)
529 return ftell64(fp);
530#elif SIZEOF_FPOS_T >= 8
Trent Mickf29f47b2000-08-11 19:02:59 +0000531 fpos_t pos;
532 if (fgetpos(fp, &pos) != 0)
533 return -1;
534 return pos;
535#else
Guido van Rossumb8552162001-09-05 14:58:11 +0000536#error "Large file support, but no way to ftell."
Trent Mickf29f47b2000-08-11 19:02:59 +0000537#endif
538}
539
540
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000542file_seek(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000543{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000544 int whence;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000545 int ret;
Guido van Rossum4f53da02001-03-01 18:26:53 +0000546 Py_off_t offset;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000547 PyObject *offobj, *off_index;
Tim Peters86821b22001-01-07 21:19:34 +0000548
Guido van Rossumd7297e61992-07-06 14:19:26 +0000549 if (f->f_fp == NULL)
550 return err_closed();
Guido van Rossum7a6e9592002-08-06 15:55:28 +0000551 drop_readahead(f);
Guido van Rossumd7297e61992-07-06 14:19:26 +0000552 whence = 0;
Guido van Rossum43713e52000-02-29 13:59:29 +0000553 if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000554 return NULL;
Martin v. Löwis056dac12006-11-12 18:24:26 +0000555 off_index = PyNumber_Index(offobj);
556 if (!off_index) {
557 if (!PyFloat_Check(offobj))
558 return NULL;
559 /* Deprecated in 2.6 */
560 PyErr_Clear();
561 if (PyErr_Warn(PyExc_DeprecationWarning,
562 "integer argument expected, got float"))
563 return NULL;
564 off_index = offobj;
565 Py_INCREF(offobj);
566 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000567#if !defined(HAVE_LARGEFILE_SUPPORT)
Martin v. Löwis056dac12006-11-12 18:24:26 +0000568 offset = PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000569#else
Martin v. Löwis056dac12006-11-12 18:24:26 +0000570 offset = PyLong_Check(off_index) ?
571 PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000572#endif
Martin v. Löwis056dac12006-11-12 18:24:26 +0000573 Py_DECREF(off_index);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000574 if (PyErr_Occurred())
Guido van Rossum88303191999-01-04 17:22:18 +0000575 return NULL;
Tim Peters86821b22001-01-07 21:19:34 +0000576
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000578 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000579 ret = _portable_fseek(f->f_fp, offset, whence);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000580 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000581
Guido van Rossumff4949e1992-08-05 19:58:53 +0000582 if (ret != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000584 clearerr(f->f_fp);
585 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000586 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000587 f->f_skipnextlf = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588 Py_INCREF(Py_None);
589 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000590}
591
Trent Mickf29f47b2000-08-11 19:02:59 +0000592
Guido van Rossumd7047b31995-01-02 19:07:15 +0000593#ifdef HAVE_FTRUNCATE
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000594static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000595file_truncate(PyFileObject *f, PyObject *args)
Guido van Rossumd7047b31995-01-02 19:07:15 +0000596{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000597 Py_off_t newsize;
Tim Petersf1827cf2003-09-07 03:30:18 +0000598 PyObject *newsizeobj = NULL;
599 Py_off_t initialpos;
600 int ret;
Tim Peters86821b22001-01-07 21:19:34 +0000601
Guido van Rossumd7047b31995-01-02 19:07:15 +0000602 if (f->f_fp == NULL)
603 return err_closed();
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000604 if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
Guido van Rossum88303191999-01-04 17:22:18 +0000605 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000606
Tim Petersf1827cf2003-09-07 03:30:18 +0000607 /* Get current file position. If the file happens to be open for
608 * update and the last operation was an input operation, C doesn't
609 * define what the later fflush() will do, but we promise truncate()
610 * won't change the current position (and fflush() *does* change it
611 * then at least on Windows). The easiest thing is to capture
612 * current pos now and seek back to it at the end.
613 */
614 Py_BEGIN_ALLOW_THREADS
615 errno = 0;
616 initialpos = _portable_ftell(f->f_fp);
617 Py_END_ALLOW_THREADS
618 if (initialpos == -1)
619 goto onioerror;
620
Tim Petersfb05db22002-03-11 00:24:00 +0000621 /* Set newsize to current postion if newsizeobj NULL, else to the
Tim Petersf1827cf2003-09-07 03:30:18 +0000622 * specified value.
623 */
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000624 if (newsizeobj != NULL) {
625#if !defined(HAVE_LARGEFILE_SUPPORT)
626 newsize = PyInt_AsLong(newsizeobj);
627#else
628 newsize = PyLong_Check(newsizeobj) ?
629 PyLong_AsLongLong(newsizeobj) :
630 PyInt_AsLong(newsizeobj);
631#endif
632 if (PyErr_Occurred())
633 return NULL;
Tim Petersfb05db22002-03-11 00:24:00 +0000634 }
Tim Petersf1827cf2003-09-07 03:30:18 +0000635 else /* default to current position */
636 newsize = initialpos;
Tim Petersfb05db22002-03-11 00:24:00 +0000637
Tim Petersf1827cf2003-09-07 03:30:18 +0000638 /* Flush the stream. We're mixing stream-level I/O with lower-level
639 * I/O, and a flush may be necessary to synch both platform views
640 * of the current file state.
641 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000642 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd7047b31995-01-02 19:07:15 +0000643 errno = 0;
644 ret = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000645 Py_END_ALLOW_THREADS
Tim Petersfb05db22002-03-11 00:24:00 +0000646 if (ret != 0)
647 goto onioerror;
Trent Mickf29f47b2000-08-11 19:02:59 +0000648
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000649#ifdef MS_WINDOWS
Tim Petersfb05db22002-03-11 00:24:00 +0000650 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
Tim Peters8f01b682002-03-12 03:04:44 +0000651 so don't even try using it. */
Tim Petersfb05db22002-03-11 00:24:00 +0000652 {
Tim Petersfb05db22002-03-11 00:24:00 +0000653 HANDLE hFile;
Tim Petersfb05db22002-03-11 00:24:00 +0000654
Tim Petersf1827cf2003-09-07 03:30:18 +0000655 /* Have to move current pos to desired endpoint on Windows. */
656 Py_BEGIN_ALLOW_THREADS
657 errno = 0;
658 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
659 Py_END_ALLOW_THREADS
660 if (ret)
661 goto onioerror;
Tim Petersfb05db22002-03-11 00:24:00 +0000662
Tim Peters8f01b682002-03-12 03:04:44 +0000663 /* Truncate. Note that this may grow the file! */
664 Py_BEGIN_ALLOW_THREADS
665 errno = 0;
666 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
Tim Petersf1827cf2003-09-07 03:30:18 +0000667 ret = hFile == (HANDLE)-1;
668 if (ret == 0) {
669 ret = SetEndOfFile(hFile) == 0;
670 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000671 errno = EACCES;
672 }
673 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000674 if (ret)
Tim Peters8f01b682002-03-12 03:04:44 +0000675 goto onioerror;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000676 }
Trent Mickf29f47b2000-08-11 19:02:59 +0000677#else
678 Py_BEGIN_ALLOW_THREADS
679 errno = 0;
680 ret = ftruncate(fileno(f->f_fp), newsize);
681 Py_END_ALLOW_THREADS
Tim Petersf1827cf2003-09-07 03:30:18 +0000682 if (ret != 0)
683 goto onioerror;
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000684#endif /* !MS_WINDOWS */
Tim Peters86821b22001-01-07 21:19:34 +0000685
Tim Petersf1827cf2003-09-07 03:30:18 +0000686 /* Restore original file position. */
687 Py_BEGIN_ALLOW_THREADS
688 errno = 0;
689 ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
690 Py_END_ALLOW_THREADS
691 if (ret)
692 goto onioerror;
693
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694 Py_INCREF(Py_None);
695 return Py_None;
Trent Mickf29f47b2000-08-11 19:02:59 +0000696
697onioerror:
698 PyErr_SetFromErrno(PyExc_IOError);
699 clearerr(f->f_fp);
700 return NULL;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000701}
702#endif /* HAVE_FTRUNCATE */
703
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000704static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000705file_tell(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000706{
Guido van Rossum4f53da02001-03-01 18:26:53 +0000707 Py_off_t pos;
Trent Mickf29f47b2000-08-11 19:02:59 +0000708
Guido van Rossumd7297e61992-07-06 14:19:26 +0000709 if (f->f_fp == NULL)
710 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000711 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000712 errno = 0;
Trent Mickf29f47b2000-08-11 19:02:59 +0000713 pos = _portable_ftell(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 Py_END_ALLOW_THREADS
Trent Mickf29f47b2000-08-11 19:02:59 +0000715 if (pos == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000717 clearerr(f->f_fp);
718 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000719 }
Jack Jansen7b8c7542002-04-14 20:12:41 +0000720 if (f->f_skipnextlf) {
721 int c;
722 c = GETC(f->f_fp);
723 if (c == '\n') {
Guido van Rossumad8fb0d2007-09-22 20:18:03 +0000724 f->f_newlinetypes |= NEWLINE_CRLF;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000725 pos++;
726 f->f_skipnextlf = 0;
727 } else if (c != EOF) ungetc(c, f->f_fp);
728 }
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000729#if !defined(HAVE_LARGEFILE_SUPPORT)
Trent Mickf29f47b2000-08-11 19:02:59 +0000730 return PyInt_FromLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000731#else
Trent Mickf29f47b2000-08-11 19:02:59 +0000732 return PyLong_FromLongLong(pos);
Guido van Rossum3c9fe0c1999-01-06 18:51:17 +0000733#endif
Guido van Rossumce5ba841991-03-06 13:06:18 +0000734}
735
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000737file_fileno(PyFileObject *f)
Guido van Rossumed233a51992-06-23 09:07:03 +0000738{
Guido van Rossumd7297e61992-07-06 14:19:26 +0000739 if (f->f_fp == NULL)
740 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741 return PyInt_FromLong((long) fileno(f->f_fp));
Guido van Rossumed233a51992-06-23 09:07:03 +0000742}
743
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000745file_flush(PyFileObject *f)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000746{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000747 int res;
Tim Peters86821b22001-01-07 21:19:34 +0000748
Guido van Rossumd7297e61992-07-06 14:19:26 +0000749 if (f->f_fp == NULL)
750 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000751 Py_BEGIN_ALLOW_THREADS
Guido van Rossumce5ba841991-03-06 13:06:18 +0000752 errno = 0;
Guido van Rossumff4949e1992-08-05 19:58:53 +0000753 res = fflush(f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754 Py_END_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000755 if (res != 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000756 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +0000757 clearerr(f->f_fp);
758 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000759 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760 Py_INCREF(Py_None);
761 return Py_None;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000762}
763
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000765file_isatty(PyFileObject *f)
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000766{
Guido van Rossumff4949e1992-08-05 19:58:53 +0000767 long res;
Guido van Rossumd7297e61992-07-06 14:19:26 +0000768 if (f->f_fp == NULL)
769 return err_closed();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000770 Py_BEGIN_ALLOW_THREADS
Guido van Rossumff4949e1992-08-05 19:58:53 +0000771 res = isatty((int)fileno(f->f_fp));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000772 Py_END_ALLOW_THREADS
Guido van Rossum7f7666f2002-04-07 06:28:00 +0000773 return PyBool_FromLong(res);
Guido van Rossuma1ab7fa1991-06-04 19:37:39 +0000774}
775
Guido van Rossumff7e83d1999-08-27 20:39:37 +0000776
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000777#if BUFSIZ < 8192
778#define SMALLCHUNK 8192
779#else
780#define SMALLCHUNK BUFSIZ
781#endif
782
Guido van Rossum3c259041999-01-14 19:00:14 +0000783#if SIZEOF_INT < 4
784#define BIGCHUNK (512 * 32)
785#else
786#define BIGCHUNK (512 * 1024)
787#endif
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000788
789static size_t
Fred Drakefd99de62000-07-09 05:02:18 +0000790new_buffersize(PyFileObject *f, size_t currentsize)
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000791{
792#ifdef HAVE_FSTAT
Fred Drake1bc8fab2001-07-19 21:49:38 +0000793 off_t pos, end;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000794 struct stat st;
795 if (fstat(fileno(f->f_fp), &st) == 0) {
796 end = st.st_size;
Guido van Rossumcada2931998-12-11 20:44:56 +0000797 /* The following is not a bug: we really need to call lseek()
798 *and* ftell(). The reason is that some stdio libraries
799 mistakenly flush their buffer when ftell() is called and
800 the lseek() call it makes fails, thereby throwing away
801 data that cannot be recovered in any way. To avoid this,
802 we first test lseek(), and only call ftell() if lseek()
803 works. We can't use the lseek() value either, because we
804 need to take the amount of buffered data into account.
805 (Yet another reason why stdio stinks. :-) */
Guido van Rossum91aaa921998-05-05 22:21:35 +0000806 pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000807 if (pos >= 0) {
Guido van Rossum91aaa921998-05-05 22:21:35 +0000808 pos = ftell(f->f_fp);
Jack Jansen2771b5b2001-10-10 22:03:27 +0000809 }
Guido van Rossumd30dc0a1998-04-27 19:01:08 +0000810 if (pos < 0)
811 clearerr(f->f_fp);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000812 if (end > pos && pos >= 0)
Guido van Rossumcada2931998-12-11 20:44:56 +0000813 return currentsize + end - pos + 1;
Guido van Rossumdcb5e7f1998-03-03 22:36:10 +0000814 /* Add 1 so if the file were to grow we'd notice. */
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000815 }
816#endif
817 if (currentsize > SMALLCHUNK) {
818 /* Keep doubling until we reach BIGCHUNK;
819 then keep adding BIGCHUNK. */
820 if (currentsize <= BIGCHUNK)
821 return currentsize + currentsize;
822 else
823 return currentsize + BIGCHUNK;
824 }
825 return currentsize + SMALLCHUNK;
826}
827
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000828#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
829#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
830#else
831#ifdef EWOULDBLOCK
832#define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
833#else
834#ifdef EAGAIN
835#define BLOCKED_ERRNO(x) ((x) == EAGAIN)
836#else
837#define BLOCKED_ERRNO(x) 0
838#endif
839#endif
840#endif
841
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000842static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000843file_read(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000844{
Guido van Rossum789a1611997-05-10 22:33:55 +0000845 long bytesrequested = -1;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000846 size_t bytesread, buffersize, chunksize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000847 PyObject *v;
Tim Peters86821b22001-01-07 21:19:34 +0000848
Guido van Rossumd7297e61992-07-06 14:19:26 +0000849 if (f->f_fp == NULL)
850 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000851 /* refuse to mix with f.next() */
852 if (f->f_buf != NULL &&
853 (f->f_bufend - f->f_bufptr) > 0 &&
854 f->f_buf[0] != '\0')
855 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +0000856 if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
Guido van Rossum789a1611997-05-10 22:33:55 +0000857 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000858 if (bytesrequested < 0)
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000859 buffersize = new_buffersize(f, (size_t)0);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000860 else
861 buffersize = bytesrequested;
Martin v. Löwis2a190742006-04-13 07:37:25 +0000862 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +0000863 PyErr_SetString(PyExc_OverflowError,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000864 "requested number of bytes is more than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +0000865 return NULL;
866 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000867 v = PyString_FromStringAndSize((char *)NULL, buffersize);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000868 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000869 return NULL;
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000870 bytesread = 0;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000871 for (;;) {
Guido van Rossum6263d541997-05-10 22:07:25 +0000872 Py_BEGIN_ALLOW_THREADS
873 errno = 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +0000874 chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000875 buffersize - bytesread, f->f_fp, (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000876 Py_END_ALLOW_THREADS
877 if (chunksize == 0) {
878 if (!ferror(f->f_fp))
879 break;
Guido van Rossum6263d541997-05-10 22:07:25 +0000880 clearerr(f->f_fp);
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000881 /* When in non-blocking mode, data shouldn't
882 * be discarded if a blocking signal was
883 * received. That will also happen if
884 * chunksize != 0, but bytesread < buffersize. */
885 if (bytesread > 0 && BLOCKED_ERRNO(errno))
886 break;
887 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum6263d541997-05-10 22:07:25 +0000888 Py_DECREF(v);
889 return NULL;
890 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000891 bytesread += chunksize;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000892 if (bytesread < buffersize) {
893 clearerr(f->f_fp);
Guido van Rossumce5ba841991-03-06 13:06:18 +0000894 break;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000895 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000896 if (bytesrequested < 0) {
Guido van Rossumcada2931998-12-11 20:44:56 +0000897 buffersize = new_buffersize(f, buffersize);
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000898 if (_PyString_Resize(&v, buffersize) < 0)
Guido van Rossumce5ba841991-03-06 13:06:18 +0000899 return NULL;
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000900 } else {
Gustavo Niemeyera080be82002-12-17 17:48:00 +0000901 /* Got what was requested. */
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +0000902 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +0000903 }
904 }
Guido van Rossum5449b6e1997-05-09 22:27:31 +0000905 if (bytesread != buffersize)
906 _PyString_Resize(&v, bytesread);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000907 return v;
908}
909
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000910static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000911file_readinto(PyFileObject *f, PyObject *args)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000912{
913 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000914 Py_ssize_t ntodo;
915 Py_ssize_t ndone, nnow;
Tim Peters86821b22001-01-07 21:19:34 +0000916
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000917 if (f->f_fp == NULL)
918 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +0000919 /* refuse to mix with f.next() */
920 if (f->f_buf != NULL &&
921 (f->f_bufend - f->f_bufptr) > 0 &&
922 f->f_buf[0] != '\0')
923 return err_iterbuffered();
Neal Norwitz62f5a9d2002-04-01 00:09:00 +0000924 if (!PyArg_ParseTuple(args, "w#", &ptr, &ntodo))
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000925 return NULL;
926 ndone = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +0000927 while (ntodo > 0) {
928 Py_BEGIN_ALLOW_THREADS
929 errno = 0;
Tim Petersf1827cf2003-09-07 03:30:18 +0000930 nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
Jeremy Hylton8b735422002-08-14 21:01:41 +0000931 (PyObject *)f);
Guido van Rossum6263d541997-05-10 22:07:25 +0000932 Py_END_ALLOW_THREADS
933 if (nnow == 0) {
934 if (!ferror(f->f_fp))
935 break;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000936 PyErr_SetFromErrno(PyExc_IOError);
937 clearerr(f->f_fp);
938 return NULL;
939 }
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000940 ndone += nnow;
941 ntodo -= nnow;
942 }
Neal Norwitz076d1e02006-08-21 18:20:10 +0000943 return PyInt_FromSsize_t(ndone);
Guido van Rossumfdf95dd1997-05-05 22:15:02 +0000944}
945
Tim Peters86821b22001-01-07 21:19:34 +0000946/**************************************************************************
Tim Petersf29b64d2001-01-15 06:33:19 +0000947Routine to get next line using platform fgets().
Tim Peters86821b22001-01-07 21:19:34 +0000948
949Under MSVC 6:
950
Tim Peters1c733232001-01-08 04:02:07 +0000951+ MS threadsafe getc is very slow (multiple layers of function calls before+
952 after each character, to lock+unlock the stream).
953+ The stream-locking functions are MS-internal -- can't access them from user
954 code.
955+ There's nothing Tim could find in the MS C or platform SDK libraries that
956 can worm around this.
Tim Peters86821b22001-01-07 21:19:34 +0000957+ MS fgets locks/unlocks only once per line; it's the only hook we have.
958
959So we use fgets for speed(!), despite that it's painful.
960
961MS realloc is also slow.
962
Tim Petersf29b64d2001-01-15 06:33:19 +0000963Reports from other platforms on this method vs getc_unlocked (which MS doesn't
964have):
965 Linux a wash
966 Solaris a wash
967 Tru64 Unix getline_via_fgets significantly faster
Tim Peters86821b22001-01-07 21:19:34 +0000968
Tim Petersf29b64d2001-01-15 06:33:19 +0000969CAUTION: The C std isn't clear about this: in those cases where fgets
970writes something into the buffer, can it write into any position beyond the
971required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
972known on which it does; and it would be a strange way to code fgets. Still,
973getline_via_fgets may not work correctly if it does. The std test
974test_bufio.py should fail if platform fgets() routinely writes beyond the
975trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
Tim Peters86821b22001-01-07 21:19:34 +0000976**************************************************************************/
977
Tim Petersf29b64d2001-01-15 06:33:19 +0000978/* Use this routine if told to, or by default on non-get_unlocked()
979 * platforms unless told not to. Yikes! Let's spell that out:
980 * On a platform with getc_unlocked():
981 * By default, use getc_unlocked().
982 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
983 * On a platform without getc_unlocked():
984 * By default, use fgets().
985 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
986 */
987#if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
988#define USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000989#endif
990
Tim Petersf29b64d2001-01-15 06:33:19 +0000991#if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
992#undef USE_FGETS_IN_GETLINE
993#endif
994
995#ifdef USE_FGETS_IN_GETLINE
Tim Peters86821b22001-01-07 21:19:34 +0000996static PyObject*
Tim Petersf29b64d2001-01-15 06:33:19 +0000997getline_via_fgets(FILE *fp)
Tim Peters86821b22001-01-07 21:19:34 +0000998{
Tim Peters15b83852001-01-08 00:53:12 +0000999/* INITBUFSIZE is the maximum line length that lets us get away with the fast
Tim Peters142297a2001-01-15 10:36:56 +00001000 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1001 * to fill this much of the buffer with a known value in order to figure out
1002 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1003 * than "most" lines, we waste time filling unused buffer slots. 100 is
1004 * surely adequate for most peoples' email archives, chewing over source code,
1005 * etc -- "regular old text files".
1006 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1007 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1008 * cautions about boosting that. 300 was chosen because the worst real-life
1009 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1010 * half the lines were 254 chars.
Tim Peters15b83852001-01-08 00:53:12 +00001011 */
Tim Peters142297a2001-01-15 10:36:56 +00001012#define INITBUFSIZE 100
1013#define MAXBUFSIZE 300
Tim Peters142297a2001-01-15 10:36:56 +00001014 char* p; /* temp */
1015 char buf[MAXBUFSIZE];
Tim Peters86821b22001-01-07 21:19:34 +00001016 PyObject* v; /* the string object result */
Tim Peters86821b22001-01-07 21:19:34 +00001017 char* pvfree; /* address of next free slot */
1018 char* pvend; /* address one beyond last free slot */
Tim Peters142297a2001-01-15 10:36:56 +00001019 size_t nfree; /* # of free buffer slots; pvend-pvfree */
1020 size_t total_v_size; /* total # of slots in buffer */
Tim Petersddea2082002-03-23 10:03:50 +00001021 size_t increment; /* amount to increment the buffer */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001022 size_t prev_v_size;
Tim Peters86821b22001-01-07 21:19:34 +00001023
Tim Peters15b83852001-01-08 00:53:12 +00001024 /* Optimize for normal case: avoid _PyString_Resize if at all
Tim Peters142297a2001-01-15 10:36:56 +00001025 * possible via first reading into stack buffer "buf".
Tim Peters15b83852001-01-08 00:53:12 +00001026 */
Tim Peters142297a2001-01-15 10:36:56 +00001027 total_v_size = INITBUFSIZE; /* start small and pray */
1028 pvfree = buf;
1029 for (;;) {
1030 Py_BEGIN_ALLOW_THREADS
1031 pvend = buf + total_v_size;
1032 nfree = pvend - pvfree;
1033 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001034 assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
1035 p = fgets(pvfree, (int)nfree, fp);
Tim Peters142297a2001-01-15 10:36:56 +00001036 Py_END_ALLOW_THREADS
Tim Peters15b83852001-01-08 00:53:12 +00001037
Tim Peters142297a2001-01-15 10:36:56 +00001038 if (p == NULL) {
1039 clearerr(fp);
1040 if (PyErr_CheckSignals())
1041 return NULL;
1042 v = PyString_FromStringAndSize(buf, pvfree - buf);
Tim Peters86821b22001-01-07 21:19:34 +00001043 return v;
1044 }
Tim Peters142297a2001-01-15 10:36:56 +00001045 /* fgets read *something* */
1046 p = memchr(pvfree, '\n', nfree);
1047 if (p != NULL) {
1048 /* Did the \n come from fgets or from us?
1049 * Since fgets stops at the first \n, and then writes
1050 * \0, if it's from fgets a \0 must be next. But if
1051 * that's so, it could not have come from us, since
1052 * the \n's we filled the buffer with have only more
1053 * \n's to the right.
1054 */
1055 if (p+1 < pvend && *(p+1) == '\0') {
1056 /* It's from fgets: we win! In particular,
1057 * we haven't done any mallocs yet, and can
1058 * build the final result on the first try.
1059 */
1060 ++p; /* include \n from fgets */
1061 }
1062 else {
1063 /* Must be from us: fgets didn't fill the
1064 * buffer and didn't find a newline, so it
1065 * must be the last and newline-free line of
1066 * the file.
1067 */
1068 assert(p > pvfree && *(p-1) == '\0');
1069 --p; /* don't include \0 from fgets */
1070 }
1071 v = PyString_FromStringAndSize(buf, p - buf);
1072 return v;
1073 }
1074 /* yuck: fgets overwrote all the newlines, i.e. the entire
1075 * buffer. So this line isn't over yet, or maybe it is but
1076 * we're exactly at EOF. If we haven't already, try using the
1077 * rest of the stack buffer.
Tim Peters86821b22001-01-07 21:19:34 +00001078 */
Tim Peters142297a2001-01-15 10:36:56 +00001079 assert(*(pvend-1) == '\0');
1080 if (pvfree == buf) {
1081 pvfree = pvend - 1; /* overwrite trailing null */
1082 total_v_size = MAXBUFSIZE;
1083 }
1084 else
1085 break;
Tim Peters86821b22001-01-07 21:19:34 +00001086 }
Tim Peters142297a2001-01-15 10:36:56 +00001087
1088 /* The stack buffer isn't big enough; malloc a string object and read
1089 * into its buffer.
Tim Peters15b83852001-01-08 00:53:12 +00001090 */
Tim Petersddea2082002-03-23 10:03:50 +00001091 total_v_size = MAXBUFSIZE << 1;
Tim Peters1c733232001-01-08 04:02:07 +00001092 v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
Tim Peters15b83852001-01-08 00:53:12 +00001093 if (v == NULL)
1094 return v;
1095 /* copy over everything except the last null byte */
Tim Peters142297a2001-01-15 10:36:56 +00001096 memcpy(BUF(v), buf, MAXBUFSIZE-1);
1097 pvfree = BUF(v) + MAXBUFSIZE - 1;
Tim Peters86821b22001-01-07 21:19:34 +00001098
1099 /* Keep reading stuff into v; if it ever ends successfully, break
Tim Peters15b83852001-01-08 00:53:12 +00001100 * after setting p one beyond the end of the line. The code here is
1101 * very much like the code above, except reads into v's buffer; see
1102 * the code above for detailed comments about the logic.
Tim Peters86821b22001-01-07 21:19:34 +00001103 */
1104 for (;;) {
Tim Peters86821b22001-01-07 21:19:34 +00001105 Py_BEGIN_ALLOW_THREADS
1106 pvend = BUF(v) + total_v_size;
1107 nfree = pvend - pvfree;
1108 memset(pvfree, '\n', nfree);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109 assert(nfree < INT_MAX);
1110 p = fgets(pvfree, (int)nfree, fp);
Tim Peters86821b22001-01-07 21:19:34 +00001111 Py_END_ALLOW_THREADS
1112
1113 if (p == NULL) {
1114 clearerr(fp);
1115 if (PyErr_CheckSignals()) {
1116 Py_DECREF(v);
1117 return NULL;
1118 }
1119 p = pvfree;
1120 break;
1121 }
Tim Peters86821b22001-01-07 21:19:34 +00001122 p = memchr(pvfree, '\n', nfree);
1123 if (p != NULL) {
1124 if (p+1 < pvend && *(p+1) == '\0') {
1125 /* \n came from fgets */
1126 ++p;
1127 break;
1128 }
1129 /* \n came from us; last line of file, no newline */
1130 assert(p > pvfree && *(p-1) == '\0');
1131 --p;
1132 break;
1133 }
1134 /* expand buffer and try again */
1135 assert(*(pvend-1) == '\0');
Tim Petersddea2082002-03-23 10:03:50 +00001136 increment = total_v_size >> 2; /* mild exponential growth */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001137 prev_v_size = total_v_size;
Tim Petersddea2082002-03-23 10:03:50 +00001138 total_v_size += increment;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001139 /* check for overflow */
1140 if (total_v_size <= prev_v_size ||
1141 total_v_size > PY_SSIZE_T_MAX) {
Tim Peters86821b22001-01-07 21:19:34 +00001142 PyErr_SetString(PyExc_OverflowError,
1143 "line is longer than a Python string can hold");
1144 Py_DECREF(v);
1145 return NULL;
1146 }
1147 if (_PyString_Resize(&v, (int)total_v_size) < 0)
1148 return NULL;
1149 /* overwrite the trailing null byte */
Armin Rigo7ccbca92006-10-04 12:17:45 +00001150 pvfree = BUF(v) + (prev_v_size - 1);
Tim Peters86821b22001-01-07 21:19:34 +00001151 }
1152 if (BUF(v) + total_v_size != p)
1153 _PyString_Resize(&v, p - BUF(v));
1154 return v;
1155#undef INITBUFSIZE
Tim Peters142297a2001-01-15 10:36:56 +00001156#undef MAXBUFSIZE
Tim Peters86821b22001-01-07 21:19:34 +00001157}
Tim Petersf29b64d2001-01-15 06:33:19 +00001158#endif /* ifdef USE_FGETS_IN_GETLINE */
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001159
Guido van Rossum0bd24411991-04-04 15:21:57 +00001160/* Internal routine to get a line.
1161 Size argument interpretation:
1162 > 0: max length;
Guido van Rossum86282062001-01-08 01:26:47 +00001163 <= 0: read arbitrary line
Guido van Rossumce5ba841991-03-06 13:06:18 +00001164*/
1165
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001166static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001167get_line(PyFileObject *f, int n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001168{
Guido van Rossum1187aa42001-01-05 14:43:05 +00001169 FILE *fp = f->f_fp;
1170 int c;
Andrew M. Kuchling4b2b4452000-11-29 02:53:22 +00001171 char *buf, *end;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001172 size_t total_v_size; /* total # of slots in buffer */
1173 size_t used_v_size; /* # used slots in buffer */
1174 size_t increment; /* amount to increment the buffer */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001175 PyObject *v;
Jack Jansen7b8c7542002-04-14 20:12:41 +00001176 int newlinetypes = f->f_newlinetypes;
1177 int skipnextlf = f->f_skipnextlf;
1178 int univ_newline = f->f_univ_newline;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001179
Jack Jansen7b8c7542002-04-14 20:12:41 +00001180#if defined(USE_FGETS_IN_GETLINE)
Jack Jansen7b8c7542002-04-14 20:12:41 +00001181 if (n <= 0 && !univ_newline )
Tim Petersf29b64d2001-01-15 06:33:19 +00001182 return getline_via_fgets(fp);
Tim Peters86821b22001-01-07 21:19:34 +00001183#endif
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001184 total_v_size = n > 0 ? n : 100;
1185 v = PyString_FromStringAndSize((char *)NULL, total_v_size);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001186 if (v == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001187 return NULL;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001188 buf = BUF(v);
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001189 end = buf + total_v_size;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190
Guido van Rossumce5ba841991-03-06 13:06:18 +00001191 for (;;) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001192 Py_BEGIN_ALLOW_THREADS
1193 FLOCKFILE(fp);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001194 if (univ_newline) {
1195 c = 'x'; /* Shut up gcc warning */
1196 while ( buf != end && (c = GETC(fp)) != EOF ) {
1197 if (skipnextlf ) {
1198 skipnextlf = 0;
1199 if (c == '\n') {
Tim Petersf1827cf2003-09-07 03:30:18 +00001200 /* Seeing a \n here with
1201 * skipnextlf true means we
Jeremy Hylton8b735422002-08-14 21:01:41 +00001202 * saw a \r before.
1203 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001204 newlinetypes |= NEWLINE_CRLF;
1205 c = GETC(fp);
1206 if (c == EOF) break;
1207 } else {
1208 newlinetypes |= NEWLINE_CR;
1209 }
1210 }
1211 if (c == '\r') {
1212 skipnextlf = 1;
1213 c = '\n';
1214 } else if ( c == '\n')
1215 newlinetypes |= NEWLINE_LF;
1216 *buf++ = c;
1217 if (c == '\n') break;
1218 }
1219 if ( c == EOF && skipnextlf )
1220 newlinetypes |= NEWLINE_CR;
1221 } else /* If not universal newlines use the normal loop */
Guido van Rossum1187aa42001-01-05 14:43:05 +00001222 while ((c = GETC(fp)) != EOF &&
1223 (*buf++ = c) != '\n' &&
1224 buf != end)
1225 ;
1226 FUNLOCKFILE(fp);
1227 Py_END_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +00001228 f->f_newlinetypes = newlinetypes;
1229 f->f_skipnextlf = skipnextlf;
Guido van Rossum1187aa42001-01-05 14:43:05 +00001230 if (c == '\n')
1231 break;
1232 if (c == EOF) {
Guido van Rossum29206bc2001-08-09 18:14:59 +00001233 if (ferror(fp)) {
1234 PyErr_SetFromErrno(PyExc_IOError);
1235 clearerr(fp);
1236 Py_DECREF(v);
1237 return NULL;
1238 }
Guido van Rossum76ad8ed1991-06-03 10:54:55 +00001239 clearerr(fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001240 if (PyErr_CheckSignals()) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001241 Py_DECREF(v);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001242 return NULL;
1243 }
Guido van Rossumce5ba841991-03-06 13:06:18 +00001244 break;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001245 }
Guido van Rossum1187aa42001-01-05 14:43:05 +00001246 /* Must be because buf == end */
1247 if (n > 0)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001248 break;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001249 used_v_size = total_v_size;
1250 increment = total_v_size >> 2; /* mild exponential growth */
1251 total_v_size += increment;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001252 if (total_v_size > PY_SSIZE_T_MAX) {
Guido van Rossum1187aa42001-01-05 14:43:05 +00001253 PyErr_SetString(PyExc_OverflowError,
1254 "line is longer than a Python string can hold");
Tim Peters86821b22001-01-07 21:19:34 +00001255 Py_DECREF(v);
Guido van Rossum1187aa42001-01-05 14:43:05 +00001256 return NULL;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001257 }
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001258 if (_PyString_Resize(&v, total_v_size) < 0)
Guido van Rossum1187aa42001-01-05 14:43:05 +00001259 return NULL;
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001260 buf = BUF(v) + used_v_size;
1261 end = BUF(v) + total_v_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001262 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001263
Neil Schemenauer3a204a72002-03-23 19:41:34 +00001264 used_v_size = buf - BUF(v);
1265 if (used_v_size != total_v_size)
1266 _PyString_Resize(&v, used_v_size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001267 return v;
1268}
1269
Guido van Rossum0bd24411991-04-04 15:21:57 +00001270/* External C interface */
1271
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001272PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001273PyFile_GetLine(PyObject *f, int n)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001274{
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001275 PyObject *result;
1276
Guido van Rossum3165fe61992-09-25 21:59:05 +00001277 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001278 PyErr_BadInternalCall();
Guido van Rossum0bd24411991-04-04 15:21:57 +00001279 return NULL;
1280 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001281
1282 if (PyFile_Check(f)) {
Thomas Woutersc45251a2006-02-12 11:53:32 +00001283 PyFileObject *fo = (PyFileObject *)f;
1284 if (fo->f_fp == NULL)
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001285 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001286 /* refuse to mix with f.next() */
1287 if (fo->f_buf != NULL &&
1288 (fo->f_bufend - fo->f_bufptr) > 0 &&
1289 fo->f_buf[0] != '\0')
1290 return err_iterbuffered();
1291 result = get_line(fo, n);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001292 }
1293 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001294 PyObject *reader;
1295 PyObject *args;
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001296
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001297 reader = PyObject_GetAttrString(f, "readline");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001298 if (reader == NULL)
1299 return NULL;
1300 if (n <= 0)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001301 args = PyTuple_New(0);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001302 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001303 args = Py_BuildValue("(i)", n);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001304 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001305 Py_DECREF(reader);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001306 return NULL;
1307 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001308 result = PyEval_CallObject(reader, args);
1309 Py_DECREF(reader);
1310 Py_DECREF(args);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001311 if (result != NULL && !PyString_Check(result) &&
1312 !PyUnicode_Check(result)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001314 result = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001315 PyErr_SetString(PyExc_TypeError,
Guido van Rossum3165fe61992-09-25 21:59:05 +00001316 "object.readline() returned non-string");
1317 }
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001318 }
1319
1320 if (n < 0 && result != NULL && PyString_Check(result)) {
1321 char *s = PyString_AS_STRING(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001322 Py_ssize_t len = PyString_GET_SIZE(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001323 if (len == 0) {
1324 Py_DECREF(result);
1325 result = NULL;
1326 PyErr_SetString(PyExc_EOFError,
1327 "EOF when reading a line");
1328 }
1329 else if (s[len-1] == '\n') {
1330 if (result->ob_refcnt == 1)
1331 _PyString_Resize(&result, len-1);
1332 else {
1333 PyObject *v;
1334 v = PyString_FromStringAndSize(s, len-1);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001335 Py_DECREF(result);
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001336 result = v;
Guido van Rossum3165fe61992-09-25 21:59:05 +00001337 }
1338 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001339 }
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001340#ifdef Py_USING_UNICODE
1341 if (n < 0 && result != NULL && PyUnicode_Check(result)) {
1342 Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001343 Py_ssize_t len = PyUnicode_GET_SIZE(result);
Martin v. Löwisaf6a27a2003-01-03 19:16:14 +00001344 if (len == 0) {
1345 Py_DECREF(result);
1346 result = NULL;
1347 PyErr_SetString(PyExc_EOFError,
1348 "EOF when reading a line");
1349 }
1350 else if (s[len-1] == '\n') {
1351 if (result->ob_refcnt == 1)
1352 PyUnicode_Resize(&result, len-1);
1353 else {
1354 PyObject *v;
1355 v = PyUnicode_FromUnicode(s, len-1);
1356 Py_DECREF(result);
1357 result = v;
1358 }
1359 }
1360 }
1361#endif
Guido van Rossum4ddf0a02001-01-07 20:51:39 +00001362 return result;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001363}
1364
1365/* Python method */
1366
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001367static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001368file_readline(PyFileObject *f, PyObject *args)
Guido van Rossum0bd24411991-04-04 15:21:57 +00001369{
Guido van Rossum789a1611997-05-10 22:33:55 +00001370 int n = -1;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001371
Guido van Rossumd7297e61992-07-06 14:19:26 +00001372 if (f->f_fp == NULL)
1373 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001374 /* refuse to mix with f.next() */
1375 if (f->f_buf != NULL &&
1376 (f->f_bufend - f->f_bufptr) > 0 &&
1377 f->f_buf[0] != '\0')
1378 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001379 if (!PyArg_ParseTuple(args, "|i:readline", &n))
Guido van Rossum789a1611997-05-10 22:33:55 +00001380 return NULL;
1381 if (n == 0)
1382 return PyString_FromString("");
1383 if (n < 0)
1384 n = 0;
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001385 return get_line(f, n);
Guido van Rossum0bd24411991-04-04 15:21:57 +00001386}
1387
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001389file_readlines(PyFileObject *f, PyObject *args)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001390{
Guido van Rossum789a1611997-05-10 22:33:55 +00001391 long sizehint = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001392 PyObject *list;
1393 PyObject *line;
Guido van Rossum6263d541997-05-10 22:07:25 +00001394 char small_buffer[SMALLCHUNK];
1395 char *buffer = small_buffer;
1396 size_t buffersize = SMALLCHUNK;
1397 PyObject *big_buffer = NULL;
1398 size_t nfilled = 0;
1399 size_t nread;
Guido van Rossum789a1611997-05-10 22:33:55 +00001400 size_t totalread = 0;
Guido van Rossum6263d541997-05-10 22:07:25 +00001401 char *p, *q, *end;
1402 int err;
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001403 int shortread = 0;
Guido van Rossum0bd24411991-04-04 15:21:57 +00001404
Guido van Rossumd7297e61992-07-06 14:19:26 +00001405 if (f->f_fp == NULL)
1406 return err_closed();
Thomas Woutersc45251a2006-02-12 11:53:32 +00001407 /* refuse to mix with f.next() */
1408 if (f->f_buf != NULL &&
1409 (f->f_bufend - f->f_bufptr) > 0 &&
1410 f->f_buf[0] != '\0')
1411 return err_iterbuffered();
Guido van Rossum43713e52000-02-29 13:59:29 +00001412 if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
Guido van Rossum0bd24411991-04-04 15:21:57 +00001413 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001414 if ((list = PyList_New(0)) == NULL)
Guido van Rossumce5ba841991-03-06 13:06:18 +00001415 return NULL;
1416 for (;;) {
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001417 if (shortread)
1418 nread = 0;
1419 else {
1420 Py_BEGIN_ALLOW_THREADS
1421 errno = 0;
Tim Peters058b1412002-04-21 07:29:14 +00001422 nread = Py_UniversalNewlineFread(buffer+nfilled,
Jack Jansen7b8c7542002-04-14 20:12:41 +00001423 buffersize-nfilled, f->f_fp, (PyObject *)f);
Guido van Rossum79fd0fc2001-10-12 20:01:53 +00001424 Py_END_ALLOW_THREADS
1425 shortread = (nread < buffersize-nfilled);
1426 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001427 if (nread == 0) {
Guido van Rossum789a1611997-05-10 22:33:55 +00001428 sizehint = 0;
Guido van Rossum3da3fce1998-02-19 20:46:48 +00001429 if (!ferror(f->f_fp))
Guido van Rossum6263d541997-05-10 22:07:25 +00001430 break;
1431 PyErr_SetFromErrno(PyExc_IOError);
1432 clearerr(f->f_fp);
1433 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001434 Py_DECREF(list);
Guido van Rossum6263d541997-05-10 22:07:25 +00001435 list = NULL;
1436 goto cleanup;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001437 }
Guido van Rossum789a1611997-05-10 22:33:55 +00001438 totalread += nread;
Anthony Baxter377be112006-04-11 06:54:30 +00001439 p = (char *)memchr(buffer+nfilled, '\n', nread);
Guido van Rossum6263d541997-05-10 22:07:25 +00001440 if (p == NULL) {
1441 /* Need a larger buffer to fit this line */
1442 nfilled += nread;
1443 buffersize *= 2;
Martin v. Löwis2a190742006-04-13 07:37:25 +00001444 if (buffersize > PY_SSIZE_T_MAX) {
Trent Mickf29f47b2000-08-11 19:02:59 +00001445 PyErr_SetString(PyExc_OverflowError,
Guido van Rossume07d5cf2001-01-09 21:50:24 +00001446 "line is longer than a Python string can hold");
Trent Mickf29f47b2000-08-11 19:02:59 +00001447 goto error;
1448 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001449 if (big_buffer == NULL) {
1450 /* Create the big buffer */
1451 big_buffer = PyString_FromStringAndSize(
1452 NULL, buffersize);
1453 if (big_buffer == NULL)
1454 goto error;
1455 buffer = PyString_AS_STRING(big_buffer);
1456 memcpy(buffer, small_buffer, nfilled);
1457 }
1458 else {
1459 /* Grow the big buffer */
Jack Jansen7b8c7542002-04-14 20:12:41 +00001460 if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
1461 goto error;
Guido van Rossum6263d541997-05-10 22:07:25 +00001462 buffer = PyString_AS_STRING(big_buffer);
1463 }
1464 continue;
1465 }
1466 end = buffer+nfilled+nread;
1467 q = buffer;
1468 do {
1469 /* Process complete lines */
1470 p++;
1471 line = PyString_FromStringAndSize(q, p-q);
1472 if (line == NULL)
1473 goto error;
1474 err = PyList_Append(list, line);
1475 Py_DECREF(line);
1476 if (err != 0)
1477 goto error;
1478 q = p;
Anthony Baxter377be112006-04-11 06:54:30 +00001479 p = (char *)memchr(q, '\n', end-q);
Guido van Rossum6263d541997-05-10 22:07:25 +00001480 } while (p != NULL);
1481 /* Move the remaining incomplete line to the start */
1482 nfilled = end-q;
1483 memmove(buffer, q, nfilled);
Guido van Rossum789a1611997-05-10 22:33:55 +00001484 if (sizehint > 0)
1485 if (totalread >= (size_t)sizehint)
1486 break;
Guido van Rossumce5ba841991-03-06 13:06:18 +00001487 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001488 if (nfilled != 0) {
1489 /* Partial last line */
1490 line = PyString_FromStringAndSize(buffer, nfilled);
1491 if (line == NULL)
1492 goto error;
Guido van Rossum789a1611997-05-10 22:33:55 +00001493 if (sizehint > 0) {
1494 /* Need to complete the last line */
Marc-André Lemburg1f468602000-07-05 15:32:40 +00001495 PyObject *rest = get_line(f, 0);
Guido van Rossum789a1611997-05-10 22:33:55 +00001496 if (rest == NULL) {
1497 Py_DECREF(line);
1498 goto error;
1499 }
1500 PyString_Concat(&line, rest);
1501 Py_DECREF(rest);
1502 if (line == NULL)
1503 goto error;
1504 }
Guido van Rossum6263d541997-05-10 22:07:25 +00001505 err = PyList_Append(list, line);
1506 Py_DECREF(line);
1507 if (err != 0)
1508 goto error;
1509 }
1510 cleanup:
Tim Peters5de98422002-04-27 18:44:32 +00001511 Py_XDECREF(big_buffer);
Guido van Rossumce5ba841991-03-06 13:06:18 +00001512 return list;
1513}
1514
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001515static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001516file_write(PyFileObject *f, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001517{
Guido van Rossumd7297e61992-07-06 14:19:26 +00001518 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001519 Py_ssize_t n, n2;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001520 if (f->f_fp == NULL)
1521 return err_closed();
Michael W. Hudsone2ec3eb2001-10-31 18:51:01 +00001522 if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001523 return NULL;
Guido van Rossumeb183da1991-04-04 10:44:06 +00001524 f->f_softspace = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001525 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001526 errno = 0;
Guido van Rossumd7297e61992-07-06 14:19:26 +00001527 n2 = fwrite(s, 1, n, f->f_fp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001528 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001529 if (n2 != n) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001530 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossumfebd5511992-03-04 16:39:24 +00001531 clearerr(f->f_fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001532 return NULL;
1533 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001534 Py_INCREF(Py_None);
1535 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001536}
1537
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001538static PyObject *
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001539file_writelines(PyFileObject *f, PyObject *seq)
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001540{
Guido van Rossumee70ad12000-03-13 16:27:06 +00001541#define CHUNKSIZE 1000
1542 PyObject *list, *line;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001543 PyObject *it; /* iter(seq) */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001544 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001545 int index, islist;
1546 Py_ssize_t i, j, nwritten, len;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001547
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001548 assert(seq != NULL);
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001549 if (f->f_fp == NULL)
1550 return err_closed();
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001551
1552 result = NULL;
1553 list = NULL;
1554 islist = PyList_Check(seq);
1555 if (islist)
1556 it = NULL;
1557 else {
1558 it = PyObject_GetIter(seq);
1559 if (it == NULL) {
1560 PyErr_SetString(PyExc_TypeError,
1561 "writelines() requires an iterable argument");
1562 return NULL;
1563 }
1564 /* From here on, fail by going to error, to reclaim "it". */
1565 list = PyList_New(CHUNKSIZE);
1566 if (list == NULL)
1567 goto error;
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001568 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001569
1570 /* Strategy: slurp CHUNKSIZE lines into a private list,
1571 checking that they are all strings, then write that list
1572 without holding the interpreter lock, then come back for more. */
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001573 for (index = 0; ; index += CHUNKSIZE) {
Guido van Rossumee70ad12000-03-13 16:27:06 +00001574 if (islist) {
1575 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001576 list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001577 if (list == NULL)
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001578 goto error;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001579 j = PyList_GET_SIZE(list);
1580 }
1581 else {
1582 for (j = 0; j < CHUNKSIZE; j++) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001583 line = PyIter_Next(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001584 if (line == NULL) {
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001585 if (PyErr_Occurred())
1586 goto error;
1587 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001588 }
Guido van Rossumee70ad12000-03-13 16:27:06 +00001589 PyList_SetItem(list, j, line);
1590 }
1591 }
1592 if (j == 0)
1593 break;
1594
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001595 /* Check that all entries are indeed strings. If not,
1596 apply the same rules as for file.write() and
1597 convert the results to strings. This is slow, but
1598 seems to be the only way since all conversion APIs
1599 could potentially execute Python code. */
1600 for (i = 0; i < j; i++) {
1601 PyObject *v = PyList_GET_ITEM(list, i);
1602 if (!PyString_Check(v)) {
1603 const char *buffer;
Tim Peters86821b22001-01-07 21:19:34 +00001604 if (((f->f_binary &&
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001605 PyObject_AsReadBuffer(v,
1606 (const void**)&buffer,
1607 &len)) ||
1608 PyObject_AsCharBuffer(v,
1609 &buffer,
1610 &len))) {
1611 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001612 "writelines() argument must be a sequence of strings");
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001613 goto error;
1614 }
1615 line = PyString_FromStringAndSize(buffer,
1616 len);
1617 if (line == NULL)
1618 goto error;
1619 Py_DECREF(v);
Marc-André Lemburgf5e96fa2000-08-25 22:49:05 +00001620 PyList_SET_ITEM(list, i, line);
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001621 }
1622 }
1623
1624 /* Since we are releasing the global lock, the
1625 following code may *not* execute Python code. */
Guido van Rossumee70ad12000-03-13 16:27:06 +00001626 Py_BEGIN_ALLOW_THREADS
1627 f->f_softspace = 0;
1628 errno = 0;
1629 for (i = 0; i < j; i++) {
Marc-André Lemburg6ef68b52000-08-25 22:39:50 +00001630 line = PyList_GET_ITEM(list, i);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001631 len = PyString_GET_SIZE(line);
1632 nwritten = fwrite(PyString_AS_STRING(line),
1633 1, len, f->f_fp);
1634 if (nwritten != len) {
1635 Py_BLOCK_THREADS
1636 PyErr_SetFromErrno(PyExc_IOError);
1637 clearerr(f->f_fp);
1638 goto error;
1639 }
1640 }
1641 Py_END_ALLOW_THREADS
1642
1643 if (j < CHUNKSIZE)
1644 break;
Guido van Rossumee70ad12000-03-13 16:27:06 +00001645 }
1646
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001647 Py_INCREF(Py_None);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001648 result = Py_None;
1649 error:
1650 Py_XDECREF(list);
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001651 Py_XDECREF(it);
Guido van Rossumee70ad12000-03-13 16:27:06 +00001652 return result;
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001653#undef CHUNKSIZE
Guido van Rossum5a2a6831993-10-25 09:59:04 +00001654}
1655
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001656static PyObject *
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001657file_self(PyFileObject *f)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001658{
1659 if (f->f_fp == NULL)
1660 return err_closed();
1661 Py_INCREF(f);
1662 return (PyObject *)f;
1663}
1664
Georg Brandl98b40ad2006-06-08 14:50:21 +00001665static PyObject *
Georg Brandlad61bc82008-02-23 15:11:18 +00001666file_exit(PyObject *f, PyObject *args)
Georg Brandl98b40ad2006-06-08 14:50:21 +00001667{
Georg Brandlad61bc82008-02-23 15:11:18 +00001668 PyObject *ret = PyObject_CallMethod(f, "close", NULL);
Georg Brandl98b40ad2006-06-08 14:50:21 +00001669 if (!ret)
1670 /* If error occurred, pass through */
1671 return NULL;
1672 Py_DECREF(ret);
1673 /* We cannot return the result of close since a true
1674 * value will be interpreted as "yes, swallow the
1675 * exception if one was raised inside the with block". */
1676 Py_RETURN_NONE;
1677}
1678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001679PyDoc_STRVAR(readline_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001680"readline([size]) -> next line from the file, as a string.\n"
1681"\n"
1682"Retain newline. A non-negative size argument limits the maximum\n"
1683"number of bytes to return (an incomplete line may be returned then).\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001684"Return an empty string at EOF.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001686PyDoc_STRVAR(read_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001687"read([size]) -> read at most size bytes, returned as a string.\n"
1688"\n"
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001689"If the size argument is negative or omitted, read until EOF is reached.\n"
1690"Notice that when in non-blocking mode, less data than what was requested\n"
1691"may be returned, even if no size parameter was given.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001693PyDoc_STRVAR(write_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001694"write(str) -> None. Write string str to file.\n"
1695"\n"
1696"Note that due to buffering, flush() or close() may be needed before\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001697"the file on disk reflects the data written.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001699PyDoc_STRVAR(fileno_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001700"fileno() -> integer \"file descriptor\".\n"
1701"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001702"This is needed for lower-level file interfaces, such os.read().");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001704PyDoc_STRVAR(seek_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001705"seek(offset[, whence]) -> None. Move to new file position.\n"
1706"\n"
1707"Argument offset is a byte count. Optional argument whence defaults to\n"
1708"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1709"(move relative to current position, positive or negative), and 2 (move\n"
1710"relative to end of file, usually negative, although many platforms allow\n"
Martin v. Löwis849a9722003-10-18 09:38:01 +00001711"seeking beyond the end of a file). If the file is opened in text mode,\n"
1712"only offsets returned by tell() are legal. Use of other offsets causes\n"
1713"undefined behavior."
Tim Petersefc3a3a2001-09-20 07:55:22 +00001714"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001715"Note that not all file objects are seekable.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001716
Guido van Rossumd7047b31995-01-02 19:07:15 +00001717#ifdef HAVE_FTRUNCATE
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001718PyDoc_STRVAR(truncate_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001719"truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1720"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001721"Size defaults to the current file position, as returned by tell().");
Guido van Rossumd7047b31995-01-02 19:07:15 +00001722#endif
Tim Petersefc3a3a2001-09-20 07:55:22 +00001723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001724PyDoc_STRVAR(tell_doc,
1725"tell() -> current file position, an integer (may be a long integer).");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001727PyDoc_STRVAR(readinto_doc,
1728"readinto() -> Undocumented. Don't use this; it may go away.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001730PyDoc_STRVAR(readlines_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001731"readlines([size]) -> list of strings, each a line from the file.\n"
1732"\n"
1733"Call readline() repeatedly and return a list of the lines so read.\n"
1734"The optional size argument, if given, is an approximate bound on the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735"total number of bytes in the lines returned.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001737PyDoc_STRVAR(xreadlines_doc,
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001738"xreadlines() -> returns self.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001739"\n"
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001740"For backward compatibility. File objects now include the performance\n"
1741"optimizations previously implemented in the xreadlines module.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001743PyDoc_STRVAR(writelines_doc,
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001744"writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001745"\n"
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001746"Note that newlines are not added. The sequence can be any iterable object\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001747"producing strings. This is equivalent to calling write() for each string.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001749PyDoc_STRVAR(flush_doc,
1750"flush() -> None. Flush the internal I/O buffer.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001752PyDoc_STRVAR(close_doc,
Tim Petersefc3a3a2001-09-20 07:55:22 +00001753"close() -> None or (perhaps) an integer. Close the file.\n"
1754"\n"
Guido van Rossum77f6a652002-04-03 22:41:51 +00001755"Sets data attribute .closed to True. A closed file cannot be used for\n"
Tim Petersefc3a3a2001-09-20 07:55:22 +00001756"further I/O operations. close() may be called more than once without\n"
1757"error. Some kinds of file objects (for example, opened by popen())\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001758"may return an exit status upon closing.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760PyDoc_STRVAR(isatty_doc,
1761"isatty() -> true or false. True if the file is connected to a tty device.");
Tim Petersefc3a3a2001-09-20 07:55:22 +00001762
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001763PyDoc_STRVAR(enter_doc,
1764 "__enter__() -> self.");
1765
Georg Brandl98b40ad2006-06-08 14:50:21 +00001766PyDoc_STRVAR(exit_doc,
1767 "__exit__(*excinfo) -> None. Closes the file.");
1768
Tim Petersefc3a3a2001-09-20 07:55:22 +00001769static PyMethodDef file_methods[] = {
Jeremy Hylton8b735422002-08-14 21:01:41 +00001770 {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
1771 {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
1772 {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
1773 {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
1774 {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001775#ifdef HAVE_FTRUNCATE
Jeremy Hylton8b735422002-08-14 21:01:41 +00001776 {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
Tim Petersefc3a3a2001-09-20 07:55:22 +00001777#endif
Jeremy Hylton8b735422002-08-14 21:01:41 +00001778 {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
1779 {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
1780 {"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001781 {"xreadlines",(PyCFunction)file_self, METH_NOARGS, xreadlines_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001782 {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
1783 {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
1784 {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
1785 {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001786 {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
Georg Brandl98b40ad2006-06-08 14:50:21 +00001787 {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
Jeremy Hylton8b735422002-08-14 21:01:41 +00001788 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001789};
1790
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001791#define OFF(x) offsetof(PyFileObject, x)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001792
Guido van Rossum6f799372001-09-20 20:46:19 +00001793static PyMemberDef file_memberlist[] = {
1794 {"softspace", T_INT, OFF(f_softspace), 0,
1795 "flag indicating that a space needs to be printed; used by print"},
1796 {"mode", T_OBJECT, OFF(f_mode), RO,
Martin v. Löwis6233c9b2002-12-11 13:06:53 +00001797 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
Guido van Rossum6f799372001-09-20 20:46:19 +00001798 {"name", T_OBJECT, OFF(f_name), RO,
1799 "file name"},
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001800 {"encoding", T_OBJECT, OFF(f_encoding), RO,
1801 "file encoding"},
Guido van Rossumb6775db1994-08-01 11:34:53 +00001802 /* getattr(f, "closed") is implemented without this table */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001803 {NULL} /* Sentinel */
1804};
1805
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001806static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807get_closed(PyFileObject *f, void *closure)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001808{
Guido van Rossum77f6a652002-04-03 22:41:51 +00001809 return PyBool_FromLong((long)(f->f_fp == 0));
Guido van Rossumb6775db1994-08-01 11:34:53 +00001810}
Jack Jansen7b8c7542002-04-14 20:12:41 +00001811static PyObject *
1812get_newlines(PyFileObject *f, void *closure)
1813{
1814 switch (f->f_newlinetypes) {
1815 case NEWLINE_UNKNOWN:
1816 Py_INCREF(Py_None);
1817 return Py_None;
1818 case NEWLINE_CR:
1819 return PyString_FromString("\r");
1820 case NEWLINE_LF:
1821 return PyString_FromString("\n");
1822 case NEWLINE_CR|NEWLINE_LF:
1823 return Py_BuildValue("(ss)", "\r", "\n");
1824 case NEWLINE_CRLF:
1825 return PyString_FromString("\r\n");
1826 case NEWLINE_CR|NEWLINE_CRLF:
1827 return Py_BuildValue("(ss)", "\r", "\r\n");
1828 case NEWLINE_LF|NEWLINE_CRLF:
1829 return Py_BuildValue("(ss)", "\n", "\r\n");
1830 case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
1831 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1832 default:
Tim Petersf1827cf2003-09-07 03:30:18 +00001833 PyErr_Format(PyExc_SystemError,
1834 "Unknown newlines value 0x%x\n",
Jeremy Hylton8b735422002-08-14 21:01:41 +00001835 f->f_newlinetypes);
Jack Jansen7b8c7542002-04-14 20:12:41 +00001836 return NULL;
1837 }
1838}
Guido van Rossumb6775db1994-08-01 11:34:53 +00001839
Guido van Rossum32d34c82001-09-20 21:45:26 +00001840static PyGetSetDef file_getsetlist[] = {
Guido van Rossum77f6a652002-04-03 22:41:51 +00001841 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Tim Petersf1827cf2003-09-07 03:30:18 +00001842 {"newlines", (getter)get_newlines, NULL,
Jeremy Hylton8b735422002-08-14 21:01:41 +00001843 "end-of-line convention used in this file"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 {0},
1845};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001847static void
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001848drop_readahead(PyFileObject *f)
Guido van Rossum65967252001-04-21 13:20:18 +00001849{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001850 if (f->f_buf != NULL) {
1851 PyMem_Free(f->f_buf);
1852 f->f_buf = NULL;
1853 }
Guido van Rossum65967252001-04-21 13:20:18 +00001854}
1855
Tim Petersf1827cf2003-09-07 03:30:18 +00001856/* Make sure that file has a readahead buffer with at least one byte
1857 (unless at EOF) and no more than bufsize. Returns negative value on
Georg Brandled02eb62006-03-31 20:31:02 +00001858 error, will set MemoryError if bufsize bytes cannot be allocated. */
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001859static int
1860readahead(PyFileObject *f, int bufsize)
1861{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001862 Py_ssize_t chunksize;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001863
1864 if (f->f_buf != NULL) {
Tim Petersf1827cf2003-09-07 03:30:18 +00001865 if( (f->f_bufend - f->f_bufptr) >= 1)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001866 return 0;
1867 else
1868 drop_readahead(f);
1869 }
Anthony Baxter377be112006-04-11 06:54:30 +00001870 if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
Georg Brandled02eb62006-03-31 20:31:02 +00001871 PyErr_NoMemory();
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001872 return -1;
1873 }
1874 Py_BEGIN_ALLOW_THREADS
1875 errno = 0;
1876 chunksize = Py_UniversalNewlineFread(
1877 f->f_buf, bufsize, f->f_fp, (PyObject *)f);
1878 Py_END_ALLOW_THREADS
1879 if (chunksize == 0) {
1880 if (ferror(f->f_fp)) {
1881 PyErr_SetFromErrno(PyExc_IOError);
1882 clearerr(f->f_fp);
1883 drop_readahead(f);
1884 return -1;
1885 }
1886 }
1887 f->f_bufptr = f->f_buf;
1888 f->f_bufend = f->f_buf + chunksize;
1889 return 0;
1890}
1891
1892/* Used by file_iternext. The returned string will start with 'skip'
Tim Petersf1827cf2003-09-07 03:30:18 +00001893 uninitialized bytes followed by the remainder of the line. Don't be
1894 horrified by the recursive call: maximum recursion depth is limited by
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001895 logarithmic buffer growth to about 50 even when reading a 1gb line. */
1896
Neal Norwitzd8b995f2002-08-06 21:50:54 +00001897static PyStringObject *
1898readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
1899{
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001900 PyStringObject* s;
1901 char *bufptr;
1902 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001903 Py_ssize_t len;
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001904
1905 if (f->f_buf == NULL)
Tim Petersf1827cf2003-09-07 03:30:18 +00001906 if (readahead(f, bufsize) < 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001907 return NULL;
1908
1909 len = f->f_bufend - f->f_bufptr;
Tim Petersf1827cf2003-09-07 03:30:18 +00001910 if (len == 0)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001911 return (PyStringObject *)
1912 PyString_FromStringAndSize(NULL, skip);
Anthony Baxter377be112006-04-11 06:54:30 +00001913 bufptr = (char *)memchr(f->f_bufptr, '\n', len);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001914 if (bufptr != NULL) {
1915 bufptr++; /* Count the '\n' */
1916 len = bufptr - f->f_bufptr;
1917 s = (PyStringObject *)
1918 PyString_FromStringAndSize(NULL, skip+len);
Tim Petersf1827cf2003-09-07 03:30:18 +00001919 if (s == NULL)
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001920 return NULL;
1921 memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
1922 f->f_bufptr = bufptr;
1923 if (bufptr == f->f_bufend)
1924 drop_readahead(f);
1925 } else {
1926 bufptr = f->f_bufptr;
1927 buf = f->f_buf;
1928 f->f_buf = NULL; /* Force new readahead buffer */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001929 assert(skip+len < INT_MAX);
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001930 s = readahead_get_line_skip(
Martin v. Löwis18e16552006-02-15 17:27:45 +00001931 f, (int)(skip+len), bufsize + (bufsize>>2) );
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001932 if (s == NULL) {
1933 PyMem_Free(buf);
1934 return NULL;
1935 }
1936 memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
1937 PyMem_Free(buf);
1938 }
1939 return s;
1940}
1941
1942/* A larger buffer size may actually decrease performance. */
1943#define READAHEAD_BUFSIZE 8192
1944
1945static PyObject *
1946file_iternext(PyFileObject *f)
1947{
1948 PyStringObject* l;
1949
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001950 if (f->f_fp == NULL)
1951 return err_closed();
1952
Guido van Rossum7a6e9592002-08-06 15:55:28 +00001953 l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
1954 if (l == NULL || PyString_GET_SIZE(l) == 0) {
1955 Py_XDECREF(l);
1956 return NULL;
1957 }
1958 return (PyObject *)l;
1959}
1960
1961
Tim Peters59c9a642001-09-13 05:38:56 +00001962static PyObject *
1963file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1964{
Tim Peters44410012001-09-14 03:26:08 +00001965 PyObject *self;
1966 static PyObject *not_yet_string;
1967
1968 assert(type != NULL && type->tp_alloc != NULL);
1969
1970 if (not_yet_string == NULL) {
Christian Heimesd7e1b2b2008-01-28 02:07:53 +00001971 not_yet_string = PyString_InternFromString("<uninitialized file>");
Tim Peters44410012001-09-14 03:26:08 +00001972 if (not_yet_string == NULL)
1973 return NULL;
1974 }
1975
1976 self = type->tp_alloc(type, 0);
1977 if (self != NULL) {
1978 /* Always fill in the name and mode, so that nobody else
1979 needs to special-case NULLs there. */
1980 Py_INCREF(not_yet_string);
1981 ((PyFileObject *)self)->f_name = not_yet_string;
1982 Py_INCREF(not_yet_string);
1983 ((PyFileObject *)self)->f_mode = not_yet_string;
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001984 Py_INCREF(Py_None);
1985 ((PyFileObject *)self)->f_encoding = Py_None;
Raymond Hettingercb87bc82004-05-31 00:35:52 +00001986 ((PyFileObject *)self)->weakreflist = NULL;
Tim Peters44410012001-09-14 03:26:08 +00001987 }
1988 return self;
1989}
1990
1991static int
1992file_init(PyObject *self, PyObject *args, PyObject *kwds)
1993{
1994 PyFileObject *foself = (PyFileObject *)self;
1995 int ret = 0;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001996 static char *kwlist[] = {"name", "mode", "buffering", 0};
Tim Peters59c9a642001-09-13 05:38:56 +00001997 char *name = NULL;
1998 char *mode = "r";
1999 int bufsize = -1;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002000 int wideargument = 0;
Tim Peters44410012001-09-14 03:26:08 +00002001
2002 assert(PyFile_Check(self));
2003 if (foself->f_fp != NULL) {
2004 /* Have to close the existing file first. */
2005 PyObject *closeresult = file_close(foself);
2006 if (closeresult == NULL)
2007 return -1;
2008 Py_DECREF(closeresult);
2009 }
Tim Peters59c9a642001-09-13 05:38:56 +00002010
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002011#ifdef Py_WIN_WIDE_FILENAMES
2012 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2013 PyObject *po;
2014 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
2015 kwlist, &po, &mode, &bufsize)) {
2016 wideargument = 1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002017 if (fill_file_fields(foself, NULL, po, mode,
2018 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002019 goto Error;
2020 } else {
2021 /* Drop the argument parsing error as narrow
2022 strings are also valid. */
2023 PyErr_Clear();
2024 }
2025 }
2026#endif
2027
2028 if (!wideargument) {
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002029 PyObject *o_name;
2030
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002031 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
2032 Py_FileSystemDefaultEncoding,
2033 &name,
2034 &mode, &bufsize))
2035 return -1;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002036
2037 /* We parse again to get the name as a PyObject */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002038 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
2039 kwlist, &o_name, &mode,
2040 &bufsize))
Brett Cannon2b3666f2006-08-31 18:54:26 +00002041 goto Error;
Nicholas Bastinabce8a62004-03-21 20:24:07 +00002042
2043 if (fill_file_fields(foself, NULL, o_name, mode,
2044 fclose) == NULL)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00002045 goto Error;
2046 }
Tim Peters44410012001-09-14 03:26:08 +00002047 if (open_the_file(foself, name, mode) == NULL)
2048 goto Error;
Martin v. Löwis1e3bdf62003-09-04 19:01:46 +00002049 foself->f_setbuf = NULL;
Tim Peters44410012001-09-14 03:26:08 +00002050 PyFile_SetBufSize(self, bufsize);
2051 goto Done;
2052
2053Error:
2054 ret = -1;
2055 /* fall through */
2056Done:
Tim Peters59c9a642001-09-13 05:38:56 +00002057 PyMem_Free(name); /* free the encoded string */
Tim Peters44410012001-09-14 03:26:08 +00002058 return ret;
Tim Peters59c9a642001-09-13 05:38:56 +00002059}
2060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002061PyDoc_VAR(file_doc) =
2062PyDoc_STR(
Tim Peters59c9a642001-09-13 05:38:56 +00002063"file(name[, mode[, buffering]]) -> file object\n"
2064"\n"
2065"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2066"writing or appending. The file will be created if it doesn't exist\n"
2067"when opened for writing or appending; it will be truncated when\n"
2068"opened for writing. Add a 'b' to the mode for binary files.\n"
2069"Add a '+' to the mode to allow simultaneous reading and writing.\n"
2070"If the buffering argument is given, 0 means unbuffered, 1 means line\n"
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00002071"buffered, and larger numbers specify the buffer size. The preferred way\n"
2072"to open a file is with the builtin open() function.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002073)
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002074PyDoc_STR(
Barry Warsaw4be55b52002-05-22 20:37:53 +00002075"Add a 'U' to mode to open the file for input with universal newline\n"
2076"support. Any line ending in the input file will be seen as a '\\n'\n"
2077"in Python. Also, a file so opened gains the attribute 'newlines';\n"
2078"the value for this attribute is one of None (no newline read yet),\n"
2079"'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2080"\n"
2081"'U' cannot be combined with 'w' or '+' mode.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002082);
Tim Peters59c9a642001-09-13 05:38:56 +00002083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002084PyTypeObject PyFile_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002085 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002086 "file",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002087 sizeof(PyFileObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002088 0,
Guido van Rossum65967252001-04-21 13:20:18 +00002089 (destructor)file_dealloc, /* tp_dealloc */
2090 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091 0, /* tp_getattr */
2092 0, /* tp_setattr */
Guido van Rossum65967252001-04-21 13:20:18 +00002093 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 (reprfunc)file_repr, /* tp_repr */
Guido van Rossum65967252001-04-21 13:20:18 +00002095 0, /* tp_as_number */
2096 0, /* tp_as_sequence */
2097 0, /* tp_as_mapping */
2098 0, /* tp_hash */
2099 0, /* tp_call */
2100 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 PyObject_GenericGetAttr, /* tp_getattro */
Tim Peters015dd822003-05-04 04:16:52 +00002102 /* softspace is writable: we must supply tp_setattro */
2103 PyObject_GenericSetAttr, /* tp_setattro */
Guido van Rossum65967252001-04-21 13:20:18 +00002104 0, /* tp_as_buffer */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002105 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Tim Peters59c9a642001-09-13 05:38:56 +00002106 file_doc, /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 0, /* tp_traverse */
2108 0, /* tp_clear */
Guido van Rossum65967252001-04-21 13:20:18 +00002109 0, /* tp_richcompare */
Raymond Hettingercb87bc82004-05-31 00:35:52 +00002110 offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002111 (getiterfunc)file_self, /* tp_iter */
Guido van Rossum7a6e9592002-08-06 15:55:28 +00002112 (iternextfunc)file_iternext, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 file_methods, /* tp_methods */
2114 file_memberlist, /* tp_members */
2115 file_getsetlist, /* tp_getset */
2116 0, /* tp_base */
2117 0, /* tp_dict */
Tim Peters59c9a642001-09-13 05:38:56 +00002118 0, /* tp_descr_get */
2119 0, /* tp_descr_set */
2120 0, /* tp_dictoffset */
Georg Brandl347b3002006-03-30 11:57:00 +00002121 file_init, /* tp_init */
Tim Peters44410012001-09-14 03:26:08 +00002122 PyType_GenericAlloc, /* tp_alloc */
Tim Peters59c9a642001-09-13 05:38:56 +00002123 file_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00002124 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002125};
Guido van Rossumeb183da1991-04-04 10:44:06 +00002126
2127/* Interface for the 'soft space' between print items. */
2128
2129int
Fred Drakefd99de62000-07-09 05:02:18 +00002130PyFile_SoftSpace(PyObject *f, int newflag)
Guido van Rossumeb183da1991-04-04 10:44:06 +00002131{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002132 long oldflag = 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002133 if (f == NULL) {
2134 /* Do nothing */
2135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 else if (PyFile_Check(f)) {
2137 oldflag = ((PyFileObject *)f)->f_softspace;
2138 ((PyFileObject *)f)->f_softspace = newflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002139 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00002140 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141 PyObject *v;
2142 v = PyObject_GetAttrString(f, "softspace");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002143 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002145 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146 if (PyInt_Check(v))
2147 oldflag = PyInt_AsLong(v);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002148 assert(oldflag < INT_MAX);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002149 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002150 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151 v = PyInt_FromLong((long)newflag);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002152 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002153 PyErr_Clear();
Guido van Rossum3165fe61992-09-25 21:59:05 +00002154 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002155 if (PyObject_SetAttrString(f, "softspace", v) != 0)
2156 PyErr_Clear();
2157 Py_DECREF(v);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002158 }
2159 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002160 return (int)oldflag;
Guido van Rossumeb183da1991-04-04 10:44:06 +00002161}
Guido van Rossum3165fe61992-09-25 21:59:05 +00002162
2163/* Interfaces to write objects/strings to file-like objects */
2164
2165int
Fred Drakefd99de62000-07-09 05:02:18 +00002166PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002167{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002168 PyObject *writer, *value, *args, *result;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002169 if (f == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002170 PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002171 return -1;
2172 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173 else if (PyFile_Check(f)) {
2174 FILE *fp = PyFile_AsFile(f);
Fred Drake086a0f72004-03-19 15:22:36 +00002175#ifdef Py_USING_UNICODE
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002176 PyObject *enc = ((PyFileObject*)f)->f_encoding;
2177 int result;
Fred Drake086a0f72004-03-19 15:22:36 +00002178#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002179 if (fp == NULL) {
2180 err_closed();
2181 return -1;
2182 }
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002183#ifdef Py_USING_UNICODE
Tim Petersf1827cf2003-09-07 03:30:18 +00002184 if ((flags & Py_PRINT_RAW) &&
Martin v. Löwis415da6e2003-05-18 12:56:25 +00002185 PyUnicode_Check(v) && enc != Py_None) {
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002186 char *cenc = PyString_AS_STRING(enc);
2187 value = PyUnicode_AsEncodedString(v, cenc, "strict");
2188 if (value == NULL)
2189 return -1;
2190 } else {
2191 value = v;
2192 Py_INCREF(value);
2193 }
2194 result = PyObject_Print(value, fp, flags);
2195 Py_DECREF(value);
2196 return result;
2197#else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002198 return PyObject_Print(v, fp, flags);
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002199#endif
Guido van Rossum3165fe61992-09-25 21:59:05 +00002200 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201 writer = PyObject_GetAttrString(f, "write");
Guido van Rossum3165fe61992-09-25 21:59:05 +00002202 if (writer == NULL)
2203 return -1;
Martin v. Löwis2777c022001-09-19 13:47:32 +00002204 if (flags & Py_PRINT_RAW) {
2205 if (PyUnicode_Check(v)) {
2206 value = v;
2207 Py_INCREF(value);
2208 } else
2209 value = PyObject_Str(v);
2210 }
2211 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002212 value = PyObject_Repr(v);
Guido van Rossumc6004111993-11-05 10:22:19 +00002213 if (value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002214 Py_DECREF(writer);
Guido van Rossumc6004111993-11-05 10:22:19 +00002215 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002216 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002217 args = PyTuple_Pack(1, value);
Guido van Rossume9eec541997-05-22 14:02:25 +00002218 if (args == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002219 Py_DECREF(value);
2220 Py_DECREF(writer);
Guido van Rossumd3f9a1a1995-07-10 23:32:26 +00002221 return -1;
2222 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002223 result = PyEval_CallObject(writer, args);
2224 Py_DECREF(args);
2225 Py_DECREF(value);
2226 Py_DECREF(writer);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002227 if (result == NULL)
2228 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002229 Py_DECREF(result);
Guido van Rossum3165fe61992-09-25 21:59:05 +00002230 return 0;
2231}
2232
Guido van Rossum27a60b11997-05-22 22:25:11 +00002233int
Tim Petersc1bbcb82001-11-28 22:13:25 +00002234PyFile_WriteString(const char *s, PyObject *f)
Guido van Rossum3165fe61992-09-25 21:59:05 +00002235{
2236 if (f == NULL) {
Guido van Rossum27a60b11997-05-22 22:25:11 +00002237 /* Should be caused by a pre-existing error */
Fred Drakefd99de62000-07-09 05:02:18 +00002238 if (!PyErr_Occurred())
Guido van Rossum27a60b11997-05-22 22:25:11 +00002239 PyErr_SetString(PyExc_SystemError,
2240 "null file for PyFile_WriteString");
2241 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002242 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002243 else if (PyFile_Check(f)) {
2244 FILE *fp = PyFile_AsFile(f);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002245 if (fp == NULL) {
2246 err_closed();
2247 return -1;
2248 }
Brett Cannon01531592007-09-17 03:28:34 +00002249 Py_BEGIN_ALLOW_THREADS
Guido van Rossum27a60b11997-05-22 22:25:11 +00002250 fputs(s, fp);
Brett Cannon01531592007-09-17 03:28:34 +00002251 Py_END_ALLOW_THREADS
Guido van Rossum27a60b11997-05-22 22:25:11 +00002252 return 0;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002253 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002254 else if (!PyErr_Occurred()) {
2255 PyObject *v = PyString_FromString(s);
Guido van Rossum27a60b11997-05-22 22:25:11 +00002256 int err;
2257 if (v == NULL)
2258 return -1;
2259 err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
2260 Py_DECREF(v);
2261 return err;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002262 }
Guido van Rossum74ba2471997-07-13 03:56:50 +00002263 else
2264 return -1;
Guido van Rossum3165fe61992-09-25 21:59:05 +00002265}
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002266
2267/* Try to get a file-descriptor from a Python object. If the object
2268 is an integer or long integer, its value is returned. If not, the
2269 object's fileno() method is called if it exists; the method must return
2270 an integer or long integer, which is returned as the file descriptor value.
2271 -1 is returned on failure.
2272*/
2273
2274int PyObject_AsFileDescriptor(PyObject *o)
2275{
2276 int fd;
2277 PyObject *meth;
2278
2279 if (PyInt_Check(o)) {
2280 fd = PyInt_AsLong(o);
2281 }
2282 else if (PyLong_Check(o)) {
2283 fd = PyLong_AsLong(o);
2284 }
2285 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
2286 {
2287 PyObject *fno = PyEval_CallObject(meth, NULL);
2288 Py_DECREF(meth);
2289 if (fno == NULL)
2290 return -1;
Tim Peters86821b22001-01-07 21:19:34 +00002291
Andrew M. Kuchling06051ed2000-07-13 23:56:54 +00002292 if (PyInt_Check(fno)) {
2293 fd = PyInt_AsLong(fno);
2294 Py_DECREF(fno);
2295 }
2296 else if (PyLong_Check(fno)) {
2297 fd = PyLong_AsLong(fno);
2298 Py_DECREF(fno);
2299 }
2300 else {
2301 PyErr_SetString(PyExc_TypeError,
2302 "fileno() returned a non-integer");
2303 Py_DECREF(fno);
2304 return -1;
2305 }
2306 }
2307 else {
2308 PyErr_SetString(PyExc_TypeError,
2309 "argument must be an int, or have a fileno() method.");
2310 return -1;
2311 }
2312
2313 if (fd < 0) {
2314 PyErr_Format(PyExc_ValueError,
2315 "file descriptor cannot be a negative integer (%i)",
2316 fd);
2317 return -1;
2318 }
2319 return fd;
2320}
Jack Jansen7b8c7542002-04-14 20:12:41 +00002321
Jack Jansen7b8c7542002-04-14 20:12:41 +00002322/* From here on we need access to the real fgets and fread */
2323#undef fgets
2324#undef fread
2325
2326/*
2327** Py_UniversalNewlineFgets is an fgets variation that understands
2328** all of \r, \n and \r\n conventions.
2329** The stream should be opened in binary mode.
2330** If fobj is NULL the routine always does newline conversion, and
2331** it may peek one char ahead to gobble the second char in \r\n.
2332** If fobj is non-NULL it must be a PyFileObject. In this case there
2333** is no readahead but in stead a flag is used to skip a following
2334** \n on the next read. Also, if the file is open in binary mode
2335** the whole conversion is skipped. Finally, the routine keeps track of
2336** the different types of newlines seen.
2337** Note that we need no error handling: fgets() treats error and eof
2338** identically.
2339*/
2340char *
2341Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
2342{
2343 char *p = buf;
2344 int c;
2345 int newlinetypes = 0;
2346 int skipnextlf = 0;
2347 int univ_newline = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002348
Jack Jansen7b8c7542002-04-14 20:12:41 +00002349 if (fobj) {
2350 if (!PyFile_Check(fobj)) {
2351 errno = ENXIO; /* What can you do... */
2352 return NULL;
2353 }
2354 univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
2355 if ( !univ_newline )
2356 return fgets(buf, n, stream);
2357 newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
2358 skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
2359 }
2360 FLOCKFILE(stream);
2361 c = 'x'; /* Shut up gcc warning */
2362 while (--n > 0 && (c = GETC(stream)) != EOF ) {
2363 if (skipnextlf ) {
2364 skipnextlf = 0;
2365 if (c == '\n') {
2366 /* Seeing a \n here with skipnextlf true
2367 ** means we saw a \r before.
2368 */
2369 newlinetypes |= NEWLINE_CRLF;
2370 c = GETC(stream);
2371 if (c == EOF) break;
2372 } else {
2373 /*
2374 ** Note that c == EOF also brings us here,
2375 ** so we're okay if the last char in the file
2376 ** is a CR.
2377 */
2378 newlinetypes |= NEWLINE_CR;
2379 }
2380 }
2381 if (c == '\r') {
2382 /* A \r is translated into a \n, and we skip
2383 ** an adjacent \n, if any. We don't set the
2384 ** newlinetypes flag until we've seen the next char.
2385 */
2386 skipnextlf = 1;
2387 c = '\n';
2388 } else if ( c == '\n') {
2389 newlinetypes |= NEWLINE_LF;
2390 }
2391 *p++ = c;
2392 if (c == '\n') break;
2393 }
2394 if ( c == EOF && skipnextlf )
2395 newlinetypes |= NEWLINE_CR;
2396 FUNLOCKFILE(stream);
2397 *p = '\0';
2398 if (fobj) {
2399 ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
2400 ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
2401 } else if ( skipnextlf ) {
2402 /* If we have no file object we cannot save the
2403 ** skipnextlf flag. We have to readahead, which
2404 ** will cause a pause if we're reading from an
2405 ** interactive stream, but that is very unlikely
2406 ** unless we're doing something silly like
2407 ** execfile("/dev/tty").
2408 */
2409 c = GETC(stream);
2410 if ( c != '\n' )
2411 ungetc(c, stream);
2412 }
2413 if (p == buf)
2414 return NULL;
2415 return buf;
2416}
2417
2418/*
2419** Py_UniversalNewlineFread is an fread variation that understands
2420** all of \r, \n and \r\n conventions.
2421** The stream should be opened in binary mode.
2422** fobj must be a PyFileObject. In this case there
2423** is no readahead but in stead a flag is used to skip a following
2424** \n on the next read. Also, if the file is open in binary mode
2425** the whole conversion is skipped. Finally, the routine keeps track of
2426** the different types of newlines seen.
2427*/
2428size_t
Tim Peters058b1412002-04-21 07:29:14 +00002429Py_UniversalNewlineFread(char *buf, size_t n,
Jack Jansen7b8c7542002-04-14 20:12:41 +00002430 FILE *stream, PyObject *fobj)
2431{
Tim Peters058b1412002-04-21 07:29:14 +00002432 char *dst = buf;
2433 PyFileObject *f = (PyFileObject *)fobj;
2434 int newlinetypes, skipnextlf;
2435
2436 assert(buf != NULL);
2437 assert(stream != NULL);
2438
Jack Jansen7b8c7542002-04-14 20:12:41 +00002439 if (!fobj || !PyFile_Check(fobj)) {
2440 errno = ENXIO; /* What can you do... */
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002441 return 0;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002442 }
Tim Peters058b1412002-04-21 07:29:14 +00002443 if (!f->f_univ_newline)
Jack Jansen7b8c7542002-04-14 20:12:41 +00002444 return fread(buf, 1, n, stream);
Tim Peters058b1412002-04-21 07:29:14 +00002445 newlinetypes = f->f_newlinetypes;
2446 skipnextlf = f->f_skipnextlf;
2447 /* Invariant: n is the number of bytes remaining to be filled
2448 * in the buffer.
2449 */
2450 while (n) {
2451 size_t nread;
2452 int shortread;
2453 char *src = dst;
2454
2455 nread = fread(dst, 1, n, stream);
2456 assert(nread <= n);
Neal Norwitzcb3319f2003-02-09 01:10:02 +00002457 if (nread == 0)
2458 break;
2459
Tim Peterse1682a82002-04-21 18:15:20 +00002460 n -= nread; /* assuming 1 byte out for each in; will adjust */
2461 shortread = n != 0; /* true iff EOF or error */
Tim Peters058b1412002-04-21 07:29:14 +00002462 while (nread--) {
2463 char c = *src++;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002464 if (c == '\r') {
Tim Peters058b1412002-04-21 07:29:14 +00002465 /* Save as LF and set flag to skip next LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002466 *dst++ = '\n';
2467 skipnextlf = 1;
Tim Peters058b1412002-04-21 07:29:14 +00002468 }
2469 else if (skipnextlf && c == '\n') {
2470 /* Skip LF, and remember we saw CR LF. */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002471 skipnextlf = 0;
2472 newlinetypes |= NEWLINE_CRLF;
Tim Peterse1682a82002-04-21 18:15:20 +00002473 ++n;
Tim Peters058b1412002-04-21 07:29:14 +00002474 }
2475 else {
2476 /* Normal char to be stored in buffer. Also
2477 * update the newlinetypes flag if either this
2478 * is an LF or the previous char was a CR.
2479 */
Jack Jansen7b8c7542002-04-14 20:12:41 +00002480 if (c == '\n')
2481 newlinetypes |= NEWLINE_LF;
2482 else if (skipnextlf)
2483 newlinetypes |= NEWLINE_CR;
2484 *dst++ = c;
2485 skipnextlf = 0;
2486 }
2487 }
Tim Peters058b1412002-04-21 07:29:14 +00002488 if (shortread) {
2489 /* If this is EOF, update type flags. */
2490 if (skipnextlf && feof(stream))
2491 newlinetypes |= NEWLINE_CR;
2492 break;
2493 }
Jack Jansen7b8c7542002-04-14 20:12:41 +00002494 }
Tim Peters058b1412002-04-21 07:29:14 +00002495 f->f_newlinetypes = newlinetypes;
2496 f->f_skipnextlf = skipnextlf;
2497 return dst - buf;
Jack Jansen7b8c7542002-04-14 20:12:41 +00002498}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002499
2500#ifdef __cplusplus
2501}
2502#endif