1 /* File object implementation */
3 #define PY_SSIZE_T_CLEAN
5 #include "structmember.h"
7 #ifdef HAVE_SYS_TYPES_H
9 #endif /* HAVE_SYS_TYPES_H */
12 #define fileno _fileno
13 /* can simulate truncate with Win32 API functions; see file_truncate */
14 #define HAVE_FTRUNCATE
15 #define WIN32_LEAN_AND_MEAN
20 /* Need GetVersion to see if on NT so safe to use _wfopen */
21 #define WIN32_LEAN_AND_MEAN
25 #if defined(PYOS_OS2) && defined(PYCC_GCC)
29 #define BUF(v) PyString_AS_STRING((PyStringObject *)v)
31 #ifndef DONT_HAVE_ERRNO_H
35 #ifdef HAVE_GETC_UNLOCKED
36 #define GETC(f) getc_unlocked(f)
37 #define FLOCKFILE(f) flockfile(f)
38 #define FUNLOCKFILE(f) funlockfile(f)
40 #define GETC(f) getc(f)
42 #define FUNLOCKFILE(f)
45 /* 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 */
52 * These macros release the GIL while preventing the f_close() function being
53 * called in the interval between them. For that purpose, a running total of
54 * the number of currently running unlocked code sections is kept in
55 * the unlocked_count field of the PyFileObject. The close() method raises
56 * an IOError if that field is non-zero. See issue #815646, #595601.
59 #define FILE_BEGIN_ALLOW_THREADS(fobj) \
61 fobj->unlocked_count++; \
62 Py_BEGIN_ALLOW_THREADS
64 #define FILE_END_ALLOW_THREADS(fobj) \
65 Py_END_ALLOW_THREADS \
66 fobj->unlocked_count--; \
67 assert(fobj->unlocked_count >= 0); \
70 #define FILE_ABORT_ALLOW_THREADS(fobj) \
72 fobj->unlocked_count--; \
73 assert(fobj->unlocked_count >= 0);
80 PyFile_AsFile(PyObject
*f
)
82 if (f
== NULL
|| !PyFile_Check(f
))
85 return ((PyFileObject
*)f
)->f_fp
;
88 void PyFile_IncUseCount(PyFileObject
*fobj
)
90 fobj
->unlocked_count
++;
93 void PyFile_DecUseCount(PyFileObject
*fobj
)
95 fobj
->unlocked_count
--;
96 assert(fobj
->unlocked_count
>= 0);
100 PyFile_Name(PyObject
*f
)
102 if (f
== NULL
|| !PyFile_Check(f
))
105 return ((PyFileObject
*)f
)->f_name
;
108 /* This is a safe wrapper around PyObject_Print to print to the FILE
109 of a PyFileObject. PyObject_Print releases the GIL but knows nothing
110 about PyFileObject. */
112 file_PyObject_Print(PyObject
*op
, PyFileObject
*f
, int flags
)
115 PyFile_IncUseCount(f
);
116 result
= PyObject_Print(op
, f
->f_fp
, flags
);
117 PyFile_DecUseCount(f
);
121 /* On Unix, fopen will succeed for directories.
122 In Python, there should be no file objects referring to
123 directories, so we need a check. */
126 dircheck(PyFileObject
* f
)
128 #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
132 if (fstat(fileno(f
->f_fp
), &buf
) == 0 &&
133 S_ISDIR(buf
.st_mode
)) {
134 char *msg
= strerror(EISDIR
);
135 PyObject
*exc
= PyObject_CallFunction(PyExc_IOError
, "(is)",
137 PyErr_SetObject(PyExc_IOError
, exc
);
147 fill_file_fields(PyFileObject
*f
, FILE *fp
, PyObject
*name
, char *mode
,
148 int (*close
)(FILE *))
150 assert(name
!= NULL
);
152 assert(PyFile_Check(f
));
153 assert(f
->f_fp
== NULL
);
155 Py_DECREF(f
->f_name
);
156 Py_DECREF(f
->f_mode
);
157 Py_DECREF(f
->f_encoding
);
158 Py_DECREF(f
->f_errors
);
163 f
->f_mode
= PyString_FromString(mode
);
167 f
->f_binary
= strchr(mode
,'b') != NULL
;
169 f
->f_univ_newline
= (strchr(mode
, 'U') != NULL
);
170 f
->f_newlinetypes
= NEWLINE_UNKNOWN
;
173 f
->f_encoding
= Py_None
;
175 f
->f_errors
= Py_None
;
177 if (f
->f_mode
== NULL
)
181 return (PyObject
*) f
;
184 /* check for known incorrect mode strings - problem is, platforms are
185 free to accept any mode characters they like and are supposed to
186 ignore stuff they don't understand... write or append mode with
187 universal newline support is expressly forbidden by PEP 278.
188 Additionally, remove the 'U' from the mode string as platforms
189 won't know what it is. Non-zero return signals an exception */
191 _PyFile_SanitizeMode(char *mode
)
194 size_t len
= strlen(mode
);
197 PyErr_SetString(PyExc_ValueError
, "empty mode string");
201 upos
= strchr(mode
, 'U');
203 memmove(upos
, upos
+1, len
-(upos
-mode
)); /* incl null char */
205 if (mode
[0] == 'w' || mode
[0] == 'a') {
206 PyErr_Format(PyExc_ValueError
, "universal newline "
207 "mode can only be used with modes "
208 "starting with 'r'");
212 if (mode
[0] != 'r') {
213 memmove(mode
+1, mode
, strlen(mode
)+1);
217 if (!strchr(mode
, 'b')) {
218 memmove(mode
+2, mode
+1, strlen(mode
));
221 } else if (mode
[0] != 'r' && mode
[0] != 'w' && mode
[0] != 'a') {
222 PyErr_Format(PyExc_ValueError
, "mode string must begin with "
223 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode
);
231 open_the_file(PyFileObject
*f
, char *name
, char *mode
)
235 assert(PyFile_Check(f
));
237 /* windows ignores the passed name in order to support Unicode */
238 assert(f
->f_name
!= NULL
);
240 assert(name
!= NULL
);
242 assert(mode
!= NULL
);
243 assert(f
->f_fp
== NULL
);
245 /* probably need to replace 'U' by 'rb' */
246 newmode
= PyMem_MALLOC(strlen(mode
) + 3);
251 strcpy(newmode
, mode
);
253 if (_PyFile_SanitizeMode(newmode
)) {
258 /* rexec.py can't stop a user from getting the file() constructor --
259 all they have to do is get *any* file object f, and then do
260 type(f). Here we prevent them from doing damage with it. */
261 if (PyEval_GetRestricted()) {
262 PyErr_SetString(PyExc_IOError
,
263 "file() constructor not accessible in restricted mode");
270 if (PyUnicode_Check(f
->f_name
)) {
272 wmode
= PyUnicode_DecodeASCII(newmode
, strlen(newmode
), NULL
);
273 if (f
->f_name
&& wmode
) {
274 FILE_BEGIN_ALLOW_THREADS(f
)
275 /* PyUnicode_AS_UNICODE OK without thread
276 lock as it is a simple dereference. */
277 f
->f_fp
= _wfopen(PyUnicode_AS_UNICODE(f
->f_name
),
278 PyUnicode_AS_UNICODE(wmode
));
279 FILE_END_ALLOW_THREADS(f
)
284 if (NULL
== f
->f_fp
&& NULL
!= name
) {
285 FILE_BEGIN_ALLOW_THREADS(f
)
286 f
->f_fp
= fopen(name
, newmode
);
287 FILE_END_ALLOW_THREADS(f
)
290 if (f
->f_fp
== NULL
) {
291 #if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
292 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
293 * across all Windows flavors. When it sets EINVAL varies
294 * across Windows flavors, the exact conditions aren't
295 * documented, and the answer lies in the OS's implementation
296 * of Win32's CreateFile function (whose source is secret).
297 * Seems the best we can do is map EINVAL to ENOENT.
298 * Starting with Visual Studio .NET 2005, EINVAL is correctly
299 * set by our CRT error handler (set in exceptions.c.)
301 if (errno
== 0) /* bad mode string */
303 else if (errno
== EINVAL
) /* unknown, but not a mode string */
306 /* EINVAL is returned when an invalid filename or
307 * an invalid mode is supplied. */
309 PyErr_Format(PyExc_IOError
,
310 "invalid filename: %s or mode: %s",
313 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError
, f
->f_name
);
322 return (PyObject
*)f
;
326 close_the_file(PyFileObject
*f
)
329 int (*local_close
)(FILE *);
330 FILE *local_fp
= f
->f_fp
;
331 if (local_fp
!= NULL
) {
332 local_close
= f
->f_close
;
333 if (local_close
!= NULL
&& f
->unlocked_count
> 0) {
334 if (f
->ob_refcnt
> 0) {
335 PyErr_SetString(PyExc_IOError
,
336 "close() called during concurrent "
337 "operation on the same file object.");
339 /* This should not happen unless someone is
340 * carelessly playing with the PyFileObject
341 * struct fields and/or its associated FILE
343 PyErr_SetString(PyExc_SystemError
,
344 "PyFileObject locking error in "
345 "destructor (refcnt <= 0 at close).");
349 /* NULL out the FILE pointer before releasing the GIL, because
350 * it will not be valid anymore after the close() function is
353 if (local_close
!= NULL
) {
354 Py_BEGIN_ALLOW_THREADS
356 sts
= (*local_close
)(local_fp
);
359 return PyErr_SetFromErrno(PyExc_IOError
);
361 return PyInt_FromLong((long)sts
);
368 PyFile_FromFile(FILE *fp
, char *name
, char *mode
, int (*close
)(FILE *))
370 PyFileObject
*f
= (PyFileObject
*)PyFile_Type
.tp_new(&PyFile_Type
,
373 PyObject
*o_name
= PyString_FromString(name
);
376 if (fill_file_fields(f
, fp
, o_name
, mode
, close
) == NULL
) {
382 return (PyObject
*) f
;
386 PyFile_FromString(char *name
, char *mode
)
388 extern int fclose(FILE *);
391 f
= (PyFileObject
*)PyFile_FromFile((FILE *)NULL
, name
, mode
, fclose
);
393 if (open_the_file(f
, name
, mode
) == NULL
) {
398 return (PyObject
*)f
;
402 PyFile_SetBufSize(PyObject
*f
, int bufsize
)
404 PyFileObject
*file
= (PyFileObject
*)f
;
425 if (type
== _IONBF
) {
426 PyMem_Free(file
->f_setbuf
);
427 file
->f_setbuf
= NULL
;
429 file
->f_setbuf
= (char *)PyMem_Realloc(file
->f_setbuf
,
433 setvbuf(file
->f_fp
, file
->f_setbuf
, type
, bufsize
);
434 #else /* !HAVE_SETVBUF */
435 setbuf(file
->f_fp
, file
->f_setbuf
);
436 #endif /* !HAVE_SETVBUF */
440 /* Set the encoding used to output Unicode strings.
441 Return 1 on success, 0 on failure. */
444 PyFile_SetEncoding(PyObject
*f
, const char *enc
)
446 return PyFile_SetEncodingAndErrors(f
, enc
, NULL
);
450 PyFile_SetEncodingAndErrors(PyObject
*f
, const char *enc
, char* errors
)
452 PyFileObject
*file
= (PyFileObject
*)f
;
453 PyObject
*str
, *oerrors
;
455 assert(PyFile_Check(f
));
456 str
= PyString_FromString(enc
);
460 oerrors
= PyString_FromString(errors
);
469 Py_DECREF(file
->f_encoding
);
470 file
->f_encoding
= str
;
471 Py_DECREF(file
->f_errors
);
472 file
->f_errors
= oerrors
;
479 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file");
483 /* Refuse regular file I/O if there's data in the iteration-buffer.
484 * Mixing them would cause data to arrive out of order, as the read*
485 * methods don't use the iteration buffer. */
487 err_iterbuffered(void)
489 PyErr_SetString(PyExc_ValueError
,
490 "Mixing iteration and read methods would lose data");
494 static void drop_readahead(PyFileObject
*);
499 file_dealloc(PyFileObject
*f
)
502 if (f
->weakreflist
!= NULL
)
503 PyObject_ClearWeakRefs((PyObject
*) f
);
504 ret
= close_the_file(f
);
506 PySys_WriteStderr("close failed in file object destructor:\n");
512 PyMem_Free(f
->f_setbuf
);
513 Py_XDECREF(f
->f_name
);
514 Py_XDECREF(f
->f_mode
);
515 Py_XDECREF(f
->f_encoding
);
516 Py_XDECREF(f
->f_errors
);
518 Py_TYPE(f
)->tp_free((PyObject
*)f
);
522 file_repr(PyFileObject
*f
)
524 if (PyUnicode_Check(f
->f_name
)) {
525 #ifdef Py_USING_UNICODE
526 PyObject
*ret
= NULL
;
527 PyObject
*name
= PyUnicode_AsUnicodeEscapeString(f
->f_name
);
528 const char *name_str
= name
? PyString_AsString(name
) : "?";
529 ret
= PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
530 f
->f_fp
== NULL
? "closed" : "open",
532 PyString_AsString(f
->f_mode
),
538 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
539 f
->f_fp
== NULL
? "closed" : "open",
540 PyString_AsString(f
->f_name
),
541 PyString_AsString(f
->f_mode
),
547 file_close(PyFileObject
*f
)
549 PyObject
*sts
= close_the_file(f
);
550 PyMem_Free(f
->f_setbuf
);
556 /* Our very own off_t-like type, 64-bit if possible */
557 #if !defined(HAVE_LARGEFILE_SUPPORT)
558 typedef off_t Py_off_t
;
559 #elif SIZEOF_OFF_T >= 8
560 typedef off_t Py_off_t
;
561 #elif SIZEOF_FPOS_T >= 8
562 typedef fpos_t Py_off_t
;
564 #error "Large file support, but neither off_t nor fpos_t is large enough."
568 /* a portable fseek() function
569 return 0 on success, non-zero on failure (with errno set) */
571 _portable_fseek(FILE *fp
, Py_off_t offset
, int whence
)
573 #if !defined(HAVE_LARGEFILE_SUPPORT)
574 return fseek(fp
, offset
, whence
);
575 #elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
576 return fseeko(fp
, offset
, whence
);
577 #elif defined(HAVE_FSEEK64)
578 return fseek64(fp
, offset
, whence
);
579 #elif defined(__BEOS__)
580 return _fseek(fp
, offset
, whence
);
581 #elif SIZEOF_FPOS_T >= 8
582 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
583 and fgetpos() to implement fseek()*/
589 if (_lseeki64(fileno(fp
), 0, 2) == -1)
592 if (fseek(fp
, 0, SEEK_END
) != 0)
597 if (fgetpos(fp
, &pos
) != 0)
601 /* case SEEK_SET: break; */
603 return fsetpos(fp
, &offset
);
605 #error "Large file support, but no way to fseek."
610 /* a portable ftell() function
611 Return -1 on failure with errno set appropriately, current file
612 position on success */
614 _portable_ftell(FILE* fp
)
616 #if !defined(HAVE_LARGEFILE_SUPPORT)
618 #elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
620 #elif defined(HAVE_FTELL64)
622 #elif SIZEOF_FPOS_T >= 8
624 if (fgetpos(fp
, &pos
) != 0)
628 #error "Large file support, but no way to ftell."
634 file_seek(PyFileObject
*f
, PyObject
*args
)
639 PyObject
*offobj
, *off_index
;
645 if (!PyArg_ParseTuple(args
, "O|i:seek", &offobj
, &whence
))
647 off_index
= PyNumber_Index(offobj
);
649 if (!PyFloat_Check(offobj
))
651 /* Deprecated in 2.6 */
653 if (PyErr_WarnEx(PyExc_DeprecationWarning
,
654 "integer argument expected, got float",
660 #if !defined(HAVE_LARGEFILE_SUPPORT)
661 offset
= PyInt_AsLong(off_index
);
663 offset
= PyLong_Check(off_index
) ?
664 PyLong_AsLongLong(off_index
) : PyInt_AsLong(off_index
);
666 Py_DECREF(off_index
);
667 if (PyErr_Occurred())
670 FILE_BEGIN_ALLOW_THREADS(f
)
672 ret
= _portable_fseek(f
->f_fp
, offset
, whence
);
673 FILE_END_ALLOW_THREADS(f
)
676 PyErr_SetFromErrno(PyExc_IOError
);
686 #ifdef HAVE_FTRUNCATE
688 file_truncate(PyFileObject
*f
, PyObject
*args
)
691 PyObject
*newsizeobj
= NULL
;
697 if (!PyArg_UnpackTuple(args
, "truncate", 0, 1, &newsizeobj
))
700 /* Get current file position. If the file happens to be open for
701 * update and the last operation was an input operation, C doesn't
702 * define what the later fflush() will do, but we promise truncate()
703 * won't change the current position (and fflush() *does* change it
704 * then at least on Windows). The easiest thing is to capture
705 * current pos now and seek back to it at the end.
707 FILE_BEGIN_ALLOW_THREADS(f
)
709 initialpos
= _portable_ftell(f
->f_fp
);
710 FILE_END_ALLOW_THREADS(f
)
711 if (initialpos
== -1)
714 /* Set newsize to current postion if newsizeobj NULL, else to the
717 if (newsizeobj
!= NULL
) {
718 #if !defined(HAVE_LARGEFILE_SUPPORT)
719 newsize
= PyInt_AsLong(newsizeobj
);
721 newsize
= PyLong_Check(newsizeobj
) ?
722 PyLong_AsLongLong(newsizeobj
) :
723 PyInt_AsLong(newsizeobj
);
725 if (PyErr_Occurred())
728 else /* default to current position */
729 newsize
= initialpos
;
731 /* Flush the stream. We're mixing stream-level I/O with lower-level
732 * I/O, and a flush may be necessary to synch both platform views
733 * of the current file state.
735 FILE_BEGIN_ALLOW_THREADS(f
)
737 ret
= fflush(f
->f_fp
);
738 FILE_END_ALLOW_THREADS(f
)
743 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
744 so don't even try using it. */
748 /* Have to move current pos to desired endpoint on Windows. */
749 FILE_BEGIN_ALLOW_THREADS(f
)
751 ret
= _portable_fseek(f
->f_fp
, newsize
, SEEK_SET
) != 0;
752 FILE_END_ALLOW_THREADS(f
)
756 /* Truncate. Note that this may grow the file! */
757 FILE_BEGIN_ALLOW_THREADS(f
)
759 hFile
= (HANDLE
)_get_osfhandle(fileno(f
->f_fp
));
760 ret
= hFile
== (HANDLE
)-1;
762 ret
= SetEndOfFile(hFile
) == 0;
766 FILE_END_ALLOW_THREADS(f
)
771 FILE_BEGIN_ALLOW_THREADS(f
)
773 ret
= ftruncate(fileno(f
->f_fp
), newsize
);
774 FILE_END_ALLOW_THREADS(f
)
777 #endif /* !MS_WINDOWS */
779 /* Restore original file position. */
780 FILE_BEGIN_ALLOW_THREADS(f
)
782 ret
= _portable_fseek(f
->f_fp
, initialpos
, SEEK_SET
) != 0;
783 FILE_END_ALLOW_THREADS(f
)
791 PyErr_SetFromErrno(PyExc_IOError
);
795 #endif /* HAVE_FTRUNCATE */
798 file_tell(PyFileObject
*f
)
804 FILE_BEGIN_ALLOW_THREADS(f
)
806 pos
= _portable_ftell(f
->f_fp
);
807 FILE_END_ALLOW_THREADS(f
)
810 PyErr_SetFromErrno(PyExc_IOError
);
814 if (f
->f_skipnextlf
) {
818 f
->f_newlinetypes
|= NEWLINE_CRLF
;
821 } else if (c
!= EOF
) ungetc(c
, f
->f_fp
);
823 #if !defined(HAVE_LARGEFILE_SUPPORT)
824 return PyInt_FromLong(pos
);
826 return PyLong_FromLongLong(pos
);
831 file_fileno(PyFileObject
*f
)
835 return PyInt_FromLong((long) fileno(f
->f_fp
));
839 file_flush(PyFileObject
*f
)
845 FILE_BEGIN_ALLOW_THREADS(f
)
847 res
= fflush(f
->f_fp
);
848 FILE_END_ALLOW_THREADS(f
)
850 PyErr_SetFromErrno(PyExc_IOError
);
859 file_isatty(PyFileObject
*f
)
864 FILE_BEGIN_ALLOW_THREADS(f
)
865 res
= isatty((int)fileno(f
->f_fp
));
866 FILE_END_ALLOW_THREADS(f
)
867 return PyBool_FromLong(res
);
872 #define SMALLCHUNK 8192
874 #define SMALLCHUNK BUFSIZ
878 #define BIGCHUNK (512 * 32)
880 #define BIGCHUNK (512 * 1024)
884 new_buffersize(PyFileObject
*f
, size_t currentsize
)
889 if (fstat(fileno(f
->f_fp
), &st
) == 0) {
891 /* The following is not a bug: we really need to call lseek()
892 *and* ftell(). The reason is that some stdio libraries
893 mistakenly flush their buffer when ftell() is called and
894 the lseek() call it makes fails, thereby throwing away
895 data that cannot be recovered in any way. To avoid this,
896 we first test lseek(), and only call ftell() if lseek()
897 works. We can't use the lseek() value either, because we
898 need to take the amount of buffered data into account.
899 (Yet another reason why stdio stinks. :-) */
900 pos
= lseek(fileno(f
->f_fp
), 0L, SEEK_CUR
);
902 pos
= ftell(f
->f_fp
);
906 if (end
> pos
&& pos
>= 0)
907 return currentsize
+ end
- pos
+ 1;
908 /* Add 1 so if the file were to grow we'd notice. */
911 if (currentsize
> SMALLCHUNK
) {
912 /* Keep doubling until we reach BIGCHUNK;
913 then keep adding BIGCHUNK. */
914 if (currentsize
<= BIGCHUNK
)
915 return currentsize
+ currentsize
;
917 return currentsize
+ BIGCHUNK
;
919 return currentsize
+ SMALLCHUNK
;
922 #if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
923 #define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
926 #define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
929 #define BLOCKED_ERRNO(x) ((x) == EAGAIN)
931 #define BLOCKED_ERRNO(x) 0
937 file_read(PyFileObject
*f
, PyObject
*args
)
939 long bytesrequested
= -1;
940 size_t bytesread
, buffersize
, chunksize
;
945 /* refuse to mix with f.next() */
946 if (f
->f_buf
!= NULL
&&
947 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
949 return err_iterbuffered();
950 if (!PyArg_ParseTuple(args
, "|l:read", &bytesrequested
))
952 if (bytesrequested
< 0)
953 buffersize
= new_buffersize(f
, (size_t)0);
955 buffersize
= bytesrequested
;
956 if (buffersize
> PY_SSIZE_T_MAX
) {
957 PyErr_SetString(PyExc_OverflowError
,
958 "requested number of bytes is more than a Python string can hold");
961 v
= PyString_FromStringAndSize((char *)NULL
, buffersize
);
966 FILE_BEGIN_ALLOW_THREADS(f
)
968 chunksize
= Py_UniversalNewlineFread(BUF(v
) + bytesread
,
969 buffersize
- bytesread
, f
->f_fp
, (PyObject
*)f
);
970 FILE_END_ALLOW_THREADS(f
)
971 if (chunksize
== 0) {
972 if (!ferror(f
->f_fp
))
975 /* When in non-blocking mode, data shouldn't
976 * be discarded if a blocking signal was
977 * received. That will also happen if
978 * chunksize != 0, but bytesread < buffersize. */
979 if (bytesread
> 0 && BLOCKED_ERRNO(errno
))
981 PyErr_SetFromErrno(PyExc_IOError
);
985 bytesread
+= chunksize
;
986 if (bytesread
< buffersize
) {
990 if (bytesrequested
< 0) {
991 buffersize
= new_buffersize(f
, buffersize
);
992 if (_PyString_Resize(&v
, buffersize
) < 0)
995 /* Got what was requested. */
999 if (bytesread
!= buffersize
)
1000 _PyString_Resize(&v
, bytesread
);
1005 file_readinto(PyFileObject
*f
, PyObject
*args
)
1009 Py_ssize_t ndone
, nnow
;
1011 if (f
->f_fp
== NULL
)
1012 return err_closed();
1013 /* refuse to mix with f.next() */
1014 if (f
->f_buf
!= NULL
&&
1015 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
1016 f
->f_buf
[0] != '\0')
1017 return err_iterbuffered();
1018 if (!PyArg_ParseTuple(args
, "w#", &ptr
, &ntodo
))
1022 FILE_BEGIN_ALLOW_THREADS(f
)
1024 nnow
= Py_UniversalNewlineFread(ptr
+ndone
, ntodo
, f
->f_fp
,
1026 FILE_END_ALLOW_THREADS(f
)
1028 if (!ferror(f
->f_fp
))
1030 PyErr_SetFromErrno(PyExc_IOError
);
1037 return PyInt_FromSsize_t(ndone
);
1040 /**************************************************************************
1041 Routine to get next line using platform fgets().
1045 + MS threadsafe getc is very slow (multiple layers of function calls before+
1046 after each character, to lock+unlock the stream).
1047 + The stream-locking functions are MS-internal -- can't access them from user
1049 + There's nothing Tim could find in the MS C or platform SDK libraries that
1050 can worm around this.
1051 + MS fgets locks/unlocks only once per line; it's the only hook we have.
1053 So we use fgets for speed(!), despite that it's painful.
1055 MS realloc is also slow.
1057 Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1061 Tru64 Unix getline_via_fgets significantly faster
1063 CAUTION: The C std isn't clear about this: in those cases where fgets
1064 writes something into the buffer, can it write into any position beyond the
1065 required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1066 known on which it does; and it would be a strange way to code fgets. Still,
1067 getline_via_fgets may not work correctly if it does. The std test
1068 test_bufio.py should fail if platform fgets() routinely writes beyond the
1069 trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
1070 **************************************************************************/
1072 /* Use this routine if told to, or by default on non-get_unlocked()
1073 * platforms unless told not to. Yikes! Let's spell that out:
1074 * On a platform with getc_unlocked():
1075 * By default, use getc_unlocked().
1076 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1077 * On a platform without getc_unlocked():
1078 * By default, use fgets().
1079 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1081 #if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1082 #define USE_FGETS_IN_GETLINE
1085 #if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1086 #undef USE_FGETS_IN_GETLINE
1089 #ifdef USE_FGETS_IN_GETLINE
1091 getline_via_fgets(PyFileObject
*f
, FILE *fp
)
1093 /* INITBUFSIZE is the maximum line length that lets us get away with the fast
1094 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1095 * to fill this much of the buffer with a known value in order to figure out
1096 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1097 * than "most" lines, we waste time filling unused buffer slots. 100 is
1098 * surely adequate for most peoples' email archives, chewing over source code,
1099 * etc -- "regular old text files".
1100 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1101 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1102 * cautions about boosting that. 300 was chosen because the worst real-life
1103 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1104 * half the lines were 254 chars.
1106 #define INITBUFSIZE 100
1107 #define MAXBUFSIZE 300
1109 char buf
[MAXBUFSIZE
];
1110 PyObject
* v
; /* the string object result */
1111 char* pvfree
; /* address of next free slot */
1112 char* pvend
; /* address one beyond last free slot */
1113 size_t nfree
; /* # of free buffer slots; pvend-pvfree */
1114 size_t total_v_size
; /* total # of slots in buffer */
1115 size_t increment
; /* amount to increment the buffer */
1118 /* Optimize for normal case: avoid _PyString_Resize if at all
1119 * possible via first reading into stack buffer "buf".
1121 total_v_size
= INITBUFSIZE
; /* start small and pray */
1124 FILE_BEGIN_ALLOW_THREADS(f
)
1125 pvend
= buf
+ total_v_size
;
1126 nfree
= pvend
- pvfree
;
1127 memset(pvfree
, '\n', nfree
);
1128 assert(nfree
< INT_MAX
); /* Should be atmost MAXBUFSIZE */
1129 p
= fgets(pvfree
, (int)nfree
, fp
);
1130 FILE_END_ALLOW_THREADS(f
)
1134 if (PyErr_CheckSignals())
1136 v
= PyString_FromStringAndSize(buf
, pvfree
- buf
);
1139 /* fgets read *something* */
1140 p
= memchr(pvfree
, '\n', nfree
);
1142 /* Did the \n come from fgets or from us?
1143 * Since fgets stops at the first \n, and then writes
1144 * \0, if it's from fgets a \0 must be next. But if
1145 * that's so, it could not have come from us, since
1146 * the \n's we filled the buffer with have only more
1147 * \n's to the right.
1149 if (p
+1 < pvend
&& *(p
+1) == '\0') {
1150 /* It's from fgets: we win! In particular,
1151 * we haven't done any mallocs yet, and can
1152 * build the final result on the first try.
1154 ++p
; /* include \n from fgets */
1157 /* Must be from us: fgets didn't fill the
1158 * buffer and didn't find a newline, so it
1159 * must be the last and newline-free line of
1162 assert(p
> pvfree
&& *(p
-1) == '\0');
1163 --p
; /* don't include \0 from fgets */
1165 v
= PyString_FromStringAndSize(buf
, p
- buf
);
1168 /* yuck: fgets overwrote all the newlines, i.e. the entire
1169 * buffer. So this line isn't over yet, or maybe it is but
1170 * we're exactly at EOF. If we haven't already, try using the
1171 * rest of the stack buffer.
1173 assert(*(pvend
-1) == '\0');
1174 if (pvfree
== buf
) {
1175 pvfree
= pvend
- 1; /* overwrite trailing null */
1176 total_v_size
= MAXBUFSIZE
;
1182 /* The stack buffer isn't big enough; malloc a string object and read
1185 total_v_size
= MAXBUFSIZE
<< 1;
1186 v
= PyString_FromStringAndSize((char*)NULL
, (int)total_v_size
);
1189 /* copy over everything except the last null byte */
1190 memcpy(BUF(v
), buf
, MAXBUFSIZE
-1);
1191 pvfree
= BUF(v
) + MAXBUFSIZE
- 1;
1193 /* Keep reading stuff into v; if it ever ends successfully, break
1194 * after setting p one beyond the end of the line. The code here is
1195 * very much like the code above, except reads into v's buffer; see
1196 * the code above for detailed comments about the logic.
1199 FILE_BEGIN_ALLOW_THREADS(f
)
1200 pvend
= BUF(v
) + total_v_size
;
1201 nfree
= pvend
- pvfree
;
1202 memset(pvfree
, '\n', nfree
);
1203 assert(nfree
< INT_MAX
);
1204 p
= fgets(pvfree
, (int)nfree
, fp
);
1205 FILE_END_ALLOW_THREADS(f
)
1209 if (PyErr_CheckSignals()) {
1216 p
= memchr(pvfree
, '\n', nfree
);
1218 if (p
+1 < pvend
&& *(p
+1) == '\0') {
1219 /* \n came from fgets */
1223 /* \n came from us; last line of file, no newline */
1224 assert(p
> pvfree
&& *(p
-1) == '\0');
1228 /* expand buffer and try again */
1229 assert(*(pvend
-1) == '\0');
1230 increment
= total_v_size
>> 2; /* mild exponential growth */
1231 prev_v_size
= total_v_size
;
1232 total_v_size
+= increment
;
1233 /* check for overflow */
1234 if (total_v_size
<= prev_v_size
||
1235 total_v_size
> PY_SSIZE_T_MAX
) {
1236 PyErr_SetString(PyExc_OverflowError
,
1237 "line is longer than a Python string can hold");
1241 if (_PyString_Resize(&v
, (int)total_v_size
) < 0)
1243 /* overwrite the trailing null byte */
1244 pvfree
= BUF(v
) + (prev_v_size
- 1);
1246 if (BUF(v
) + total_v_size
!= p
)
1247 _PyString_Resize(&v
, p
- BUF(v
));
1252 #endif /* ifdef USE_FGETS_IN_GETLINE */
1254 /* Internal routine to get a line.
1255 Size argument interpretation:
1257 <= 0: read arbitrary line
1261 get_line(PyFileObject
*f
, int n
)
1266 size_t total_v_size
; /* total # of slots in buffer */
1267 size_t used_v_size
; /* # used slots in buffer */
1268 size_t increment
; /* amount to increment the buffer */
1270 int newlinetypes
= f
->f_newlinetypes
;
1271 int skipnextlf
= f
->f_skipnextlf
;
1272 int univ_newline
= f
->f_univ_newline
;
1274 #if defined(USE_FGETS_IN_GETLINE)
1275 if (n
<= 0 && !univ_newline
)
1276 return getline_via_fgets(f
, fp
);
1278 total_v_size
= n
> 0 ? n
: 100;
1279 v
= PyString_FromStringAndSize((char *)NULL
, total_v_size
);
1283 end
= buf
+ total_v_size
;
1286 FILE_BEGIN_ALLOW_THREADS(f
)
1289 c
= 'x'; /* Shut up gcc warning */
1290 while ( buf
!= end
&& (c
= GETC(fp
)) != EOF
) {
1294 /* Seeing a \n here with
1295 * skipnextlf true means we
1298 newlinetypes
|= NEWLINE_CRLF
;
1300 if (c
== EOF
) break;
1302 newlinetypes
|= NEWLINE_CR
;
1308 } else if ( c
== '\n')
1309 newlinetypes
|= NEWLINE_LF
;
1311 if (c
== '\n') break;
1313 if ( c
== EOF
&& skipnextlf
)
1314 newlinetypes
|= NEWLINE_CR
;
1315 } else /* If not universal newlines use the normal loop */
1316 while ((c
= GETC(fp
)) != EOF
&&
1317 (*buf
++ = c
) != '\n' &&
1321 FILE_END_ALLOW_THREADS(f
)
1322 f
->f_newlinetypes
= newlinetypes
;
1323 f
->f_skipnextlf
= skipnextlf
;
1328 PyErr_SetFromErrno(PyExc_IOError
);
1334 if (PyErr_CheckSignals()) {
1340 /* Must be because buf == end */
1343 used_v_size
= total_v_size
;
1344 increment
= total_v_size
>> 2; /* mild exponential growth */
1345 total_v_size
+= increment
;
1346 if (total_v_size
> PY_SSIZE_T_MAX
) {
1347 PyErr_SetString(PyExc_OverflowError
,
1348 "line is longer than a Python string can hold");
1352 if (_PyString_Resize(&v
, total_v_size
) < 0)
1354 buf
= BUF(v
) + used_v_size
;
1355 end
= BUF(v
) + total_v_size
;
1358 used_v_size
= buf
- BUF(v
);
1359 if (used_v_size
!= total_v_size
)
1360 _PyString_Resize(&v
, used_v_size
);
1364 /* External C interface */
1367 PyFile_GetLine(PyObject
*f
, int n
)
1372 PyErr_BadInternalCall();
1376 if (PyFile_Check(f
)) {
1377 PyFileObject
*fo
= (PyFileObject
*)f
;
1378 if (fo
->f_fp
== NULL
)
1379 return err_closed();
1380 /* refuse to mix with f.next() */
1381 if (fo
->f_buf
!= NULL
&&
1382 (fo
->f_bufend
- fo
->f_bufptr
) > 0 &&
1383 fo
->f_buf
[0] != '\0')
1384 return err_iterbuffered();
1385 result
= get_line(fo
, n
);
1391 reader
= PyObject_GetAttrString(f
, "readline");
1395 args
= PyTuple_New(0);
1397 args
= Py_BuildValue("(i)", n
);
1402 result
= PyEval_CallObject(reader
, args
);
1405 if (result
!= NULL
&& !PyString_Check(result
) &&
1406 !PyUnicode_Check(result
)) {
1409 PyErr_SetString(PyExc_TypeError
,
1410 "object.readline() returned non-string");
1414 if (n
< 0 && result
!= NULL
&& PyString_Check(result
)) {
1415 char *s
= PyString_AS_STRING(result
);
1416 Py_ssize_t len
= PyString_GET_SIZE(result
);
1420 PyErr_SetString(PyExc_EOFError
,
1421 "EOF when reading a line");
1423 else if (s
[len
-1] == '\n') {
1424 if (result
->ob_refcnt
== 1)
1425 _PyString_Resize(&result
, len
-1);
1428 v
= PyString_FromStringAndSize(s
, len
-1);
1434 #ifdef Py_USING_UNICODE
1435 if (n
< 0 && result
!= NULL
&& PyUnicode_Check(result
)) {
1436 Py_UNICODE
*s
= PyUnicode_AS_UNICODE(result
);
1437 Py_ssize_t len
= PyUnicode_GET_SIZE(result
);
1441 PyErr_SetString(PyExc_EOFError
,
1442 "EOF when reading a line");
1444 else if (s
[len
-1] == '\n') {
1445 if (result
->ob_refcnt
== 1)
1446 PyUnicode_Resize(&result
, len
-1);
1449 v
= PyUnicode_FromUnicode(s
, len
-1);
1462 file_readline(PyFileObject
*f
, PyObject
*args
)
1466 if (f
->f_fp
== NULL
)
1467 return err_closed();
1468 /* refuse to mix with f.next() */
1469 if (f
->f_buf
!= NULL
&&
1470 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
1471 f
->f_buf
[0] != '\0')
1472 return err_iterbuffered();
1473 if (!PyArg_ParseTuple(args
, "|i:readline", &n
))
1476 return PyString_FromString("");
1479 return get_line(f
, n
);
1483 file_readlines(PyFileObject
*f
, PyObject
*args
)
1486 PyObject
*list
= NULL
;
1488 char small_buffer
[SMALLCHUNK
];
1489 char *buffer
= small_buffer
;
1490 size_t buffersize
= SMALLCHUNK
;
1491 PyObject
*big_buffer
= NULL
;
1494 size_t totalread
= 0;
1499 if (f
->f_fp
== NULL
)
1500 return err_closed();
1501 /* refuse to mix with f.next() */
1502 if (f
->f_buf
!= NULL
&&
1503 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
1504 f
->f_buf
[0] != '\0')
1505 return err_iterbuffered();
1506 if (!PyArg_ParseTuple(args
, "|l:readlines", &sizehint
))
1508 if ((list
= PyList_New(0)) == NULL
)
1514 FILE_BEGIN_ALLOW_THREADS(f
)
1516 nread
= Py_UniversalNewlineFread(buffer
+nfilled
,
1517 buffersize
-nfilled
, f
->f_fp
, (PyObject
*)f
);
1518 FILE_END_ALLOW_THREADS(f
)
1519 shortread
= (nread
< buffersize
-nfilled
);
1523 if (!ferror(f
->f_fp
))
1525 PyErr_SetFromErrno(PyExc_IOError
);
1530 p
= (char *)memchr(buffer
+nfilled
, '\n', nread
);
1532 /* Need a larger buffer to fit this line */
1535 if (buffersize
> PY_SSIZE_T_MAX
) {
1536 PyErr_SetString(PyExc_OverflowError
,
1537 "line is longer than a Python string can hold");
1540 if (big_buffer
== NULL
) {
1541 /* Create the big buffer */
1542 big_buffer
= PyString_FromStringAndSize(
1544 if (big_buffer
== NULL
)
1546 buffer
= PyString_AS_STRING(big_buffer
);
1547 memcpy(buffer
, small_buffer
, nfilled
);
1550 /* Grow the big buffer */
1551 if ( _PyString_Resize(&big_buffer
, buffersize
) < 0 )
1553 buffer
= PyString_AS_STRING(big_buffer
);
1557 end
= buffer
+nfilled
+nread
;
1560 /* Process complete lines */
1562 line
= PyString_FromStringAndSize(q
, p
-q
);
1565 err
= PyList_Append(list
, line
);
1570 p
= (char *)memchr(q
, '\n', end
-q
);
1571 } while (p
!= NULL
);
1572 /* Move the remaining incomplete line to the start */
1574 memmove(buffer
, q
, nfilled
);
1576 if (totalread
>= (size_t)sizehint
)
1580 /* Partial last line */
1581 line
= PyString_FromStringAndSize(buffer
, nfilled
);
1585 /* Need to complete the last line */
1586 PyObject
*rest
= get_line(f
, 0);
1591 PyString_Concat(&line
, rest
);
1596 err
= PyList_Append(list
, line
);
1603 Py_XDECREF(big_buffer
);
1612 file_write(PyFileObject
*f
, PyObject
*args
)
1616 if (f
->f_fp
== NULL
)
1617 return err_closed();
1618 if (!PyArg_ParseTuple(args
, f
->f_binary
? "s#" : "t#", &s
, &n
))
1621 FILE_BEGIN_ALLOW_THREADS(f
)
1623 n2
= fwrite(s
, 1, n
, f
->f_fp
);
1624 FILE_END_ALLOW_THREADS(f
)
1626 PyErr_SetFromErrno(PyExc_IOError
);
1635 file_writelines(PyFileObject
*f
, PyObject
*seq
)
1637 #define CHUNKSIZE 1000
1638 PyObject
*list
, *line
;
1639 PyObject
*it
; /* iter(seq) */
1642 Py_ssize_t i
, j
, nwritten
, len
;
1644 assert(seq
!= NULL
);
1645 if (f
->f_fp
== NULL
)
1646 return err_closed();
1650 islist
= PyList_Check(seq
);
1654 it
= PyObject_GetIter(seq
);
1656 PyErr_SetString(PyExc_TypeError
,
1657 "writelines() requires an iterable argument");
1660 /* From here on, fail by going to error, to reclaim "it". */
1661 list
= PyList_New(CHUNKSIZE
);
1666 /* Strategy: slurp CHUNKSIZE lines into a private list,
1667 checking that they are all strings, then write that list
1668 without holding the interpreter lock, then come back for more. */
1669 for (index
= 0; ; index
+= CHUNKSIZE
) {
1672 list
= PyList_GetSlice(seq
, index
, index
+CHUNKSIZE
);
1675 j
= PyList_GET_SIZE(list
);
1678 for (j
= 0; j
< CHUNKSIZE
; j
++) {
1679 line
= PyIter_Next(it
);
1681 if (PyErr_Occurred())
1685 PyList_SetItem(list
, j
, line
);
1691 /* Check that all entries are indeed strings. If not,
1692 apply the same rules as for file.write() and
1693 convert the results to strings. This is slow, but
1694 seems to be the only way since all conversion APIs
1695 could potentially execute Python code. */
1696 for (i
= 0; i
< j
; i
++) {
1697 PyObject
*v
= PyList_GET_ITEM(list
, i
);
1698 if (!PyString_Check(v
)) {
1700 if (((f
->f_binary
&&
1701 PyObject_AsReadBuffer(v
,
1702 (const void**)&buffer
,
1704 PyObject_AsCharBuffer(v
,
1707 PyErr_SetString(PyExc_TypeError
,
1708 "writelines() argument must be a sequence of strings");
1711 line
= PyString_FromStringAndSize(buffer
,
1716 PyList_SET_ITEM(list
, i
, line
);
1720 /* Since we are releasing the global lock, the
1721 following code may *not* execute Python code. */
1723 FILE_BEGIN_ALLOW_THREADS(f
)
1725 for (i
= 0; i
< j
; i
++) {
1726 line
= PyList_GET_ITEM(list
, i
);
1727 len
= PyString_GET_SIZE(line
);
1728 nwritten
= fwrite(PyString_AS_STRING(line
),
1730 if (nwritten
!= len
) {
1731 FILE_ABORT_ALLOW_THREADS(f
)
1732 PyErr_SetFromErrno(PyExc_IOError
);
1737 FILE_END_ALLOW_THREADS(f
)
1753 file_self(PyFileObject
*f
)
1755 if (f
->f_fp
== NULL
)
1756 return err_closed();
1758 return (PyObject
*)f
;
1762 file_xreadlines(PyFileObject
*f
)
1764 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1765 "try 'for line in f' instead", 1) < 0)
1767 return file_self(f
);
1771 file_exit(PyObject
*f
, PyObject
*args
)
1773 PyObject
*ret
= PyObject_CallMethod(f
, "close", NULL
);
1775 /* If error occurred, pass through */
1778 /* We cannot return the result of close since a true
1779 * value will be interpreted as "yes, swallow the
1780 * exception if one was raised inside the with block". */
1784 PyDoc_STRVAR(readline_doc
,
1785 "readline([size]) -> next line from the file, as a string.\n"
1787 "Retain newline. A non-negative size argument limits the maximum\n"
1788 "number of bytes to return (an incomplete line may be returned then).\n"
1789 "Return an empty string at EOF.");
1791 PyDoc_STRVAR(read_doc
,
1792 "read([size]) -> read at most size bytes, returned as a string.\n"
1794 "If the size argument is negative or omitted, read until EOF is reached.\n"
1795 "Notice that when in non-blocking mode, less data than what was requested\n"
1796 "may be returned, even if no size parameter was given.");
1798 PyDoc_STRVAR(write_doc
,
1799 "write(str) -> None. Write string str to file.\n"
1801 "Note that due to buffering, flush() or close() may be needed before\n"
1802 "the file on disk reflects the data written.");
1804 PyDoc_STRVAR(fileno_doc
,
1805 "fileno() -> integer \"file descriptor\".\n"
1807 "This is needed for lower-level file interfaces, such os.read().");
1809 PyDoc_STRVAR(seek_doc
,
1810 "seek(offset[, whence]) -> None. Move to new file position.\n"
1812 "Argument offset is a byte count. Optional argument whence defaults to\n"
1813 "0 (offset from start of file, offset should be >= 0); other values are 1\n"
1814 "(move relative to current position, positive or negative), and 2 (move\n"
1815 "relative to end of file, usually negative, although many platforms allow\n"
1816 "seeking beyond the end of a file). If the file is opened in text mode,\n"
1817 "only offsets returned by tell() are legal. Use of other offsets causes\n"
1818 "undefined behavior."
1820 "Note that not all file objects are seekable.");
1822 #ifdef HAVE_FTRUNCATE
1823 PyDoc_STRVAR(truncate_doc
,
1824 "truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1826 "Size defaults to the current file position, as returned by tell().");
1829 PyDoc_STRVAR(tell_doc
,
1830 "tell() -> current file position, an integer (may be a long integer).");
1832 PyDoc_STRVAR(readinto_doc
,
1833 "readinto() -> Undocumented. Don't use this; it may go away.");
1835 PyDoc_STRVAR(readlines_doc
,
1836 "readlines([size]) -> list of strings, each a line from the file.\n"
1838 "Call readline() repeatedly and return a list of the lines so read.\n"
1839 "The optional size argument, if given, is an approximate bound on the\n"
1840 "total number of bytes in the lines returned.");
1842 PyDoc_STRVAR(xreadlines_doc
,
1843 "xreadlines() -> returns self.\n"
1845 "For backward compatibility. File objects now include the performance\n"
1846 "optimizations previously implemented in the xreadlines module.");
1848 PyDoc_STRVAR(writelines_doc
,
1849 "writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
1851 "Note that newlines are not added. The sequence can be any iterable object\n"
1852 "producing strings. This is equivalent to calling write() for each string.");
1854 PyDoc_STRVAR(flush_doc
,
1855 "flush() -> None. Flush the internal I/O buffer.");
1857 PyDoc_STRVAR(close_doc
,
1858 "close() -> None or (perhaps) an integer. Close the file.\n"
1860 "Sets data attribute .closed to True. A closed file cannot be used for\n"
1861 "further I/O operations. close() may be called more than once without\n"
1862 "error. Some kinds of file objects (for example, opened by popen())\n"
1863 "may return an exit status upon closing.");
1865 PyDoc_STRVAR(isatty_doc
,
1866 "isatty() -> true or false. True if the file is connected to a tty device.");
1868 PyDoc_STRVAR(enter_doc
,
1869 "__enter__() -> self.");
1871 PyDoc_STRVAR(exit_doc
,
1872 "__exit__(*excinfo) -> None. Closes the file.");
1874 static PyMethodDef file_methods
[] = {
1875 {"readline", (PyCFunction
)file_readline
, METH_VARARGS
, readline_doc
},
1876 {"read", (PyCFunction
)file_read
, METH_VARARGS
, read_doc
},
1877 {"write", (PyCFunction
)file_write
, METH_VARARGS
, write_doc
},
1878 {"fileno", (PyCFunction
)file_fileno
, METH_NOARGS
, fileno_doc
},
1879 {"seek", (PyCFunction
)file_seek
, METH_VARARGS
, seek_doc
},
1880 #ifdef HAVE_FTRUNCATE
1881 {"truncate", (PyCFunction
)file_truncate
, METH_VARARGS
, truncate_doc
},
1883 {"tell", (PyCFunction
)file_tell
, METH_NOARGS
, tell_doc
},
1884 {"readinto", (PyCFunction
)file_readinto
, METH_VARARGS
, readinto_doc
},
1885 {"readlines", (PyCFunction
)file_readlines
, METH_VARARGS
, readlines_doc
},
1886 {"xreadlines",(PyCFunction
)file_xreadlines
, METH_NOARGS
, xreadlines_doc
},
1887 {"writelines",(PyCFunction
)file_writelines
, METH_O
, writelines_doc
},
1888 {"flush", (PyCFunction
)file_flush
, METH_NOARGS
, flush_doc
},
1889 {"close", (PyCFunction
)file_close
, METH_NOARGS
, close_doc
},
1890 {"isatty", (PyCFunction
)file_isatty
, METH_NOARGS
, isatty_doc
},
1891 {"__enter__", (PyCFunction
)file_self
, METH_NOARGS
, enter_doc
},
1892 {"__exit__", (PyCFunction
)file_exit
, METH_VARARGS
, exit_doc
},
1893 {NULL
, NULL
} /* sentinel */
1896 #define OFF(x) offsetof(PyFileObject, x)
1898 static PyMemberDef file_memberlist
[] = {
1899 {"mode", T_OBJECT
, OFF(f_mode
), RO
,
1900 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
1901 {"name", T_OBJECT
, OFF(f_name
), RO
,
1903 {"encoding", T_OBJECT
, OFF(f_encoding
), RO
,
1905 {"errors", T_OBJECT
, OFF(f_errors
), RO
,
1906 "Unicode error handler"},
1907 /* getattr(f, "closed") is implemented without this table */
1908 {NULL
} /* Sentinel */
1912 get_closed(PyFileObject
*f
, void *closure
)
1914 return PyBool_FromLong((long)(f
->f_fp
== 0));
1917 get_newlines(PyFileObject
*f
, void *closure
)
1919 switch (f
->f_newlinetypes
) {
1920 case NEWLINE_UNKNOWN
:
1924 return PyString_FromString("\r");
1926 return PyString_FromString("\n");
1927 case NEWLINE_CR
|NEWLINE_LF
:
1928 return Py_BuildValue("(ss)", "\r", "\n");
1930 return PyString_FromString("\r\n");
1931 case NEWLINE_CR
|NEWLINE_CRLF
:
1932 return Py_BuildValue("(ss)", "\r", "\r\n");
1933 case NEWLINE_LF
|NEWLINE_CRLF
:
1934 return Py_BuildValue("(ss)", "\n", "\r\n");
1935 case NEWLINE_CR
|NEWLINE_LF
|NEWLINE_CRLF
:
1936 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
1938 PyErr_Format(PyExc_SystemError
,
1939 "Unknown newlines value 0x%x\n",
1946 get_softspace(PyFileObject
*f
, void *closure
)
1948 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
1950 return PyInt_FromLong(f
->f_softspace
);
1954 set_softspace(PyFileObject
*f
, PyObject
*value
)
1957 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
1960 if (value
== NULL
) {
1961 PyErr_SetString(PyExc_TypeError
,
1962 "can't delete softspace attribute");
1966 new = PyInt_AsLong(value
);
1967 if (new == -1 && PyErr_Occurred())
1969 f
->f_softspace
= new;
1973 static PyGetSetDef file_getsetlist
[] = {
1974 {"closed", (getter
)get_closed
, NULL
, "True if the file is closed"},
1975 {"newlines", (getter
)get_newlines
, NULL
,
1976 "end-of-line convention used in this file"},
1977 {"softspace", (getter
)get_softspace
, (setter
)set_softspace
,
1978 "flag indicating that a space needs to be printed; used by print"},
1983 drop_readahead(PyFileObject
*f
)
1985 if (f
->f_buf
!= NULL
) {
1986 PyMem_Free(f
->f_buf
);
1991 /* Make sure that file has a readahead buffer with at least one byte
1992 (unless at EOF) and no more than bufsize. Returns negative value on
1993 error, will set MemoryError if bufsize bytes cannot be allocated. */
1995 readahead(PyFileObject
*f
, int bufsize
)
1997 Py_ssize_t chunksize
;
1999 if (f
->f_buf
!= NULL
) {
2000 if( (f
->f_bufend
- f
->f_bufptr
) >= 1)
2005 if ((f
->f_buf
= (char *)PyMem_Malloc(bufsize
)) == NULL
) {
2009 FILE_BEGIN_ALLOW_THREADS(f
)
2011 chunksize
= Py_UniversalNewlineFread(
2012 f
->f_buf
, bufsize
, f
->f_fp
, (PyObject
*)f
);
2013 FILE_END_ALLOW_THREADS(f
)
2014 if (chunksize
== 0) {
2015 if (ferror(f
->f_fp
)) {
2016 PyErr_SetFromErrno(PyExc_IOError
);
2022 f
->f_bufptr
= f
->f_buf
;
2023 f
->f_bufend
= f
->f_buf
+ chunksize
;
2027 /* Used by file_iternext. The returned string will start with 'skip'
2028 uninitialized bytes followed by the remainder of the line. Don't be
2029 horrified by the recursive call: maximum recursion depth is limited by
2030 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2032 static PyStringObject
*
2033 readahead_get_line_skip(PyFileObject
*f
, int skip
, int bufsize
)
2040 if (f
->f_buf
== NULL
)
2041 if (readahead(f
, bufsize
) < 0)
2044 len
= f
->f_bufend
- f
->f_bufptr
;
2046 return (PyStringObject
*)
2047 PyString_FromStringAndSize(NULL
, skip
);
2048 bufptr
= (char *)memchr(f
->f_bufptr
, '\n', len
);
2049 if (bufptr
!= NULL
) {
2050 bufptr
++; /* Count the '\n' */
2051 len
= bufptr
- f
->f_bufptr
;
2052 s
= (PyStringObject
*)
2053 PyString_FromStringAndSize(NULL
, skip
+len
);
2056 memcpy(PyString_AS_STRING(s
)+skip
, f
->f_bufptr
, len
);
2057 f
->f_bufptr
= bufptr
;
2058 if (bufptr
== f
->f_bufend
)
2061 bufptr
= f
->f_bufptr
;
2063 f
->f_buf
= NULL
; /* Force new readahead buffer */
2064 assert(skip
+len
< INT_MAX
);
2065 s
= readahead_get_line_skip(
2066 f
, (int)(skip
+len
), bufsize
+ (bufsize
>>2) );
2071 memcpy(PyString_AS_STRING(s
)+skip
, bufptr
, len
);
2077 /* A larger buffer size may actually decrease performance. */
2078 #define READAHEAD_BUFSIZE 8192
2081 file_iternext(PyFileObject
*f
)
2085 if (f
->f_fp
== NULL
)
2086 return err_closed();
2088 l
= readahead_get_line_skip(f
, 0, READAHEAD_BUFSIZE
);
2089 if (l
== NULL
|| PyString_GET_SIZE(l
) == 0) {
2093 return (PyObject
*)l
;
2098 file_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2101 static PyObject
*not_yet_string
;
2103 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
2105 if (not_yet_string
== NULL
) {
2106 not_yet_string
= PyString_InternFromString("<uninitialized file>");
2107 if (not_yet_string
== NULL
)
2111 self
= type
->tp_alloc(type
, 0);
2113 /* Always fill in the name and mode, so that nobody else
2114 needs to special-case NULLs there. */
2115 Py_INCREF(not_yet_string
);
2116 ((PyFileObject
*)self
)->f_name
= not_yet_string
;
2117 Py_INCREF(not_yet_string
);
2118 ((PyFileObject
*)self
)->f_mode
= not_yet_string
;
2120 ((PyFileObject
*)self
)->f_encoding
= Py_None
;
2122 ((PyFileObject
*)self
)->f_errors
= Py_None
;
2123 ((PyFileObject
*)self
)->weakreflist
= NULL
;
2124 ((PyFileObject
*)self
)->unlocked_count
= 0;
2130 file_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2132 PyFileObject
*foself
= (PyFileObject
*)self
;
2134 static char *kwlist
[] = {"name", "mode", "buffering", 0};
2138 int wideargument
= 0;
2140 assert(PyFile_Check(self
));
2141 if (foself
->f_fp
!= NULL
) {
2142 /* Have to close the existing file first. */
2143 PyObject
*closeresult
= file_close(foself
);
2144 if (closeresult
== NULL
)
2146 Py_DECREF(closeresult
);
2149 #ifdef Py_WIN_WIDE_FILENAMES
2150 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2152 if (PyArg_ParseTupleAndKeywords(args
, kwds
, "U|si:file",
2153 kwlist
, &po
, &mode
, &bufsize
)) {
2155 if (fill_file_fields(foself
, NULL
, po
, mode
,
2159 /* Drop the argument parsing error as narrow
2160 strings are also valid. */
2166 if (!wideargument
) {
2169 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "et|si:file", kwlist
,
2170 Py_FileSystemDefaultEncoding
,
2175 /* We parse again to get the name as a PyObject */
2176 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|si:file",
2177 kwlist
, &o_name
, &mode
,
2181 if (fill_file_fields(foself
, NULL
, o_name
, mode
,
2185 if (open_the_file(foself
, name
, mode
) == NULL
)
2187 foself
->f_setbuf
= NULL
;
2188 PyFile_SetBufSize(self
, bufsize
);
2195 PyMem_Free(name
); /* free the encoded string */
2199 PyDoc_VAR(file_doc
) =
2201 "file(name[, mode[, buffering]]) -> file object\n"
2203 "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2204 "writing or appending. The file will be created if it doesn't exist\n"
2205 "when opened for writing or appending; it will be truncated when\n"
2206 "opened for writing. Add a 'b' to the mode for binary files.\n"
2207 "Add a '+' to the mode to allow simultaneous reading and writing.\n"
2208 "If the buffering argument is given, 0 means unbuffered, 1 means line\n"
2209 "buffered, and larger numbers specify the buffer size. The preferred way\n"
2210 "to open a file is with the builtin open() function.\n"
2213 "Add a 'U' to mode to open the file for input with universal newline\n"
2214 "support. Any line ending in the input file will be seen as a '\\n'\n"
2215 "in Python. Also, a file so opened gains the attribute 'newlines';\n"
2216 "the value for this attribute is one of None (no newline read yet),\n"
2217 "'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2219 "'U' cannot be combined with 'w' or '+' mode.\n"
2222 PyTypeObject PyFile_Type
= {
2223 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
2225 sizeof(PyFileObject
),
2227 (destructor
)file_dealloc
, /* tp_dealloc */
2232 (reprfunc
)file_repr
, /* tp_repr */
2233 0, /* tp_as_number */
2234 0, /* tp_as_sequence */
2235 0, /* tp_as_mapping */
2239 PyObject_GenericGetAttr
, /* tp_getattro */
2240 /* softspace is writable: we must supply tp_setattro */
2241 PyObject_GenericSetAttr
, /* tp_setattro */
2242 0, /* tp_as_buffer */
2243 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
2244 file_doc
, /* tp_doc */
2245 0, /* tp_traverse */
2247 0, /* tp_richcompare */
2248 offsetof(PyFileObject
, weakreflist
), /* tp_weaklistoffset */
2249 (getiterfunc
)file_self
, /* tp_iter */
2250 (iternextfunc
)file_iternext
, /* tp_iternext */
2251 file_methods
, /* tp_methods */
2252 file_memberlist
, /* tp_members */
2253 file_getsetlist
, /* tp_getset */
2256 0, /* tp_descr_get */
2257 0, /* tp_descr_set */
2258 0, /* tp_dictoffset */
2259 file_init
, /* tp_init */
2260 PyType_GenericAlloc
, /* tp_alloc */
2261 file_new
, /* tp_new */
2262 PyObject_Del
, /* tp_free */
2265 /* Interface for the 'soft space' between print items. */
2268 PyFile_SoftSpace(PyObject
*f
, int newflag
)
2274 else if (PyFile_Check(f
)) {
2275 oldflag
= ((PyFileObject
*)f
)->f_softspace
;
2276 ((PyFileObject
*)f
)->f_softspace
= newflag
;
2280 v
= PyObject_GetAttrString(f
, "softspace");
2285 oldflag
= PyInt_AsLong(v
);
2286 assert(oldflag
< INT_MAX
);
2289 v
= PyInt_FromLong((long)newflag
);
2293 if (PyObject_SetAttrString(f
, "softspace", v
) != 0)
2298 return (int)oldflag
;
2301 /* Interfaces to write objects/strings to file-like objects */
2304 PyFile_WriteObject(PyObject
*v
, PyObject
*f
, int flags
)
2306 PyObject
*writer
, *value
, *args
, *result
;
2308 PyErr_SetString(PyExc_TypeError
, "writeobject with NULL file");
2311 else if (PyFile_Check(f
)) {
2312 PyFileObject
*fobj
= (PyFileObject
*) f
;
2313 #ifdef Py_USING_UNICODE
2314 PyObject
*enc
= fobj
->f_encoding
;
2317 if (fobj
->f_fp
== NULL
) {
2321 #ifdef Py_USING_UNICODE
2322 if ((flags
& Py_PRINT_RAW
) &&
2323 PyUnicode_Check(v
) && enc
!= Py_None
) {
2324 char *cenc
= PyString_AS_STRING(enc
);
2325 char *errors
= fobj
->f_errors
== Py_None
?
2326 "strict" : PyString_AS_STRING(fobj
->f_errors
);
2327 value
= PyUnicode_AsEncodedString(v
, cenc
, errors
);
2334 result
= file_PyObject_Print(value
, fobj
, flags
);
2338 return file_PyObject_Print(v
, fobj
, flags
);
2341 writer
= PyObject_GetAttrString(f
, "write");
2344 if (flags
& Py_PRINT_RAW
) {
2345 if (PyUnicode_Check(v
)) {
2349 value
= PyObject_Str(v
);
2352 value
= PyObject_Repr(v
);
2353 if (value
== NULL
) {
2357 args
= PyTuple_Pack(1, value
);
2363 result
= PyEval_CallObject(writer
, args
);
2374 PyFile_WriteString(const char *s
, PyObject
*f
)
2378 /* Should be caused by a pre-existing error */
2379 if (!PyErr_Occurred())
2380 PyErr_SetString(PyExc_SystemError
,
2381 "null file for PyFile_WriteString");
2384 else if (PyFile_Check(f
)) {
2385 PyFileObject
*fobj
= (PyFileObject
*) f
;
2386 FILE *fp
= PyFile_AsFile(f
);
2391 FILE_BEGIN_ALLOW_THREADS(fobj
)
2393 FILE_END_ALLOW_THREADS(fobj
)
2396 else if (!PyErr_Occurred()) {
2397 PyObject
*v
= PyString_FromString(s
);
2401 err
= PyFile_WriteObject(v
, f
, Py_PRINT_RAW
);
2409 /* Try to get a file-descriptor from a Python object. If the object
2410 is an integer or long integer, its value is returned. If not, the
2411 object's fileno() method is called if it exists; the method must return
2412 an integer or long integer, which is returned as the file descriptor value.
2413 -1 is returned on failure.
2416 int PyObject_AsFileDescriptor(PyObject
*o
)
2421 if (PyInt_Check(o
)) {
2422 fd
= PyInt_AsLong(o
);
2424 else if (PyLong_Check(o
)) {
2425 fd
= PyLong_AsLong(o
);
2427 else if ((meth
= PyObject_GetAttrString(o
, "fileno")) != NULL
)
2429 PyObject
*fno
= PyEval_CallObject(meth
, NULL
);
2434 if (PyInt_Check(fno
)) {
2435 fd
= PyInt_AsLong(fno
);
2438 else if (PyLong_Check(fno
)) {
2439 fd
= PyLong_AsLong(fno
);
2443 PyErr_SetString(PyExc_TypeError
,
2444 "fileno() returned a non-integer");
2450 PyErr_SetString(PyExc_TypeError
,
2451 "argument must be an int, or have a fileno() method.");
2456 PyErr_Format(PyExc_ValueError
,
2457 "file descriptor cannot be a negative integer (%i)",
2464 /* From here on we need access to the real fgets and fread */
2469 ** Py_UniversalNewlineFgets is an fgets variation that understands
2470 ** all of \r, \n and \r\n conventions.
2471 ** The stream should be opened in binary mode.
2472 ** If fobj is NULL the routine always does newline conversion, and
2473 ** it may peek one char ahead to gobble the second char in \r\n.
2474 ** If fobj is non-NULL it must be a PyFileObject. In this case there
2475 ** is no readahead but in stead a flag is used to skip a following
2476 ** \n on the next read. Also, if the file is open in binary mode
2477 ** the whole conversion is skipped. Finally, the routine keeps track of
2478 ** the different types of newlines seen.
2479 ** Note that we need no error handling: fgets() treats error and eof
2483 Py_UniversalNewlineFgets(char *buf
, int n
, FILE *stream
, PyObject
*fobj
)
2487 int newlinetypes
= 0;
2489 int univ_newline
= 1;
2492 if (!PyFile_Check(fobj
)) {
2493 errno
= ENXIO
; /* What can you do... */
2496 univ_newline
= ((PyFileObject
*)fobj
)->f_univ_newline
;
2497 if ( !univ_newline
)
2498 return fgets(buf
, n
, stream
);
2499 newlinetypes
= ((PyFileObject
*)fobj
)->f_newlinetypes
;
2500 skipnextlf
= ((PyFileObject
*)fobj
)->f_skipnextlf
;
2503 c
= 'x'; /* Shut up gcc warning */
2504 while (--n
> 0 && (c
= GETC(stream
)) != EOF
) {
2508 /* Seeing a \n here with skipnextlf true
2509 ** means we saw a \r before.
2511 newlinetypes
|= NEWLINE_CRLF
;
2513 if (c
== EOF
) break;
2516 ** Note that c == EOF also brings us here,
2517 ** so we're okay if the last char in the file
2520 newlinetypes
|= NEWLINE_CR
;
2524 /* A \r is translated into a \n, and we skip
2525 ** an adjacent \n, if any. We don't set the
2526 ** newlinetypes flag until we've seen the next char.
2530 } else if ( c
== '\n') {
2531 newlinetypes
|= NEWLINE_LF
;
2534 if (c
== '\n') break;
2536 if ( c
== EOF
&& skipnextlf
)
2537 newlinetypes
|= NEWLINE_CR
;
2538 FUNLOCKFILE(stream
);
2541 ((PyFileObject
*)fobj
)->f_newlinetypes
= newlinetypes
;
2542 ((PyFileObject
*)fobj
)->f_skipnextlf
= skipnextlf
;
2543 } else if ( skipnextlf
) {
2544 /* If we have no file object we cannot save the
2545 ** skipnextlf flag. We have to readahead, which
2546 ** will cause a pause if we're reading from an
2547 ** interactive stream, but that is very unlikely
2548 ** unless we're doing something silly like
2549 ** execfile("/dev/tty").
2561 ** Py_UniversalNewlineFread is an fread variation that understands
2562 ** all of \r, \n and \r\n conventions.
2563 ** The stream should be opened in binary mode.
2564 ** fobj must be a PyFileObject. In this case there
2565 ** is no readahead but in stead a flag is used to skip a following
2566 ** \n on the next read. Also, if the file is open in binary mode
2567 ** the whole conversion is skipped. Finally, the routine keeps track of
2568 ** the different types of newlines seen.
2571 Py_UniversalNewlineFread(char *buf
, size_t n
,
2572 FILE *stream
, PyObject
*fobj
)
2575 PyFileObject
*f
= (PyFileObject
*)fobj
;
2576 int newlinetypes
, skipnextlf
;
2578 assert(buf
!= NULL
);
2579 assert(stream
!= NULL
);
2581 if (!fobj
|| !PyFile_Check(fobj
)) {
2582 errno
= ENXIO
; /* What can you do... */
2585 if (!f
->f_univ_newline
)
2586 return fread(buf
, 1, n
, stream
);
2587 newlinetypes
= f
->f_newlinetypes
;
2588 skipnextlf
= f
->f_skipnextlf
;
2589 /* Invariant: n is the number of bytes remaining to be filled
2597 nread
= fread(dst
, 1, n
, stream
);
2602 n
-= nread
; /* assuming 1 byte out for each in; will adjust */
2603 shortread
= n
!= 0; /* true iff EOF or error */
2607 /* Save as LF and set flag to skip next LF. */
2611 else if (skipnextlf
&& c
== '\n') {
2612 /* Skip LF, and remember we saw CR LF. */
2614 newlinetypes
|= NEWLINE_CRLF
;
2618 /* Normal char to be stored in buffer. Also
2619 * update the newlinetypes flag if either this
2620 * is an LF or the previous char was a CR.
2623 newlinetypes
|= NEWLINE_LF
;
2624 else if (skipnextlf
)
2625 newlinetypes
|= NEWLINE_CR
;
2631 /* If this is EOF, update type flags. */
2632 if (skipnextlf
&& feof(stream
))
2633 newlinetypes
|= NEWLINE_CR
;
2637 f
->f_newlinetypes
= newlinetypes
;
2638 f
->f_skipnextlf
= skipnextlf
;