1 /* Author: Daniel Stutzbach */
3 #define PY_SSIZE_T_CLEAN
8 #include <stddef.h> /* For offsetof */
11 * Known likely problems:
13 * - Files larger then 2**32-1
14 * - Files with unicode filenames
15 * - Passing numbers greater than 2**32-1 when an integer is expected
16 * - Making it work on Windows and other oddball platforms
20 * - autoconfify header file inclusion
24 /* can simulate truncate with Win32 API functions; see file_truncate */
25 #define HAVE_FTRUNCATE
26 #define WIN32_LEAN_AND_MEAN
33 unsigned readable
: 1;
34 unsigned writable
: 1;
35 int seekable
: 2; /* -1 means unknown */
37 PyObject
*weakreflist
;
40 PyTypeObject PyFileIO_Type
;
42 #define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
44 /* Returns 0 on success, errno (which is < 0) on failure. */
46 internal_close(PyFileIOObject
*self
)
52 Py_BEGIN_ALLOW_THREADS
61 fileio_close(PyFileIOObject
*self
)
67 errno
= internal_close(self
);
69 PyErr_SetFromErrno(PyExc_IOError
);
77 fileio_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kews
)
81 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
83 self
= (PyFileIOObject
*) type
->tp_alloc(type
, 0);
90 self
->weakreflist
= NULL
;
93 return (PyObject
*) self
;
96 /* On Unix, open will succeed for directories.
97 In Python, there should be no file objects referring to
98 directories, so we need a check. */
101 dircheck(PyFileIOObject
* self
, char *name
)
103 #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
107 if (fstat(self
->fd
, &buf
) == 0 && S_ISDIR(buf
.st_mode
)) {
108 char *msg
= strerror(EISDIR
);
110 internal_close(self
);
112 exc
= PyObject_CallFunction(PyExc_IOError
, "(iss)",
114 PyErr_SetObject(PyExc_IOError
, exc
);
125 #if defined(HAVE_FSTAT)
127 if (fstat(fd
, &buf
) < 0 && errno
== EBADF
) {
129 char *msg
= strerror(EBADF
);
130 exc
= PyObject_CallFunction(PyExc_OSError
, "(is)",
132 PyErr_SetObject(PyExc_OSError
, exc
);
142 fileio_init(PyObject
*oself
, PyObject
*args
, PyObject
*kwds
)
144 PyFileIOObject
*self
= (PyFileIOObject
*) oself
;
145 static char *kwlist
[] = {"file", "mode", "closefd", NULL
};
150 Py_UNICODE
*widename
= NULL
;
153 int rwa
= 0, plus
= 0, append
= 0;
158 assert(PyFileIO_Check(oself
));
160 /* Have to close the existing file first. */
161 if (internal_close(self
) < 0)
165 if (PyArg_ParseTupleAndKeywords(args
, kwds
, "i|si:fileio",
166 kwlist
, &fd
, &mode
, &closefd
)) {
168 PyErr_SetString(PyExc_ValueError
,
169 "Negative filedescriptor");
178 #ifdef Py_WIN_WIDE_FILENAMES
179 if (GetVersion() < 0x80000000) {
180 /* On NT, so wide API available */
182 if (PyArg_ParseTupleAndKeywords(args
, kwds
, "U|si:fileio",
183 kwlist
, &po
, &mode
, &closefd
)
185 widename
= PyUnicode_AS_UNICODE(po
);
187 /* Drop the argument parsing error as narrow
188 strings are also valid. */
192 if (widename
== NULL
)
195 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "et|si:fileio",
197 Py_FileSystemDefaultEncoding
,
198 &name
, &mode
, &closefd
))
209 PyErr_SetString(PyExc_ValueError
,
210 "Must have exactly one of read/write/append mode");
221 flags
|= O_CREAT
| O_TRUNC
;
236 self
->readable
= self
->writable
= 1;
240 PyErr_Format(PyExc_ValueError
,
241 "invalid mode: %.200s", mode
);
249 if (self
->readable
&& self
->writable
)
251 else if (self
->readable
)
267 self
->closefd
= closefd
;
272 PyErr_SetString(PyExc_ValueError
,
273 "Cannot use closefd=False with file name");
277 Py_BEGIN_ALLOW_THREADS
280 if (widename
!= NULL
)
281 self
->fd
= _wopen(widename
, flags
, 0666);
284 self
->fd
= open(name
, flags
, 0666);
288 if (widename
!= NULL
)
289 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError
, widename
);
292 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, name
);
295 if(dircheck(self
, name
) < 0)
310 fileio_dealloc(PyFileIOObject
*self
)
312 if (self
->weakreflist
!= NULL
)
313 PyObject_ClearWeakRefs((PyObject
*) self
);
315 if (self
->fd
>= 0 && self
->closefd
) {
316 errno
= internal_close(self
);
318 PySys_WriteStderr("close failed: [Errno %d] %s\n",
319 errno
, strerror(errno
));
323 Py_TYPE(self
)->tp_free((PyObject
*)self
);
329 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file");
334 err_mode(char *action
)
336 PyErr_Format(PyExc_ValueError
, "File not open for %s", action
);
341 fileio_fileno(PyFileIOObject
*self
)
345 return PyInt_FromLong((long) self
->fd
);
349 fileio_readable(PyFileIOObject
*self
)
353 return PyBool_FromLong((long) self
->readable
);
357 fileio_writable(PyFileIOObject
*self
)
361 return PyBool_FromLong((long) self
->writable
);
365 fileio_seekable(PyFileIOObject
*self
)
369 if (self
->seekable
< 0) {
371 Py_BEGIN_ALLOW_THREADS
372 ret
= lseek(self
->fd
, 0, SEEK_CUR
);
379 return PyBool_FromLong((long) self
->seekable
);
383 fileio_readinto(PyFileIOObject
*self
, PyObject
*args
)
391 return err_mode("reading");
393 if (!PyArg_ParseTuple(args
, "w*", &pbuf
))
396 Py_BEGIN_ALLOW_THREADS
398 n
= read(self
->fd
, pbuf
.buf
, pbuf
.len
);
400 PyBuffer_Release(&pbuf
);
404 PyErr_SetFromErrno(PyExc_IOError
);
408 return PyLong_FromSsize_t(n
);
411 #define DEFAULT_BUFFER_SIZE (8*1024)
414 fileio_readall(PyFileIOObject
*self
)
417 Py_ssize_t total
= 0;
420 result
= PyString_FromStringAndSize(NULL
, DEFAULT_BUFFER_SIZE
);
425 Py_ssize_t newsize
= total
+ DEFAULT_BUFFER_SIZE
;
426 if (PyString_GET_SIZE(result
) < newsize
) {
427 if (_PyString_Resize(&result
, newsize
) < 0) {
436 Py_BEGIN_ALLOW_THREADS
439 PyString_AS_STRING(result
) + total
,
447 if (errno
== EAGAIN
) {
452 PyErr_SetFromErrno(PyExc_IOError
);
458 if (PyString_GET_SIZE(result
) > total
) {
459 if (_PyString_Resize(&result
, total
) < 0) {
460 /* This should never happen, but just in case */
469 fileio_read(PyFileIOObject
*self
, PyObject
*args
)
473 Py_ssize_t size
= -1;
479 return err_mode("reading");
481 if (!PyArg_ParseTuple(args
, "|n", &size
))
485 return fileio_readall(self
);
488 bytes
= PyString_FromStringAndSize(NULL
, size
);
491 ptr
= PyString_AS_STRING(bytes
);
493 Py_BEGIN_ALLOW_THREADS
495 n
= read(self
->fd
, ptr
, size
);
501 PyErr_SetFromErrno(PyExc_IOError
);
506 if (_PyString_Resize(&bytes
, n
) < 0) {
512 return (PyObject
*) bytes
;
516 fileio_write(PyFileIOObject
*self
, PyObject
*args
)
524 return err_mode("writing");
526 if (!PyArg_ParseTuple(args
, "s*", &pbuf
))
529 Py_BEGIN_ALLOW_THREADS
531 n
= write(self
->fd
, pbuf
.buf
, pbuf
.len
);
534 PyBuffer_Release(&pbuf
);
539 PyErr_SetFromErrno(PyExc_IOError
);
543 return PyLong_FromSsize_t(n
);
546 /* XXX Windows support below is likely incomplete */
548 #if defined(MS_WIN64) || defined(MS_WINDOWS)
549 typedef PY_LONG_LONG Py_off_t
;
551 typedef off_t Py_off_t
;
554 /* Cribbed from posix_lseek() */
556 portable_lseek(int fd
, PyObject
*posobj
, int whence
)
561 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
564 case 0: whence
= SEEK_SET
; break;
567 case 1: whence
= SEEK_CUR
; break;
570 case 2: whence
= SEEK_END
; break;
573 #endif /* SEEK_SET */
578 if(PyFloat_Check(posobj
)) {
579 PyErr_SetString(PyExc_TypeError
, "an integer is required");
582 #if defined(HAVE_LARGEFILE_SUPPORT)
583 pos
= PyLong_AsLongLong(posobj
);
585 pos
= PyLong_AsLong(posobj
);
587 if (PyErr_Occurred())
591 Py_BEGIN_ALLOW_THREADS
592 #if defined(MS_WIN64) || defined(MS_WINDOWS)
593 res
= _lseeki64(fd
, pos
, whence
);
595 res
= lseek(fd
, pos
, whence
);
599 return PyErr_SetFromErrno(PyExc_IOError
);
601 #if defined(HAVE_LARGEFILE_SUPPORT)
602 return PyLong_FromLongLong(res
);
604 return PyLong_FromLong(res
);
609 fileio_seek(PyFileIOObject
*self
, PyObject
*args
)
617 if (!PyArg_ParseTuple(args
, "O|i", &posobj
, &whence
))
620 return portable_lseek(self
->fd
, posobj
, whence
);
624 fileio_tell(PyFileIOObject
*self
, PyObject
*args
)
629 return portable_lseek(self
->fd
, NULL
, 1);
632 #ifdef HAVE_FTRUNCATE
634 fileio_truncate(PyFileIOObject
*self
, PyObject
*args
)
636 PyObject
*posobj
= NULL
;
645 return err_mode("writing");
647 if (!PyArg_ParseTuple(args
, "|O", &posobj
))
650 if (posobj
== Py_None
|| posobj
== NULL
) {
651 /* Get the current position. */
652 posobj
= portable_lseek(fd
, NULL
, 1);
657 /* Move to the position to be truncated. */
658 posobj
= portable_lseek(fd
, posobj
, 0);
661 #if defined(HAVE_LARGEFILE_SUPPORT)
662 pos
= PyLong_AsLongLong(posobj
);
664 pos
= PyLong_AsLong(posobj
);
666 if (PyErr_Occurred())
670 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
671 so don't even try using it. */
675 /* Truncate. Note that this may grow the file! */
676 Py_BEGIN_ALLOW_THREADS
678 hFile
= (HANDLE
)_get_osfhandle(fd
);
679 ret
= hFile
== (HANDLE
)-1;
681 ret
= SetEndOfFile(hFile
) == 0;
688 Py_BEGIN_ALLOW_THREADS
690 ret
= ftruncate(fd
, pos
);
692 #endif /* !MS_WINDOWS */
695 PyErr_SetFromErrno(PyExc_IOError
);
704 mode_string(PyFileIOObject
*self
)
706 if (self
->readable
) {
717 fileio_repr(PyFileIOObject
*self
)
720 return PyString_FromFormat("_fileio._FileIO(-1)");
722 return PyString_FromFormat("_fileio._FileIO(%d, '%s')",
723 self
->fd
, mode_string(self
));
727 fileio_isatty(PyFileIOObject
*self
)
733 Py_BEGIN_ALLOW_THREADS
734 res
= isatty(self
->fd
);
736 return PyBool_FromLong(res
);
740 PyDoc_STRVAR(fileio_doc
,
741 "file(name: str[, mode: str]) -> file IO object\n"
743 "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
744 "writing or appending. The file will be created if it doesn't exist\n"
745 "when opened for writing or appending; it will be truncated when\n"
746 "opened for writing. Add a '+' to the mode to allow simultaneous\n"
747 "reading and writing.");
749 PyDoc_STRVAR(read_doc
,
750 "read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
752 "Only makes one system call, so less data may be returned than requested\n"
753 "In non-blocking mode, returns None if no data is available.\n"
754 "On end-of-file, returns ''.");
756 PyDoc_STRVAR(readall_doc
,
757 "readall() -> bytes. read all data from the file, returned as bytes.\n"
759 "In non-blocking mode, returns as much as is immediately available,\n"
760 "or None if no data is available. On end-of-file, returns ''.");
762 PyDoc_STRVAR(write_doc
,
763 "write(b: bytes) -> int. Write bytes b to file, return number written.\n"
765 "Only makes one system call, so not all of the data may be written.\n"
766 "The number of bytes actually written is returned.");
768 PyDoc_STRVAR(fileno_doc
,
769 "fileno() -> int. \"file descriptor\".\n"
771 "This is needed for lower-level file interfaces, such the fcntl module.");
773 PyDoc_STRVAR(seek_doc
,
774 "seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
776 "Argument offset is a byte count. Optional argument whence defaults to\n"
777 "0 (offset from start of file, offset should be >= 0); other values are 1\n"
778 "(move relative to current position, positive or negative), and 2 (move\n"
779 "relative to end of file, usually negative, although many platforms allow\n"
780 "seeking beyond the end of a file)."
782 "Note that not all file objects are seekable.");
784 #ifdef HAVE_FTRUNCATE
785 PyDoc_STRVAR(truncate_doc
,
786 "truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
788 "Size defaults to the current file position, as returned by tell()."
789 "The current file position is changed to the value of size.");
792 PyDoc_STRVAR(tell_doc
,
793 "tell() -> int. Current file position");
795 PyDoc_STRVAR(readinto_doc
,
796 "readinto() -> Undocumented. Don't use this; it may go away.");
798 PyDoc_STRVAR(close_doc
,
799 "close() -> None. Close the file.\n"
801 "A closed file cannot be used for further I/O operations. close() may be\n"
802 "called more than once without error. Changes the fileno to -1.");
804 PyDoc_STRVAR(isatty_doc
,
805 "isatty() -> bool. True if the file is connected to a tty device.");
807 PyDoc_STRVAR(seekable_doc
,
808 "seekable() -> bool. True if file supports random-access.");
810 PyDoc_STRVAR(readable_doc
,
811 "readable() -> bool. True if file was opened in a read mode.");
813 PyDoc_STRVAR(writable_doc
,
814 "writable() -> bool. True if file was opened in a write mode.");
816 static PyMethodDef fileio_methods
[] = {
817 {"read", (PyCFunction
)fileio_read
, METH_VARARGS
, read_doc
},
818 {"readall", (PyCFunction
)fileio_readall
, METH_NOARGS
, readall_doc
},
819 {"readinto", (PyCFunction
)fileio_readinto
, METH_VARARGS
, readinto_doc
},
820 {"write", (PyCFunction
)fileio_write
, METH_VARARGS
, write_doc
},
821 {"seek", (PyCFunction
)fileio_seek
, METH_VARARGS
, seek_doc
},
822 {"tell", (PyCFunction
)fileio_tell
, METH_VARARGS
, tell_doc
},
823 #ifdef HAVE_FTRUNCATE
824 {"truncate", (PyCFunction
)fileio_truncate
, METH_VARARGS
, truncate_doc
},
826 {"close", (PyCFunction
)fileio_close
, METH_NOARGS
, close_doc
},
827 {"seekable", (PyCFunction
)fileio_seekable
, METH_NOARGS
, seekable_doc
},
828 {"readable", (PyCFunction
)fileio_readable
, METH_NOARGS
, readable_doc
},
829 {"writable", (PyCFunction
)fileio_writable
, METH_NOARGS
, writable_doc
},
830 {"fileno", (PyCFunction
)fileio_fileno
, METH_NOARGS
, fileno_doc
},
831 {"isatty", (PyCFunction
)fileio_isatty
, METH_NOARGS
, isatty_doc
},
832 {NULL
, NULL
} /* sentinel */
835 /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
838 get_closed(PyFileIOObject
*self
, void *closure
)
840 return PyBool_FromLong((long)(self
->fd
< 0));
844 get_closefd(PyFileIOObject
*self
, void *closure
)
846 return PyBool_FromLong((long)(self
->closefd
));
850 get_mode(PyFileIOObject
*self
, void *closure
)
852 return PyString_FromString(mode_string(self
));
855 static PyGetSetDef fileio_getsetlist
[] = {
856 {"closed", (getter
)get_closed
, NULL
, "True if the file is closed"},
857 {"closefd", (getter
)get_closefd
, NULL
,
858 "True if the file descriptor will be closed"},
859 {"mode", (getter
)get_mode
, NULL
, "String giving the file mode"},
863 PyTypeObject PyFileIO_Type
= {
864 PyVarObject_HEAD_INIT(NULL
, 0)
866 sizeof(PyFileIOObject
),
868 (destructor
)fileio_dealloc
, /* tp_dealloc */
873 (reprfunc
)fileio_repr
, /* tp_repr */
874 0, /* tp_as_number */
875 0, /* tp_as_sequence */
876 0, /* tp_as_mapping */
880 PyObject_GenericGetAttr
, /* tp_getattro */
882 0, /* tp_as_buffer */
883 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
884 fileio_doc
, /* tp_doc */
887 0, /* tp_richcompare */
888 offsetof(PyFileIOObject
, weakreflist
), /* tp_weaklistoffset */
891 fileio_methods
, /* tp_methods */
893 fileio_getsetlist
, /* tp_getset */
896 0, /* tp_descr_get */
897 0, /* tp_descr_set */
898 0, /* tp_dictoffset */
899 fileio_init
, /* tp_init */
900 PyType_GenericAlloc
, /* tp_alloc */
901 fileio_new
, /* tp_new */
902 PyObject_Del
, /* tp_free */
905 static PyMethodDef module_methods
[] = {
912 PyObject
*m
; /* a module object */
914 m
= Py_InitModule3("_fileio", module_methods
,
915 "Fast implementation of io.FileIO.");
918 if (PyType_Ready(&PyFileIO_Type
) < 0)
920 Py_INCREF(&PyFileIO_Type
);
921 PyModule_AddObject(m
, "_FileIO", (PyObject
*) &PyFileIO_Type
);