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
, "(isO)",
136 EISDIR
, msg
, f
->f_name
);
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 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
185 #define Py_VERIFY_WINNT
186 /* The CRT on windows compiled with Visual Studio 2005 and higher may
187 * assert if given invalid mode strings. This is all fine and well
188 * in static languages like C where the mode string is typcially hard
189 * coded. But in Python, were we pass in the mode string from the user,
190 * we need to verify it first manually
192 static int _PyVerify_Mode_WINNT(const char *mode
)
194 /* See if mode string is valid on Windows to avoid hard assertions */
195 /* remove leading spacese */
201 while(*mode
== ' ') /* strip initial spaces */
203 if (!strchr("rwa", *mode
)) /* must start with one of these */
206 if (*mode
== ' ' || *mode
== 'N') /* ignore spaces and N */
208 s
= "+TD"; /* each of this can appear only once */
209 c
= strchr(s
, *mode
);
212 if (singles
& (1<<idx
))
217 s
= "btcnSR"; /* only one of each letter in the pairs allowed */
218 c
= strchr(s
, *mode
);
220 ptrdiff_t idx
= (s
-c
)/2;
221 if (pairs
& (1<<idx
))
230 return 0; /* found an invalid char */
234 char *e
[] = {"UTF-8", "UTF-16LE", "UNICODE"};
238 if (strncmp(mode
, "ccs", 3))
247 for(encoding
= 0; encoding
<_countof(e
); ++encoding
) {
248 size_t l
= strlen(e
[encoding
]);
249 if (!strncmp(mode
, e
[encoding
], l
)) {
250 mode
+= l
; /* found a valid encoding */
254 if (encoding
== _countof(e
))
257 /* skip trailing spaces */
261 return *mode
== '\0'; /* must be at the end of the string */
265 /* check for known incorrect mode strings - problem is, platforms are
266 free to accept any mode characters they like and are supposed to
267 ignore stuff they don't understand... write or append mode with
268 universal newline support is expressly forbidden by PEP 278.
269 Additionally, remove the 'U' from the mode string as platforms
270 won't know what it is. Non-zero return signals an exception */
272 _PyFile_SanitizeMode(char *mode
)
275 size_t len
= strlen(mode
);
278 PyErr_SetString(PyExc_ValueError
, "empty mode string");
282 upos
= strchr(mode
, 'U');
284 memmove(upos
, upos
+1, len
-(upos
-mode
)); /* incl null char */
286 if (mode
[0] == 'w' || mode
[0] == 'a') {
287 PyErr_Format(PyExc_ValueError
, "universal newline "
288 "mode can only be used with modes "
289 "starting with 'r'");
293 if (mode
[0] != 'r') {
294 memmove(mode
+1, mode
, strlen(mode
)+1);
298 if (!strchr(mode
, 'b')) {
299 memmove(mode
+2, mode
+1, strlen(mode
));
302 } else if (mode
[0] != 'r' && mode
[0] != 'w' && mode
[0] != 'a') {
303 PyErr_Format(PyExc_ValueError
, "mode string must begin with "
304 "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode
);
307 #ifdef Py_VERIFY_WINNT
308 /* additional checks on NT with visual studio 2005 and higher */
309 if (!_PyVerify_Mode_WINNT(mode
)) {
310 PyErr_Format(PyExc_ValueError
, "Invalid mode ('%.50s')", mode
);
318 open_the_file(PyFileObject
*f
, char *name
, char *mode
)
322 assert(PyFile_Check(f
));
324 /* windows ignores the passed name in order to support Unicode */
325 assert(f
->f_name
!= NULL
);
327 assert(name
!= NULL
);
329 assert(mode
!= NULL
);
330 assert(f
->f_fp
== NULL
);
332 /* probably need to replace 'U' by 'rb' */
333 newmode
= PyMem_MALLOC(strlen(mode
) + 3);
338 strcpy(newmode
, mode
);
340 if (_PyFile_SanitizeMode(newmode
)) {
345 /* rexec.py can't stop a user from getting the file() constructor --
346 all they have to do is get *any* file object f, and then do
347 type(f). Here we prevent them from doing damage with it. */
348 if (PyEval_GetRestricted()) {
349 PyErr_SetString(PyExc_IOError
,
350 "file() constructor not accessible in restricted mode");
357 if (PyUnicode_Check(f
->f_name
)) {
359 wmode
= PyUnicode_DecodeASCII(newmode
, strlen(newmode
), NULL
);
360 if (f
->f_name
&& wmode
) {
361 FILE_BEGIN_ALLOW_THREADS(f
)
362 /* PyUnicode_AS_UNICODE OK without thread
363 lock as it is a simple dereference. */
364 f
->f_fp
= _wfopen(PyUnicode_AS_UNICODE(f
->f_name
),
365 PyUnicode_AS_UNICODE(wmode
));
366 FILE_END_ALLOW_THREADS(f
)
371 if (NULL
== f
->f_fp
&& NULL
!= name
) {
372 FILE_BEGIN_ALLOW_THREADS(f
)
373 f
->f_fp
= fopen(name
, newmode
);
374 FILE_END_ALLOW_THREADS(f
)
377 if (f
->f_fp
== NULL
) {
378 #if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
379 /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
380 * across all Windows flavors. When it sets EINVAL varies
381 * across Windows flavors, the exact conditions aren't
382 * documented, and the answer lies in the OS's implementation
383 * of Win32's CreateFile function (whose source is secret).
384 * Seems the best we can do is map EINVAL to ENOENT.
385 * Starting with Visual Studio .NET 2005, EINVAL is correctly
386 * set by our CRT error handler (set in exceptions.c.)
388 if (errno
== 0) /* bad mode string */
390 else if (errno
== EINVAL
) /* unknown, but not a mode string */
393 /* EINVAL is returned when an invalid filename or
394 * an invalid mode is supplied. */
395 if (errno
== EINVAL
) {
398 PyOS_snprintf(message
, 100,
399 "invalid mode ('%.50s') or filename", mode
);
400 v
= Py_BuildValue("(isO)", errno
, message
, f
->f_name
);
402 PyErr_SetObject(PyExc_IOError
, v
);
407 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError
, f
->f_name
);
416 return (PyObject
*)f
;
420 close_the_file(PyFileObject
*f
)
423 int (*local_close
)(FILE *);
424 FILE *local_fp
= f
->f_fp
;
425 if (local_fp
!= NULL
) {
426 local_close
= f
->f_close
;
427 if (local_close
!= NULL
&& f
->unlocked_count
> 0) {
428 if (f
->ob_refcnt
> 0) {
429 PyErr_SetString(PyExc_IOError
,
430 "close() called during concurrent "
431 "operation on the same file object.");
433 /* This should not happen unless someone is
434 * carelessly playing with the PyFileObject
435 * struct fields and/or its associated FILE
437 PyErr_SetString(PyExc_SystemError
,
438 "PyFileObject locking error in "
439 "destructor (refcnt <= 0 at close).");
443 /* NULL out the FILE pointer before releasing the GIL, because
444 * it will not be valid anymore after the close() function is
447 if (local_close
!= NULL
) {
448 Py_BEGIN_ALLOW_THREADS
450 sts
= (*local_close
)(local_fp
);
453 return PyErr_SetFromErrno(PyExc_IOError
);
455 return PyInt_FromLong((long)sts
);
462 PyFile_FromFile(FILE *fp
, char *name
, char *mode
, int (*close
)(FILE *))
464 PyFileObject
*f
= (PyFileObject
*)PyFile_Type
.tp_new(&PyFile_Type
,
467 PyObject
*o_name
= PyString_FromString(name
);
470 if (fill_file_fields(f
, fp
, o_name
, mode
, close
) == NULL
) {
476 return (PyObject
*) f
;
480 PyFile_FromString(char *name
, char *mode
)
482 extern int fclose(FILE *);
485 f
= (PyFileObject
*)PyFile_FromFile((FILE *)NULL
, name
, mode
, fclose
);
487 if (open_the_file(f
, name
, mode
) == NULL
) {
492 return (PyObject
*)f
;
496 PyFile_SetBufSize(PyObject
*f
, int bufsize
)
498 PyFileObject
*file
= (PyFileObject
*)f
;
519 if (type
== _IONBF
) {
520 PyMem_Free(file
->f_setbuf
);
521 file
->f_setbuf
= NULL
;
523 file
->f_setbuf
= (char *)PyMem_Realloc(file
->f_setbuf
,
527 setvbuf(file
->f_fp
, file
->f_setbuf
, type
, bufsize
);
528 #else /* !HAVE_SETVBUF */
529 setbuf(file
->f_fp
, file
->f_setbuf
);
530 #endif /* !HAVE_SETVBUF */
534 /* Set the encoding used to output Unicode strings.
535 Return 1 on success, 0 on failure. */
538 PyFile_SetEncoding(PyObject
*f
, const char *enc
)
540 return PyFile_SetEncodingAndErrors(f
, enc
, NULL
);
544 PyFile_SetEncodingAndErrors(PyObject
*f
, const char *enc
, char* errors
)
546 PyFileObject
*file
= (PyFileObject
*)f
;
547 PyObject
*str
, *oerrors
;
549 assert(PyFile_Check(f
));
550 str
= PyString_FromString(enc
);
554 oerrors
= PyString_FromString(errors
);
563 Py_DECREF(file
->f_encoding
);
564 file
->f_encoding
= str
;
565 Py_DECREF(file
->f_errors
);
566 file
->f_errors
= oerrors
;
573 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file");
577 /* Refuse regular file I/O if there's data in the iteration-buffer.
578 * Mixing them would cause data to arrive out of order, as the read*
579 * methods don't use the iteration buffer. */
581 err_iterbuffered(void)
583 PyErr_SetString(PyExc_ValueError
,
584 "Mixing iteration and read methods would lose data");
588 static void drop_readahead(PyFileObject
*);
593 file_dealloc(PyFileObject
*f
)
596 if (f
->weakreflist
!= NULL
)
597 PyObject_ClearWeakRefs((PyObject
*) f
);
598 ret
= close_the_file(f
);
600 PySys_WriteStderr("close failed in file object destructor:\n");
606 PyMem_Free(f
->f_setbuf
);
607 Py_XDECREF(f
->f_name
);
608 Py_XDECREF(f
->f_mode
);
609 Py_XDECREF(f
->f_encoding
);
610 Py_XDECREF(f
->f_errors
);
612 Py_TYPE(f
)->tp_free((PyObject
*)f
);
616 file_repr(PyFileObject
*f
)
618 if (PyUnicode_Check(f
->f_name
)) {
619 #ifdef Py_USING_UNICODE
620 PyObject
*ret
= NULL
;
621 PyObject
*name
= PyUnicode_AsUnicodeEscapeString(f
->f_name
);
622 const char *name_str
= name
? PyString_AsString(name
) : "?";
623 ret
= PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
624 f
->f_fp
== NULL
? "closed" : "open",
626 PyString_AsString(f
->f_mode
),
632 return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
633 f
->f_fp
== NULL
? "closed" : "open",
634 PyString_AsString(f
->f_name
),
635 PyString_AsString(f
->f_mode
),
641 file_close(PyFileObject
*f
)
643 PyObject
*sts
= close_the_file(f
);
644 PyMem_Free(f
->f_setbuf
);
650 /* Our very own off_t-like type, 64-bit if possible */
651 #if !defined(HAVE_LARGEFILE_SUPPORT)
652 typedef off_t Py_off_t
;
653 #elif SIZEOF_OFF_T >= 8
654 typedef off_t Py_off_t
;
655 #elif SIZEOF_FPOS_T >= 8
656 typedef fpos_t Py_off_t
;
658 #error "Large file support, but neither off_t nor fpos_t is large enough."
662 /* a portable fseek() function
663 return 0 on success, non-zero on failure (with errno set) */
665 _portable_fseek(FILE *fp
, Py_off_t offset
, int whence
)
667 #if !defined(HAVE_LARGEFILE_SUPPORT)
668 return fseek(fp
, offset
, whence
);
669 #elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
670 return fseeko(fp
, offset
, whence
);
671 #elif defined(HAVE_FSEEK64)
672 return fseek64(fp
, offset
, whence
);
673 #elif defined(__BEOS__)
674 return _fseek(fp
, offset
, whence
);
675 #elif SIZEOF_FPOS_T >= 8
676 /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
677 and fgetpos() to implement fseek()*/
683 if (_lseeki64(fileno(fp
), 0, 2) == -1)
686 if (fseek(fp
, 0, SEEK_END
) != 0)
691 if (fgetpos(fp
, &pos
) != 0)
695 /* case SEEK_SET: break; */
697 return fsetpos(fp
, &offset
);
699 #error "Large file support, but no way to fseek."
704 /* a portable ftell() function
705 Return -1 on failure with errno set appropriately, current file
706 position on success */
708 _portable_ftell(FILE* fp
)
710 #if !defined(HAVE_LARGEFILE_SUPPORT)
712 #elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
714 #elif defined(HAVE_FTELL64)
716 #elif SIZEOF_FPOS_T >= 8
718 if (fgetpos(fp
, &pos
) != 0)
722 #error "Large file support, but no way to ftell."
728 file_seek(PyFileObject
*f
, PyObject
*args
)
733 PyObject
*offobj
, *off_index
;
739 if (!PyArg_ParseTuple(args
, "O|i:seek", &offobj
, &whence
))
741 off_index
= PyNumber_Index(offobj
);
743 if (!PyFloat_Check(offobj
))
745 /* Deprecated in 2.6 */
747 if (PyErr_WarnEx(PyExc_DeprecationWarning
,
748 "integer argument expected, got float",
754 #if !defined(HAVE_LARGEFILE_SUPPORT)
755 offset
= PyInt_AsLong(off_index
);
757 offset
= PyLong_Check(off_index
) ?
758 PyLong_AsLongLong(off_index
) : PyInt_AsLong(off_index
);
760 Py_DECREF(off_index
);
761 if (PyErr_Occurred())
764 FILE_BEGIN_ALLOW_THREADS(f
)
766 ret
= _portable_fseek(f
->f_fp
, offset
, whence
);
767 FILE_END_ALLOW_THREADS(f
)
770 PyErr_SetFromErrno(PyExc_IOError
);
780 #ifdef HAVE_FTRUNCATE
782 file_truncate(PyFileObject
*f
, PyObject
*args
)
785 PyObject
*newsizeobj
= NULL
;
791 if (!PyArg_UnpackTuple(args
, "truncate", 0, 1, &newsizeobj
))
794 /* Get current file position. If the file happens to be open for
795 * update and the last operation was an input operation, C doesn't
796 * define what the later fflush() will do, but we promise truncate()
797 * won't change the current position (and fflush() *does* change it
798 * then at least on Windows). The easiest thing is to capture
799 * current pos now and seek back to it at the end.
801 FILE_BEGIN_ALLOW_THREADS(f
)
803 initialpos
= _portable_ftell(f
->f_fp
);
804 FILE_END_ALLOW_THREADS(f
)
805 if (initialpos
== -1)
808 /* Set newsize to current postion if newsizeobj NULL, else to the
811 if (newsizeobj
!= NULL
) {
812 #if !defined(HAVE_LARGEFILE_SUPPORT)
813 newsize
= PyInt_AsLong(newsizeobj
);
815 newsize
= PyLong_Check(newsizeobj
) ?
816 PyLong_AsLongLong(newsizeobj
) :
817 PyInt_AsLong(newsizeobj
);
819 if (PyErr_Occurred())
822 else /* default to current position */
823 newsize
= initialpos
;
825 /* Flush the stream. We're mixing stream-level I/O with lower-level
826 * I/O, and a flush may be necessary to synch both platform views
827 * of the current file state.
829 FILE_BEGIN_ALLOW_THREADS(f
)
831 ret
= fflush(f
->f_fp
);
832 FILE_END_ALLOW_THREADS(f
)
837 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
838 so don't even try using it. */
842 /* Have to move current pos to desired endpoint on Windows. */
843 FILE_BEGIN_ALLOW_THREADS(f
)
845 ret
= _portable_fseek(f
->f_fp
, newsize
, SEEK_SET
) != 0;
846 FILE_END_ALLOW_THREADS(f
)
850 /* Truncate. Note that this may grow the file! */
851 FILE_BEGIN_ALLOW_THREADS(f
)
853 hFile
= (HANDLE
)_get_osfhandle(fileno(f
->f_fp
));
854 ret
= hFile
== (HANDLE
)-1;
856 ret
= SetEndOfFile(hFile
) == 0;
860 FILE_END_ALLOW_THREADS(f
)
865 FILE_BEGIN_ALLOW_THREADS(f
)
867 ret
= ftruncate(fileno(f
->f_fp
), newsize
);
868 FILE_END_ALLOW_THREADS(f
)
871 #endif /* !MS_WINDOWS */
873 /* Restore original file position. */
874 FILE_BEGIN_ALLOW_THREADS(f
)
876 ret
= _portable_fseek(f
->f_fp
, initialpos
, SEEK_SET
) != 0;
877 FILE_END_ALLOW_THREADS(f
)
885 PyErr_SetFromErrno(PyExc_IOError
);
889 #endif /* HAVE_FTRUNCATE */
892 file_tell(PyFileObject
*f
)
898 FILE_BEGIN_ALLOW_THREADS(f
)
900 pos
= _portable_ftell(f
->f_fp
);
901 FILE_END_ALLOW_THREADS(f
)
904 PyErr_SetFromErrno(PyExc_IOError
);
908 if (f
->f_skipnextlf
) {
912 f
->f_newlinetypes
|= NEWLINE_CRLF
;
915 } else if (c
!= EOF
) ungetc(c
, f
->f_fp
);
917 #if !defined(HAVE_LARGEFILE_SUPPORT)
918 return PyInt_FromLong(pos
);
920 return PyLong_FromLongLong(pos
);
925 file_fileno(PyFileObject
*f
)
929 return PyInt_FromLong((long) fileno(f
->f_fp
));
933 file_flush(PyFileObject
*f
)
939 FILE_BEGIN_ALLOW_THREADS(f
)
941 res
= fflush(f
->f_fp
);
942 FILE_END_ALLOW_THREADS(f
)
944 PyErr_SetFromErrno(PyExc_IOError
);
953 file_isatty(PyFileObject
*f
)
958 FILE_BEGIN_ALLOW_THREADS(f
)
959 res
= isatty((int)fileno(f
->f_fp
));
960 FILE_END_ALLOW_THREADS(f
)
961 return PyBool_FromLong(res
);
966 #define SMALLCHUNK 8192
968 #define SMALLCHUNK BUFSIZ
972 #define BIGCHUNK (512 * 32)
974 #define BIGCHUNK (512 * 1024)
978 new_buffersize(PyFileObject
*f
, size_t currentsize
)
983 if (fstat(fileno(f
->f_fp
), &st
) == 0) {
985 /* The following is not a bug: we really need to call lseek()
986 *and* ftell(). The reason is that some stdio libraries
987 mistakenly flush their buffer when ftell() is called and
988 the lseek() call it makes fails, thereby throwing away
989 data that cannot be recovered in any way. To avoid this,
990 we first test lseek(), and only call ftell() if lseek()
991 works. We can't use the lseek() value either, because we
992 need to take the amount of buffered data into account.
993 (Yet another reason why stdio stinks. :-) */
994 pos
= lseek(fileno(f
->f_fp
), 0L, SEEK_CUR
);
996 pos
= ftell(f
->f_fp
);
1000 if (end
> pos
&& pos
>= 0)
1001 return currentsize
+ end
- pos
+ 1;
1002 /* Add 1 so if the file were to grow we'd notice. */
1005 if (currentsize
> SMALLCHUNK
) {
1006 /* Keep doubling until we reach BIGCHUNK;
1007 then keep adding BIGCHUNK. */
1008 if (currentsize
<= BIGCHUNK
)
1009 return currentsize
+ currentsize
;
1011 return currentsize
+ BIGCHUNK
;
1013 return currentsize
+ SMALLCHUNK
;
1016 #if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
1017 #define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK || (x) == EAGAIN)
1020 #define BLOCKED_ERRNO(x) ((x) == EWOULDBLOCK)
1023 #define BLOCKED_ERRNO(x) ((x) == EAGAIN)
1025 #define BLOCKED_ERRNO(x) 0
1031 file_read(PyFileObject
*f
, PyObject
*args
)
1033 long bytesrequested
= -1;
1034 size_t bytesread
, buffersize
, chunksize
;
1037 if (f
->f_fp
== NULL
)
1038 return err_closed();
1039 /* refuse to mix with f.next() */
1040 if (f
->f_buf
!= NULL
&&
1041 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
1042 f
->f_buf
[0] != '\0')
1043 return err_iterbuffered();
1044 if (!PyArg_ParseTuple(args
, "|l:read", &bytesrequested
))
1046 if (bytesrequested
< 0)
1047 buffersize
= new_buffersize(f
, (size_t)0);
1049 buffersize
= bytesrequested
;
1050 if (buffersize
> PY_SSIZE_T_MAX
) {
1051 PyErr_SetString(PyExc_OverflowError
,
1052 "requested number of bytes is more than a Python string can hold");
1055 v
= PyString_FromStringAndSize((char *)NULL
, buffersize
);
1060 FILE_BEGIN_ALLOW_THREADS(f
)
1062 chunksize
= Py_UniversalNewlineFread(BUF(v
) + bytesread
,
1063 buffersize
- bytesread
, f
->f_fp
, (PyObject
*)f
);
1064 FILE_END_ALLOW_THREADS(f
)
1065 if (chunksize
== 0) {
1066 if (!ferror(f
->f_fp
))
1069 /* When in non-blocking mode, data shouldn't
1070 * be discarded if a blocking signal was
1071 * received. That will also happen if
1072 * chunksize != 0, but bytesread < buffersize. */
1073 if (bytesread
> 0 && BLOCKED_ERRNO(errno
))
1075 PyErr_SetFromErrno(PyExc_IOError
);
1079 bytesread
+= chunksize
;
1080 if (bytesread
< buffersize
) {
1084 if (bytesrequested
< 0) {
1085 buffersize
= new_buffersize(f
, buffersize
);
1086 if (_PyString_Resize(&v
, buffersize
) < 0)
1089 /* Got what was requested. */
1093 if (bytesread
!= buffersize
)
1094 _PyString_Resize(&v
, bytesread
);
1099 file_readinto(PyFileObject
*f
, PyObject
*args
)
1103 Py_ssize_t ndone
, nnow
;
1106 if (f
->f_fp
== NULL
)
1107 return err_closed();
1108 /* refuse to mix with f.next() */
1109 if (f
->f_buf
!= NULL
&&
1110 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
1111 f
->f_buf
[0] != '\0')
1112 return err_iterbuffered();
1113 if (!PyArg_ParseTuple(args
, "w*", &pbuf
))
1119 FILE_BEGIN_ALLOW_THREADS(f
)
1121 nnow
= Py_UniversalNewlineFread(ptr
+ndone
, ntodo
, f
->f_fp
,
1123 FILE_END_ALLOW_THREADS(f
)
1125 if (!ferror(f
->f_fp
))
1127 PyErr_SetFromErrno(PyExc_IOError
);
1129 PyBuffer_Release(&pbuf
);
1135 PyBuffer_Release(&pbuf
);
1136 return PyInt_FromSsize_t(ndone
);
1139 /**************************************************************************
1140 Routine to get next line using platform fgets().
1144 + MS threadsafe getc is very slow (multiple layers of function calls before+
1145 after each character, to lock+unlock the stream).
1146 + The stream-locking functions are MS-internal -- can't access them from user
1148 + There's nothing Tim could find in the MS C or platform SDK libraries that
1149 can worm around this.
1150 + MS fgets locks/unlocks only once per line; it's the only hook we have.
1152 So we use fgets for speed(!), despite that it's painful.
1154 MS realloc is also slow.
1156 Reports from other platforms on this method vs getc_unlocked (which MS doesn't
1160 Tru64 Unix getline_via_fgets significantly faster
1162 CAUTION: The C std isn't clear about this: in those cases where fgets
1163 writes something into the buffer, can it write into any position beyond the
1164 required trailing null byte? MSVC 6 fgets does not, and no platform is (yet)
1165 known on which it does; and it would be a strange way to code fgets. Still,
1166 getline_via_fgets may not work correctly if it does. The std test
1167 test_bufio.py should fail if platform fgets() routinely writes beyond the
1168 trailing null byte. #define DONT_USE_FGETS_IN_GETLINE to disable this code.
1169 **************************************************************************/
1171 /* Use this routine if told to, or by default on non-get_unlocked()
1172 * platforms unless told not to. Yikes! Let's spell that out:
1173 * On a platform with getc_unlocked():
1174 * By default, use getc_unlocked().
1175 * If you want to use fgets() instead, #define USE_FGETS_IN_GETLINE.
1176 * On a platform without getc_unlocked():
1177 * By default, use fgets().
1178 * If you don't want to use fgets(), #define DONT_USE_FGETS_IN_GETLINE.
1180 #if !defined(USE_FGETS_IN_GETLINE) && !defined(HAVE_GETC_UNLOCKED)
1181 #define USE_FGETS_IN_GETLINE
1184 #if defined(DONT_USE_FGETS_IN_GETLINE) && defined(USE_FGETS_IN_GETLINE)
1185 #undef USE_FGETS_IN_GETLINE
1188 #ifdef USE_FGETS_IN_GETLINE
1190 getline_via_fgets(PyFileObject
*f
, FILE *fp
)
1192 /* INITBUFSIZE is the maximum line length that lets us get away with the fast
1193 * no-realloc, one-fgets()-call path. Boosting it isn't free, because we have
1194 * to fill this much of the buffer with a known value in order to figure out
1195 * how much of the buffer fgets() overwrites. So if INITBUFSIZE is larger
1196 * than "most" lines, we waste time filling unused buffer slots. 100 is
1197 * surely adequate for most peoples' email archives, chewing over source code,
1198 * etc -- "regular old text files".
1199 * MAXBUFSIZE is the maximum line length that lets us get away with the less
1200 * fast (but still zippy) no-realloc, two-fgets()-call path. See above for
1201 * cautions about boosting that. 300 was chosen because the worst real-life
1202 * text-crunching job reported on Python-Dev was a mail-log crawler where over
1203 * half the lines were 254 chars.
1205 #define INITBUFSIZE 100
1206 #define MAXBUFSIZE 300
1208 char buf
[MAXBUFSIZE
];
1209 PyObject
* v
; /* the string object result */
1210 char* pvfree
; /* address of next free slot */
1211 char* pvend
; /* address one beyond last free slot */
1212 size_t nfree
; /* # of free buffer slots; pvend-pvfree */
1213 size_t total_v_size
; /* total # of slots in buffer */
1214 size_t increment
; /* amount to increment the buffer */
1217 /* Optimize for normal case: avoid _PyString_Resize if at all
1218 * possible via first reading into stack buffer "buf".
1220 total_v_size
= INITBUFSIZE
; /* start small and pray */
1223 FILE_BEGIN_ALLOW_THREADS(f
)
1224 pvend
= buf
+ total_v_size
;
1225 nfree
= pvend
- pvfree
;
1226 memset(pvfree
, '\n', nfree
);
1227 assert(nfree
< INT_MAX
); /* Should be atmost MAXBUFSIZE */
1228 p
= fgets(pvfree
, (int)nfree
, fp
);
1229 FILE_END_ALLOW_THREADS(f
)
1233 if (PyErr_CheckSignals())
1235 v
= PyString_FromStringAndSize(buf
, pvfree
- buf
);
1238 /* fgets read *something* */
1239 p
= memchr(pvfree
, '\n', nfree
);
1241 /* Did the \n come from fgets or from us?
1242 * Since fgets stops at the first \n, and then writes
1243 * \0, if it's from fgets a \0 must be next. But if
1244 * that's so, it could not have come from us, since
1245 * the \n's we filled the buffer with have only more
1246 * \n's to the right.
1248 if (p
+1 < pvend
&& *(p
+1) == '\0') {
1249 /* It's from fgets: we win! In particular,
1250 * we haven't done any mallocs yet, and can
1251 * build the final result on the first try.
1253 ++p
; /* include \n from fgets */
1256 /* Must be from us: fgets didn't fill the
1257 * buffer and didn't find a newline, so it
1258 * must be the last and newline-free line of
1261 assert(p
> pvfree
&& *(p
-1) == '\0');
1262 --p
; /* don't include \0 from fgets */
1264 v
= PyString_FromStringAndSize(buf
, p
- buf
);
1267 /* yuck: fgets overwrote all the newlines, i.e. the entire
1268 * buffer. So this line isn't over yet, or maybe it is but
1269 * we're exactly at EOF. If we haven't already, try using the
1270 * rest of the stack buffer.
1272 assert(*(pvend
-1) == '\0');
1273 if (pvfree
== buf
) {
1274 pvfree
= pvend
- 1; /* overwrite trailing null */
1275 total_v_size
= MAXBUFSIZE
;
1281 /* The stack buffer isn't big enough; malloc a string object and read
1284 total_v_size
= MAXBUFSIZE
<< 1;
1285 v
= PyString_FromStringAndSize((char*)NULL
, (int)total_v_size
);
1288 /* copy over everything except the last null byte */
1289 memcpy(BUF(v
), buf
, MAXBUFSIZE
-1);
1290 pvfree
= BUF(v
) + MAXBUFSIZE
- 1;
1292 /* Keep reading stuff into v; if it ever ends successfully, break
1293 * after setting p one beyond the end of the line. The code here is
1294 * very much like the code above, except reads into v's buffer; see
1295 * the code above for detailed comments about the logic.
1298 FILE_BEGIN_ALLOW_THREADS(f
)
1299 pvend
= BUF(v
) + total_v_size
;
1300 nfree
= pvend
- pvfree
;
1301 memset(pvfree
, '\n', nfree
);
1302 assert(nfree
< INT_MAX
);
1303 p
= fgets(pvfree
, (int)nfree
, fp
);
1304 FILE_END_ALLOW_THREADS(f
)
1308 if (PyErr_CheckSignals()) {
1315 p
= memchr(pvfree
, '\n', nfree
);
1317 if (p
+1 < pvend
&& *(p
+1) == '\0') {
1318 /* \n came from fgets */
1322 /* \n came from us; last line of file, no newline */
1323 assert(p
> pvfree
&& *(p
-1) == '\0');
1327 /* expand buffer and try again */
1328 assert(*(pvend
-1) == '\0');
1329 increment
= total_v_size
>> 2; /* mild exponential growth */
1330 prev_v_size
= total_v_size
;
1331 total_v_size
+= increment
;
1332 /* check for overflow */
1333 if (total_v_size
<= prev_v_size
||
1334 total_v_size
> PY_SSIZE_T_MAX
) {
1335 PyErr_SetString(PyExc_OverflowError
,
1336 "line is longer than a Python string can hold");
1340 if (_PyString_Resize(&v
, (int)total_v_size
) < 0)
1342 /* overwrite the trailing null byte */
1343 pvfree
= BUF(v
) + (prev_v_size
- 1);
1345 if (BUF(v
) + total_v_size
!= p
)
1346 _PyString_Resize(&v
, p
- BUF(v
));
1351 #endif /* ifdef USE_FGETS_IN_GETLINE */
1353 /* Internal routine to get a line.
1354 Size argument interpretation:
1356 <= 0: read arbitrary line
1360 get_line(PyFileObject
*f
, int n
)
1365 size_t total_v_size
; /* total # of slots in buffer */
1366 size_t used_v_size
; /* # used slots in buffer */
1367 size_t increment
; /* amount to increment the buffer */
1369 int newlinetypes
= f
->f_newlinetypes
;
1370 int skipnextlf
= f
->f_skipnextlf
;
1371 int univ_newline
= f
->f_univ_newline
;
1373 #if defined(USE_FGETS_IN_GETLINE)
1374 if (n
<= 0 && !univ_newline
)
1375 return getline_via_fgets(f
, fp
);
1377 total_v_size
= n
> 0 ? n
: 100;
1378 v
= PyString_FromStringAndSize((char *)NULL
, total_v_size
);
1382 end
= buf
+ total_v_size
;
1385 FILE_BEGIN_ALLOW_THREADS(f
)
1388 c
= 'x'; /* Shut up gcc warning */
1389 while ( buf
!= end
&& (c
= GETC(fp
)) != EOF
) {
1393 /* Seeing a \n here with
1394 * skipnextlf true means we
1397 newlinetypes
|= NEWLINE_CRLF
;
1399 if (c
== EOF
) break;
1401 newlinetypes
|= NEWLINE_CR
;
1407 } else if ( c
== '\n')
1408 newlinetypes
|= NEWLINE_LF
;
1410 if (c
== '\n') break;
1412 if ( c
== EOF
&& skipnextlf
)
1413 newlinetypes
|= NEWLINE_CR
;
1414 } else /* If not universal newlines use the normal loop */
1415 while ((c
= GETC(fp
)) != EOF
&&
1416 (*buf
++ = c
) != '\n' &&
1420 FILE_END_ALLOW_THREADS(f
)
1421 f
->f_newlinetypes
= newlinetypes
;
1422 f
->f_skipnextlf
= skipnextlf
;
1427 PyErr_SetFromErrno(PyExc_IOError
);
1433 if (PyErr_CheckSignals()) {
1439 /* Must be because buf == end */
1442 used_v_size
= total_v_size
;
1443 increment
= total_v_size
>> 2; /* mild exponential growth */
1444 total_v_size
+= increment
;
1445 if (total_v_size
> PY_SSIZE_T_MAX
) {
1446 PyErr_SetString(PyExc_OverflowError
,
1447 "line is longer than a Python string can hold");
1451 if (_PyString_Resize(&v
, total_v_size
) < 0)
1453 buf
= BUF(v
) + used_v_size
;
1454 end
= BUF(v
) + total_v_size
;
1457 used_v_size
= buf
- BUF(v
);
1458 if (used_v_size
!= total_v_size
)
1459 _PyString_Resize(&v
, used_v_size
);
1463 /* External C interface */
1466 PyFile_GetLine(PyObject
*f
, int n
)
1471 PyErr_BadInternalCall();
1475 if (PyFile_Check(f
)) {
1476 PyFileObject
*fo
= (PyFileObject
*)f
;
1477 if (fo
->f_fp
== NULL
)
1478 return err_closed();
1479 /* refuse to mix with f.next() */
1480 if (fo
->f_buf
!= NULL
&&
1481 (fo
->f_bufend
- fo
->f_bufptr
) > 0 &&
1482 fo
->f_buf
[0] != '\0')
1483 return err_iterbuffered();
1484 result
= get_line(fo
, n
);
1490 reader
= PyObject_GetAttrString(f
, "readline");
1494 args
= PyTuple_New(0);
1496 args
= Py_BuildValue("(i)", n
);
1501 result
= PyEval_CallObject(reader
, args
);
1504 if (result
!= NULL
&& !PyString_Check(result
) &&
1505 !PyUnicode_Check(result
)) {
1508 PyErr_SetString(PyExc_TypeError
,
1509 "object.readline() returned non-string");
1513 if (n
< 0 && result
!= NULL
&& PyString_Check(result
)) {
1514 char *s
= PyString_AS_STRING(result
);
1515 Py_ssize_t len
= PyString_GET_SIZE(result
);
1519 PyErr_SetString(PyExc_EOFError
,
1520 "EOF when reading a line");
1522 else if (s
[len
-1] == '\n') {
1523 if (result
->ob_refcnt
== 1)
1524 _PyString_Resize(&result
, len
-1);
1527 v
= PyString_FromStringAndSize(s
, len
-1);
1533 #ifdef Py_USING_UNICODE
1534 if (n
< 0 && result
!= NULL
&& PyUnicode_Check(result
)) {
1535 Py_UNICODE
*s
= PyUnicode_AS_UNICODE(result
);
1536 Py_ssize_t len
= PyUnicode_GET_SIZE(result
);
1540 PyErr_SetString(PyExc_EOFError
,
1541 "EOF when reading a line");
1543 else if (s
[len
-1] == '\n') {
1544 if (result
->ob_refcnt
== 1)
1545 PyUnicode_Resize(&result
, len
-1);
1548 v
= PyUnicode_FromUnicode(s
, len
-1);
1561 file_readline(PyFileObject
*f
, PyObject
*args
)
1565 if (f
->f_fp
== NULL
)
1566 return err_closed();
1567 /* refuse to mix with f.next() */
1568 if (f
->f_buf
!= NULL
&&
1569 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
1570 f
->f_buf
[0] != '\0')
1571 return err_iterbuffered();
1572 if (!PyArg_ParseTuple(args
, "|i:readline", &n
))
1575 return PyString_FromString("");
1578 return get_line(f
, n
);
1582 file_readlines(PyFileObject
*f
, PyObject
*args
)
1585 PyObject
*list
= NULL
;
1587 char small_buffer
[SMALLCHUNK
];
1588 char *buffer
= small_buffer
;
1589 size_t buffersize
= SMALLCHUNK
;
1590 PyObject
*big_buffer
= NULL
;
1593 size_t totalread
= 0;
1598 if (f
->f_fp
== NULL
)
1599 return err_closed();
1600 /* refuse to mix with f.next() */
1601 if (f
->f_buf
!= NULL
&&
1602 (f
->f_bufend
- f
->f_bufptr
) > 0 &&
1603 f
->f_buf
[0] != '\0')
1604 return err_iterbuffered();
1605 if (!PyArg_ParseTuple(args
, "|l:readlines", &sizehint
))
1607 if ((list
= PyList_New(0)) == NULL
)
1613 FILE_BEGIN_ALLOW_THREADS(f
)
1615 nread
= Py_UniversalNewlineFread(buffer
+nfilled
,
1616 buffersize
-nfilled
, f
->f_fp
, (PyObject
*)f
);
1617 FILE_END_ALLOW_THREADS(f
)
1618 shortread
= (nread
< buffersize
-nfilled
);
1622 if (!ferror(f
->f_fp
))
1624 PyErr_SetFromErrno(PyExc_IOError
);
1629 p
= (char *)memchr(buffer
+nfilled
, '\n', nread
);
1631 /* Need a larger buffer to fit this line */
1634 if (buffersize
> PY_SSIZE_T_MAX
) {
1635 PyErr_SetString(PyExc_OverflowError
,
1636 "line is longer than a Python string can hold");
1639 if (big_buffer
== NULL
) {
1640 /* Create the big buffer */
1641 big_buffer
= PyString_FromStringAndSize(
1643 if (big_buffer
== NULL
)
1645 buffer
= PyString_AS_STRING(big_buffer
);
1646 memcpy(buffer
, small_buffer
, nfilled
);
1649 /* Grow the big buffer */
1650 if ( _PyString_Resize(&big_buffer
, buffersize
) < 0 )
1652 buffer
= PyString_AS_STRING(big_buffer
);
1656 end
= buffer
+nfilled
+nread
;
1659 /* Process complete lines */
1661 line
= PyString_FromStringAndSize(q
, p
-q
);
1664 err
= PyList_Append(list
, line
);
1669 p
= (char *)memchr(q
, '\n', end
-q
);
1670 } while (p
!= NULL
);
1671 /* Move the remaining incomplete line to the start */
1673 memmove(buffer
, q
, nfilled
);
1675 if (totalread
>= (size_t)sizehint
)
1679 /* Partial last line */
1680 line
= PyString_FromStringAndSize(buffer
, nfilled
);
1684 /* Need to complete the last line */
1685 PyObject
*rest
= get_line(f
, 0);
1690 PyString_Concat(&line
, rest
);
1695 err
= PyList_Append(list
, line
);
1702 Py_XDECREF(big_buffer
);
1711 file_write(PyFileObject
*f
, PyObject
*args
)
1716 if (f
->f_fp
== NULL
)
1717 return err_closed();
1719 if (!PyArg_ParseTuple(args
, "s*", &pbuf
))
1724 if (!PyArg_ParseTuple(args
, "t#", &s
, &n
))
1727 FILE_BEGIN_ALLOW_THREADS(f
)
1729 n2
= fwrite(s
, 1, n
, f
->f_fp
);
1730 FILE_END_ALLOW_THREADS(f
)
1732 PyBuffer_Release(&pbuf
);
1734 PyErr_SetFromErrno(PyExc_IOError
);
1743 file_writelines(PyFileObject
*f
, PyObject
*seq
)
1745 #define CHUNKSIZE 1000
1746 PyObject
*list
, *line
;
1747 PyObject
*it
; /* iter(seq) */
1750 Py_ssize_t i
, j
, nwritten
, len
;
1752 assert(seq
!= NULL
);
1753 if (f
->f_fp
== NULL
)
1754 return err_closed();
1758 islist
= PyList_Check(seq
);
1762 it
= PyObject_GetIter(seq
);
1764 PyErr_SetString(PyExc_TypeError
,
1765 "writelines() requires an iterable argument");
1768 /* From here on, fail by going to error, to reclaim "it". */
1769 list
= PyList_New(CHUNKSIZE
);
1774 /* Strategy: slurp CHUNKSIZE lines into a private list,
1775 checking that they are all strings, then write that list
1776 without holding the interpreter lock, then come back for more. */
1777 for (index
= 0; ; index
+= CHUNKSIZE
) {
1780 list
= PyList_GetSlice(seq
, index
, index
+CHUNKSIZE
);
1783 j
= PyList_GET_SIZE(list
);
1786 for (j
= 0; j
< CHUNKSIZE
; j
++) {
1787 line
= PyIter_Next(it
);
1789 if (PyErr_Occurred())
1793 PyList_SetItem(list
, j
, line
);
1799 /* Check that all entries are indeed strings. If not,
1800 apply the same rules as for file.write() and
1801 convert the results to strings. This is slow, but
1802 seems to be the only way since all conversion APIs
1803 could potentially execute Python code. */
1804 for (i
= 0; i
< j
; i
++) {
1805 PyObject
*v
= PyList_GET_ITEM(list
, i
);
1806 if (!PyString_Check(v
)) {
1808 if (((f
->f_binary
&&
1809 PyObject_AsReadBuffer(v
,
1810 (const void**)&buffer
,
1812 PyObject_AsCharBuffer(v
,
1815 PyErr_SetString(PyExc_TypeError
,
1816 "writelines() argument must be a sequence of strings");
1819 line
= PyString_FromStringAndSize(buffer
,
1824 PyList_SET_ITEM(list
, i
, line
);
1828 /* Since we are releasing the global lock, the
1829 following code may *not* execute Python code. */
1831 FILE_BEGIN_ALLOW_THREADS(f
)
1833 for (i
= 0; i
< j
; i
++) {
1834 line
= PyList_GET_ITEM(list
, i
);
1835 len
= PyString_GET_SIZE(line
);
1836 nwritten
= fwrite(PyString_AS_STRING(line
),
1838 if (nwritten
!= len
) {
1839 FILE_ABORT_ALLOW_THREADS(f
)
1840 PyErr_SetFromErrno(PyExc_IOError
);
1845 FILE_END_ALLOW_THREADS(f
)
1861 file_self(PyFileObject
*f
)
1863 if (f
->f_fp
== NULL
)
1864 return err_closed();
1866 return (PyObject
*)f
;
1870 file_xreadlines(PyFileObject
*f
)
1872 if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
1873 "try 'for line in f' instead", 1) < 0)
1875 return file_self(f
);
1879 file_exit(PyObject
*f
, PyObject
*args
)
1881 PyObject
*ret
= PyObject_CallMethod(f
, "close", NULL
);
1883 /* If error occurred, pass through */
1886 /* We cannot return the result of close since a true
1887 * value will be interpreted as "yes, swallow the
1888 * exception if one was raised inside the with block". */
1892 PyDoc_STRVAR(readline_doc
,
1893 "readline([size]) -> next line from the file, as a string.\n"
1895 "Retain newline. A non-negative size argument limits the maximum\n"
1896 "number of bytes to return (an incomplete line may be returned then).\n"
1897 "Return an empty string at EOF.");
1899 PyDoc_STRVAR(read_doc
,
1900 "read([size]) -> read at most size bytes, returned as a string.\n"
1902 "If the size argument is negative or omitted, read until EOF is reached.\n"
1903 "Notice that when in non-blocking mode, less data than what was requested\n"
1904 "may be returned, even if no size parameter was given.");
1906 PyDoc_STRVAR(write_doc
,
1907 "write(str) -> None. Write string str to file.\n"
1909 "Note that due to buffering, flush() or close() may be needed before\n"
1910 "the file on disk reflects the data written.");
1912 PyDoc_STRVAR(fileno_doc
,
1913 "fileno() -> integer \"file descriptor\".\n"
1915 "This is needed for lower-level file interfaces, such os.read().");
1917 PyDoc_STRVAR(seek_doc
,
1918 "seek(offset[, whence]) -> None. Move to new file position.\n"
1920 "Argument offset is a byte count. Optional argument whence defaults to\n"
1921 "0 (offset from start of file, offset should be >= 0); other values are 1\n"
1922 "(move relative to current position, positive or negative), and 2 (move\n"
1923 "relative to end of file, usually negative, although many platforms allow\n"
1924 "seeking beyond the end of a file). If the file is opened in text mode,\n"
1925 "only offsets returned by tell() are legal. Use of other offsets causes\n"
1926 "undefined behavior."
1928 "Note that not all file objects are seekable.");
1930 #ifdef HAVE_FTRUNCATE
1931 PyDoc_STRVAR(truncate_doc
,
1932 "truncate([size]) -> None. Truncate the file to at most size bytes.\n"
1934 "Size defaults to the current file position, as returned by tell().");
1937 PyDoc_STRVAR(tell_doc
,
1938 "tell() -> current file position, an integer (may be a long integer).");
1940 PyDoc_STRVAR(readinto_doc
,
1941 "readinto() -> Undocumented. Don't use this; it may go away.");
1943 PyDoc_STRVAR(readlines_doc
,
1944 "readlines([size]) -> list of strings, each a line from the file.\n"
1946 "Call readline() repeatedly and return a list of the lines so read.\n"
1947 "The optional size argument, if given, is an approximate bound on the\n"
1948 "total number of bytes in the lines returned.");
1950 PyDoc_STRVAR(xreadlines_doc
,
1951 "xreadlines() -> returns self.\n"
1953 "For backward compatibility. File objects now include the performance\n"
1954 "optimizations previously implemented in the xreadlines module.");
1956 PyDoc_STRVAR(writelines_doc
,
1957 "writelines(sequence_of_strings) -> None. Write the strings to the file.\n"
1959 "Note that newlines are not added. The sequence can be any iterable object\n"
1960 "producing strings. This is equivalent to calling write() for each string.");
1962 PyDoc_STRVAR(flush_doc
,
1963 "flush() -> None. Flush the internal I/O buffer.");
1965 PyDoc_STRVAR(close_doc
,
1966 "close() -> None or (perhaps) an integer. Close the file.\n"
1968 "Sets data attribute .closed to True. A closed file cannot be used for\n"
1969 "further I/O operations. close() may be called more than once without\n"
1970 "error. Some kinds of file objects (for example, opened by popen())\n"
1971 "may return an exit status upon closing.");
1973 PyDoc_STRVAR(isatty_doc
,
1974 "isatty() -> true or false. True if the file is connected to a tty device.");
1976 PyDoc_STRVAR(enter_doc
,
1977 "__enter__() -> self.");
1979 PyDoc_STRVAR(exit_doc
,
1980 "__exit__(*excinfo) -> None. Closes the file.");
1982 static PyMethodDef file_methods
[] = {
1983 {"readline", (PyCFunction
)file_readline
, METH_VARARGS
, readline_doc
},
1984 {"read", (PyCFunction
)file_read
, METH_VARARGS
, read_doc
},
1985 {"write", (PyCFunction
)file_write
, METH_VARARGS
, write_doc
},
1986 {"fileno", (PyCFunction
)file_fileno
, METH_NOARGS
, fileno_doc
},
1987 {"seek", (PyCFunction
)file_seek
, METH_VARARGS
, seek_doc
},
1988 #ifdef HAVE_FTRUNCATE
1989 {"truncate", (PyCFunction
)file_truncate
, METH_VARARGS
, truncate_doc
},
1991 {"tell", (PyCFunction
)file_tell
, METH_NOARGS
, tell_doc
},
1992 {"readinto", (PyCFunction
)file_readinto
, METH_VARARGS
, readinto_doc
},
1993 {"readlines", (PyCFunction
)file_readlines
, METH_VARARGS
, readlines_doc
},
1994 {"xreadlines",(PyCFunction
)file_xreadlines
, METH_NOARGS
, xreadlines_doc
},
1995 {"writelines",(PyCFunction
)file_writelines
, METH_O
, writelines_doc
},
1996 {"flush", (PyCFunction
)file_flush
, METH_NOARGS
, flush_doc
},
1997 {"close", (PyCFunction
)file_close
, METH_NOARGS
, close_doc
},
1998 {"isatty", (PyCFunction
)file_isatty
, METH_NOARGS
, isatty_doc
},
1999 {"__enter__", (PyCFunction
)file_self
, METH_NOARGS
, enter_doc
},
2000 {"__exit__", (PyCFunction
)file_exit
, METH_VARARGS
, exit_doc
},
2001 {NULL
, NULL
} /* sentinel */
2004 #define OFF(x) offsetof(PyFileObject, x)
2006 static PyMemberDef file_memberlist
[] = {
2007 {"mode", T_OBJECT
, OFF(f_mode
), RO
,
2008 "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
2009 {"name", T_OBJECT
, OFF(f_name
), RO
,
2011 {"encoding", T_OBJECT
, OFF(f_encoding
), RO
,
2013 {"errors", T_OBJECT
, OFF(f_errors
), RO
,
2014 "Unicode error handler"},
2015 /* getattr(f, "closed") is implemented without this table */
2016 {NULL
} /* Sentinel */
2020 get_closed(PyFileObject
*f
, void *closure
)
2022 return PyBool_FromLong((long)(f
->f_fp
== 0));
2025 get_newlines(PyFileObject
*f
, void *closure
)
2027 switch (f
->f_newlinetypes
) {
2028 case NEWLINE_UNKNOWN
:
2032 return PyString_FromString("\r");
2034 return PyString_FromString("\n");
2035 case NEWLINE_CR
|NEWLINE_LF
:
2036 return Py_BuildValue("(ss)", "\r", "\n");
2038 return PyString_FromString("\r\n");
2039 case NEWLINE_CR
|NEWLINE_CRLF
:
2040 return Py_BuildValue("(ss)", "\r", "\r\n");
2041 case NEWLINE_LF
|NEWLINE_CRLF
:
2042 return Py_BuildValue("(ss)", "\n", "\r\n");
2043 case NEWLINE_CR
|NEWLINE_LF
|NEWLINE_CRLF
:
2044 return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
2046 PyErr_Format(PyExc_SystemError
,
2047 "Unknown newlines value 0x%x\n",
2054 get_softspace(PyFileObject
*f
, void *closure
)
2056 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2058 return PyInt_FromLong(f
->f_softspace
);
2062 set_softspace(PyFileObject
*f
, PyObject
*value
)
2065 if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
2068 if (value
== NULL
) {
2069 PyErr_SetString(PyExc_TypeError
,
2070 "can't delete softspace attribute");
2074 new = PyInt_AsLong(value
);
2075 if (new == -1 && PyErr_Occurred())
2077 f
->f_softspace
= new;
2081 static PyGetSetDef file_getsetlist
[] = {
2082 {"closed", (getter
)get_closed
, NULL
, "True if the file is closed"},
2083 {"newlines", (getter
)get_newlines
, NULL
,
2084 "end-of-line convention used in this file"},
2085 {"softspace", (getter
)get_softspace
, (setter
)set_softspace
,
2086 "flag indicating that a space needs to be printed; used by print"},
2091 drop_readahead(PyFileObject
*f
)
2093 if (f
->f_buf
!= NULL
) {
2094 PyMem_Free(f
->f_buf
);
2099 /* Make sure that file has a readahead buffer with at least one byte
2100 (unless at EOF) and no more than bufsize. Returns negative value on
2101 error, will set MemoryError if bufsize bytes cannot be allocated. */
2103 readahead(PyFileObject
*f
, int bufsize
)
2105 Py_ssize_t chunksize
;
2107 if (f
->f_buf
!= NULL
) {
2108 if( (f
->f_bufend
- f
->f_bufptr
) >= 1)
2113 if ((f
->f_buf
= (char *)PyMem_Malloc(bufsize
)) == NULL
) {
2117 FILE_BEGIN_ALLOW_THREADS(f
)
2119 chunksize
= Py_UniversalNewlineFread(
2120 f
->f_buf
, bufsize
, f
->f_fp
, (PyObject
*)f
);
2121 FILE_END_ALLOW_THREADS(f
)
2122 if (chunksize
== 0) {
2123 if (ferror(f
->f_fp
)) {
2124 PyErr_SetFromErrno(PyExc_IOError
);
2130 f
->f_bufptr
= f
->f_buf
;
2131 f
->f_bufend
= f
->f_buf
+ chunksize
;
2135 /* Used by file_iternext. The returned string will start with 'skip'
2136 uninitialized bytes followed by the remainder of the line. Don't be
2137 horrified by the recursive call: maximum recursion depth is limited by
2138 logarithmic buffer growth to about 50 even when reading a 1gb line. */
2140 static PyStringObject
*
2141 readahead_get_line_skip(PyFileObject
*f
, int skip
, int bufsize
)
2148 if (f
->f_buf
== NULL
)
2149 if (readahead(f
, bufsize
) < 0)
2152 len
= f
->f_bufend
- f
->f_bufptr
;
2154 return (PyStringObject
*)
2155 PyString_FromStringAndSize(NULL
, skip
);
2156 bufptr
= (char *)memchr(f
->f_bufptr
, '\n', len
);
2157 if (bufptr
!= NULL
) {
2158 bufptr
++; /* Count the '\n' */
2159 len
= bufptr
- f
->f_bufptr
;
2160 s
= (PyStringObject
*)
2161 PyString_FromStringAndSize(NULL
, skip
+len
);
2164 memcpy(PyString_AS_STRING(s
)+skip
, f
->f_bufptr
, len
);
2165 f
->f_bufptr
= bufptr
;
2166 if (bufptr
== f
->f_bufend
)
2169 bufptr
= f
->f_bufptr
;
2171 f
->f_buf
= NULL
; /* Force new readahead buffer */
2172 assert(skip
+len
< INT_MAX
);
2173 s
= readahead_get_line_skip(
2174 f
, (int)(skip
+len
), bufsize
+ (bufsize
>>2) );
2179 memcpy(PyString_AS_STRING(s
)+skip
, bufptr
, len
);
2185 /* A larger buffer size may actually decrease performance. */
2186 #define READAHEAD_BUFSIZE 8192
2189 file_iternext(PyFileObject
*f
)
2193 if (f
->f_fp
== NULL
)
2194 return err_closed();
2196 l
= readahead_get_line_skip(f
, 0, READAHEAD_BUFSIZE
);
2197 if (l
== NULL
|| PyString_GET_SIZE(l
) == 0) {
2201 return (PyObject
*)l
;
2206 file_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2209 static PyObject
*not_yet_string
;
2211 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
2213 if (not_yet_string
== NULL
) {
2214 not_yet_string
= PyString_InternFromString("<uninitialized file>");
2215 if (not_yet_string
== NULL
)
2219 self
= type
->tp_alloc(type
, 0);
2221 /* Always fill in the name and mode, so that nobody else
2222 needs to special-case NULLs there. */
2223 Py_INCREF(not_yet_string
);
2224 ((PyFileObject
*)self
)->f_name
= not_yet_string
;
2225 Py_INCREF(not_yet_string
);
2226 ((PyFileObject
*)self
)->f_mode
= not_yet_string
;
2228 ((PyFileObject
*)self
)->f_encoding
= Py_None
;
2230 ((PyFileObject
*)self
)->f_errors
= Py_None
;
2231 ((PyFileObject
*)self
)->weakreflist
= NULL
;
2232 ((PyFileObject
*)self
)->unlocked_count
= 0;
2238 file_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2240 PyFileObject
*foself
= (PyFileObject
*)self
;
2242 static char *kwlist
[] = {"name", "mode", "buffering", 0};
2246 int wideargument
= 0;
2248 assert(PyFile_Check(self
));
2249 if (foself
->f_fp
!= NULL
) {
2250 /* Have to close the existing file first. */
2251 PyObject
*closeresult
= file_close(foself
);
2252 if (closeresult
== NULL
)
2254 Py_DECREF(closeresult
);
2258 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
2260 if (PyArg_ParseTupleAndKeywords(args
, kwds
, "U|si:file",
2261 kwlist
, &po
, &mode
, &bufsize
)) {
2263 if (fill_file_fields(foself
, NULL
, po
, mode
,
2267 /* Drop the argument parsing error as narrow
2268 strings are also valid. */
2274 if (!wideargument
) {
2277 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "et|si:file", kwlist
,
2278 Py_FileSystemDefaultEncoding
,
2283 /* We parse again to get the name as a PyObject */
2284 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|si:file",
2285 kwlist
, &o_name
, &mode
,
2289 if (fill_file_fields(foself
, NULL
, o_name
, mode
,
2293 if (open_the_file(foself
, name
, mode
) == NULL
)
2295 foself
->f_setbuf
= NULL
;
2296 PyFile_SetBufSize(self
, bufsize
);
2303 PyMem_Free(name
); /* free the encoded string */
2307 PyDoc_VAR(file_doc
) =
2309 "file(name[, mode[, buffering]]) -> file object\n"
2311 "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
2312 "writing or appending. The file will be created if it doesn't exist\n"
2313 "when opened for writing or appending; it will be truncated when\n"
2314 "opened for writing. Add a 'b' to the mode for binary files.\n"
2315 "Add a '+' to the mode to allow simultaneous reading and writing.\n"
2316 "If the buffering argument is given, 0 means unbuffered, 1 means line\n"
2317 "buffered, and larger numbers specify the buffer size. The preferred way\n"
2318 "to open a file is with the builtin open() function.\n"
2321 "Add a 'U' to mode to open the file for input with universal newline\n"
2322 "support. Any line ending in the input file will be seen as a '\\n'\n"
2323 "in Python. Also, a file so opened gains the attribute 'newlines';\n"
2324 "the value for this attribute is one of None (no newline read yet),\n"
2325 "'\\r', '\\n', '\\r\\n' or a tuple containing all the newline types seen.\n"
2327 "'U' cannot be combined with 'w' or '+' mode.\n"
2330 PyTypeObject PyFile_Type
= {
2331 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
2333 sizeof(PyFileObject
),
2335 (destructor
)file_dealloc
, /* tp_dealloc */
2340 (reprfunc
)file_repr
, /* tp_repr */
2341 0, /* tp_as_number */
2342 0, /* tp_as_sequence */
2343 0, /* tp_as_mapping */
2347 PyObject_GenericGetAttr
, /* tp_getattro */
2348 /* softspace is writable: we must supply tp_setattro */
2349 PyObject_GenericSetAttr
, /* tp_setattro */
2350 0, /* tp_as_buffer */
2351 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
2352 file_doc
, /* tp_doc */
2353 0, /* tp_traverse */
2355 0, /* tp_richcompare */
2356 offsetof(PyFileObject
, weakreflist
), /* tp_weaklistoffset */
2357 (getiterfunc
)file_self
, /* tp_iter */
2358 (iternextfunc
)file_iternext
, /* tp_iternext */
2359 file_methods
, /* tp_methods */
2360 file_memberlist
, /* tp_members */
2361 file_getsetlist
, /* tp_getset */
2364 0, /* tp_descr_get */
2365 0, /* tp_descr_set */
2366 0, /* tp_dictoffset */
2367 file_init
, /* tp_init */
2368 PyType_GenericAlloc
, /* tp_alloc */
2369 file_new
, /* tp_new */
2370 PyObject_Del
, /* tp_free */
2373 /* Interface for the 'soft space' between print items. */
2376 PyFile_SoftSpace(PyObject
*f
, int newflag
)
2382 else if (PyFile_Check(f
)) {
2383 oldflag
= ((PyFileObject
*)f
)->f_softspace
;
2384 ((PyFileObject
*)f
)->f_softspace
= newflag
;
2388 v
= PyObject_GetAttrString(f
, "softspace");
2393 oldflag
= PyInt_AsLong(v
);
2394 assert(oldflag
< INT_MAX
);
2397 v
= PyInt_FromLong((long)newflag
);
2401 if (PyObject_SetAttrString(f
, "softspace", v
) != 0)
2406 return (int)oldflag
;
2409 /* Interfaces to write objects/strings to file-like objects */
2412 PyFile_WriteObject(PyObject
*v
, PyObject
*f
, int flags
)
2414 PyObject
*writer
, *value
, *args
, *result
;
2416 PyErr_SetString(PyExc_TypeError
, "writeobject with NULL file");
2419 else if (PyFile_Check(f
)) {
2420 PyFileObject
*fobj
= (PyFileObject
*) f
;
2421 #ifdef Py_USING_UNICODE
2422 PyObject
*enc
= fobj
->f_encoding
;
2425 if (fobj
->f_fp
== NULL
) {
2429 #ifdef Py_USING_UNICODE
2430 if ((flags
& Py_PRINT_RAW
) &&
2431 PyUnicode_Check(v
) && enc
!= Py_None
) {
2432 char *cenc
= PyString_AS_STRING(enc
);
2433 char *errors
= fobj
->f_errors
== Py_None
?
2434 "strict" : PyString_AS_STRING(fobj
->f_errors
);
2435 value
= PyUnicode_AsEncodedString(v
, cenc
, errors
);
2442 result
= file_PyObject_Print(value
, fobj
, flags
);
2446 return file_PyObject_Print(v
, fobj
, flags
);
2449 writer
= PyObject_GetAttrString(f
, "write");
2452 if (flags
& Py_PRINT_RAW
) {
2453 if (PyUnicode_Check(v
)) {
2457 value
= PyObject_Str(v
);
2460 value
= PyObject_Repr(v
);
2461 if (value
== NULL
) {
2465 args
= PyTuple_Pack(1, value
);
2471 result
= PyEval_CallObject(writer
, args
);
2482 PyFile_WriteString(const char *s
, PyObject
*f
)
2486 /* Should be caused by a pre-existing error */
2487 if (!PyErr_Occurred())
2488 PyErr_SetString(PyExc_SystemError
,
2489 "null file for PyFile_WriteString");
2492 else if (PyFile_Check(f
)) {
2493 PyFileObject
*fobj
= (PyFileObject
*) f
;
2494 FILE *fp
= PyFile_AsFile(f
);
2499 FILE_BEGIN_ALLOW_THREADS(fobj
)
2501 FILE_END_ALLOW_THREADS(fobj
)
2504 else if (!PyErr_Occurred()) {
2505 PyObject
*v
= PyString_FromString(s
);
2509 err
= PyFile_WriteObject(v
, f
, Py_PRINT_RAW
);
2517 /* Try to get a file-descriptor from a Python object. If the object
2518 is an integer or long integer, its value is returned. If not, the
2519 object's fileno() method is called if it exists; the method must return
2520 an integer or long integer, which is returned as the file descriptor value.
2521 -1 is returned on failure.
2524 int PyObject_AsFileDescriptor(PyObject
*o
)
2529 if (PyInt_Check(o
)) {
2530 fd
= PyInt_AsLong(o
);
2532 else if (PyLong_Check(o
)) {
2533 fd
= PyLong_AsLong(o
);
2535 else if ((meth
= PyObject_GetAttrString(o
, "fileno")) != NULL
)
2537 PyObject
*fno
= PyEval_CallObject(meth
, NULL
);
2542 if (PyInt_Check(fno
)) {
2543 fd
= PyInt_AsLong(fno
);
2546 else if (PyLong_Check(fno
)) {
2547 fd
= PyLong_AsLong(fno
);
2551 PyErr_SetString(PyExc_TypeError
,
2552 "fileno() returned a non-integer");
2558 PyErr_SetString(PyExc_TypeError
,
2559 "argument must be an int, or have a fileno() method.");
2564 PyErr_Format(PyExc_ValueError
,
2565 "file descriptor cannot be a negative integer (%i)",
2572 /* From here on we need access to the real fgets and fread */
2577 ** Py_UniversalNewlineFgets is an fgets variation that understands
2578 ** all of \r, \n and \r\n conventions.
2579 ** The stream should be opened in binary mode.
2580 ** If fobj is NULL the routine always does newline conversion, and
2581 ** it may peek one char ahead to gobble the second char in \r\n.
2582 ** If fobj is non-NULL it must be a PyFileObject. In this case there
2583 ** is no readahead but in stead a flag is used to skip a following
2584 ** \n on the next read. Also, if the file is open in binary mode
2585 ** the whole conversion is skipped. Finally, the routine keeps track of
2586 ** the different types of newlines seen.
2587 ** Note that we need no error handling: fgets() treats error and eof
2591 Py_UniversalNewlineFgets(char *buf
, int n
, FILE *stream
, PyObject
*fobj
)
2595 int newlinetypes
= 0;
2597 int univ_newline
= 1;
2600 if (!PyFile_Check(fobj
)) {
2601 errno
= ENXIO
; /* What can you do... */
2604 univ_newline
= ((PyFileObject
*)fobj
)->f_univ_newline
;
2605 if ( !univ_newline
)
2606 return fgets(buf
, n
, stream
);
2607 newlinetypes
= ((PyFileObject
*)fobj
)->f_newlinetypes
;
2608 skipnextlf
= ((PyFileObject
*)fobj
)->f_skipnextlf
;
2611 c
= 'x'; /* Shut up gcc warning */
2612 while (--n
> 0 && (c
= GETC(stream
)) != EOF
) {
2616 /* Seeing a \n here with skipnextlf true
2617 ** means we saw a \r before.
2619 newlinetypes
|= NEWLINE_CRLF
;
2621 if (c
== EOF
) break;
2624 ** Note that c == EOF also brings us here,
2625 ** so we're okay if the last char in the file
2628 newlinetypes
|= NEWLINE_CR
;
2632 /* A \r is translated into a \n, and we skip
2633 ** an adjacent \n, if any. We don't set the
2634 ** newlinetypes flag until we've seen the next char.
2638 } else if ( c
== '\n') {
2639 newlinetypes
|= NEWLINE_LF
;
2642 if (c
== '\n') break;
2644 if ( c
== EOF
&& skipnextlf
)
2645 newlinetypes
|= NEWLINE_CR
;
2646 FUNLOCKFILE(stream
);
2649 ((PyFileObject
*)fobj
)->f_newlinetypes
= newlinetypes
;
2650 ((PyFileObject
*)fobj
)->f_skipnextlf
= skipnextlf
;
2651 } else if ( skipnextlf
) {
2652 /* If we have no file object we cannot save the
2653 ** skipnextlf flag. We have to readahead, which
2654 ** will cause a pause if we're reading from an
2655 ** interactive stream, but that is very unlikely
2656 ** unless we're doing something silly like
2657 ** execfile("/dev/tty").
2669 ** Py_UniversalNewlineFread is an fread variation that understands
2670 ** all of \r, \n and \r\n conventions.
2671 ** The stream should be opened in binary mode.
2672 ** fobj must be a PyFileObject. In this case there
2673 ** is no readahead but in stead a flag is used to skip a following
2674 ** \n on the next read. Also, if the file is open in binary mode
2675 ** the whole conversion is skipped. Finally, the routine keeps track of
2676 ** the different types of newlines seen.
2679 Py_UniversalNewlineFread(char *buf
, size_t n
,
2680 FILE *stream
, PyObject
*fobj
)
2683 PyFileObject
*f
= (PyFileObject
*)fobj
;
2684 int newlinetypes
, skipnextlf
;
2686 assert(buf
!= NULL
);
2687 assert(stream
!= NULL
);
2689 if (!fobj
|| !PyFile_Check(fobj
)) {
2690 errno
= ENXIO
; /* What can you do... */
2693 if (!f
->f_univ_newline
)
2694 return fread(buf
, 1, n
, stream
);
2695 newlinetypes
= f
->f_newlinetypes
;
2696 skipnextlf
= f
->f_skipnextlf
;
2697 /* Invariant: n is the number of bytes remaining to be filled
2705 nread
= fread(dst
, 1, n
, stream
);
2710 n
-= nread
; /* assuming 1 byte out for each in; will adjust */
2711 shortread
= n
!= 0; /* true iff EOF or error */
2715 /* Save as LF and set flag to skip next LF. */
2719 else if (skipnextlf
&& c
== '\n') {
2720 /* Skip LF, and remember we saw CR LF. */
2722 newlinetypes
|= NEWLINE_CRLF
;
2726 /* Normal char to be stored in buffer. Also
2727 * update the newlinetypes flag if either this
2728 * is an LF or the previous char was a CR.
2731 newlinetypes
|= NEWLINE_LF
;
2732 else if (skipnextlf
)
2733 newlinetypes
|= NEWLINE_CR
;
2739 /* If this is EOF, update type flags. */
2740 if (skipnextlf
&& feof(stream
))
2741 newlinetypes
|= NEWLINE_CR
;
2745 f
->f_newlinetypes
= newlinetypes
;
2746 f
->f_skipnextlf
= skipnextlf
;