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))
45 portable_lseek(int fd
, PyObject
*posobj
, int whence
);
47 /* Returns 0 on success, errno (which is < 0) on failure. */
49 internal_close(PyFileIOObject
*self
)
55 Py_BEGIN_ALLOW_THREADS
64 fileio_close(PyFileIOObject
*self
)
70 errno
= internal_close(self
);
72 PyErr_SetFromErrno(PyExc_IOError
);
80 fileio_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kews
)
84 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
86 self
= (PyFileIOObject
*) type
->tp_alloc(type
, 0);
93 self
->weakreflist
= NULL
;
96 return (PyObject
*) self
;
99 /* On Unix, open will succeed for directories.
100 In Python, there should be no file objects referring to
101 directories, so we need a check. */
104 dircheck(PyFileIOObject
* self
, char *name
)
106 #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
110 if (fstat(self
->fd
, &buf
) == 0 && S_ISDIR(buf
.st_mode
)) {
111 char *msg
= strerror(EISDIR
);
113 internal_close(self
);
115 exc
= PyObject_CallFunction(PyExc_IOError
, "(iss)",
117 PyErr_SetObject(PyExc_IOError
, exc
);
128 #if defined(HAVE_FSTAT)
130 if (!_PyVerify_fd(fd
) || (fstat(fd
, &buf
) < 0 && errno
== EBADF
)) {
132 char *msg
= strerror(EBADF
);
133 exc
= PyObject_CallFunction(PyExc_OSError
, "(is)",
135 PyErr_SetObject(PyExc_OSError
, exc
);
145 fileio_init(PyObject
*oself
, PyObject
*args
, PyObject
*kwds
)
147 PyFileIOObject
*self
= (PyFileIOObject
*) oself
;
148 static char *kwlist
[] = {"file", "mode", "closefd", NULL
};
153 Py_UNICODE
*widename
= NULL
;
156 int rwa
= 0, plus
= 0, append
= 0;
161 assert(PyFileIO_Check(oself
));
163 /* Have to close the existing file first. */
164 if (internal_close(self
) < 0)
168 if (PyArg_ParseTupleAndKeywords(args
, kwds
, "i|si:fileio",
169 kwlist
, &fd
, &mode
, &closefd
)) {
171 PyErr_SetString(PyExc_ValueError
,
172 "Negative filedescriptor");
181 #ifdef Py_WIN_WIDE_FILENAMES
182 if (GetVersion() < 0x80000000) {
183 /* On NT, so wide API available */
185 if (PyArg_ParseTupleAndKeywords(args
, kwds
, "U|si:fileio",
186 kwlist
, &po
, &mode
, &closefd
)
188 widename
= PyUnicode_AS_UNICODE(po
);
190 /* Drop the argument parsing error as narrow
191 strings are also valid. */
195 if (widename
== NULL
)
198 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "et|si:fileio",
200 Py_FileSystemDefaultEncoding
,
201 &name
, &mode
, &closefd
))
212 PyErr_SetString(PyExc_ValueError
,
213 "Must have exactly one of read/write/append mode");
224 flags
|= O_CREAT
| O_TRUNC
;
239 self
->readable
= self
->writable
= 1;
243 PyErr_Format(PyExc_ValueError
,
244 "invalid mode: %.200s", mode
);
252 if (self
->readable
&& self
->writable
)
254 else if (self
->readable
)
270 self
->closefd
= closefd
;
275 PyErr_SetString(PyExc_ValueError
,
276 "Cannot use closefd=False with file name");
280 Py_BEGIN_ALLOW_THREADS
283 if (widename
!= NULL
)
284 self
->fd
= _wopen(widename
, flags
, 0666);
287 self
->fd
= open(name
, flags
, 0666);
291 if (widename
!= NULL
)
292 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError
, widename
);
295 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, name
);
298 if(dircheck(self
, name
) < 0)
303 /* For consistent behaviour, we explicitly seek to the
304 end of file (otherwise, it might be done only on the
306 PyObject
*pos
= portable_lseek(self
->fd
, NULL
, 2);
323 fileio_dealloc(PyFileIOObject
*self
)
325 if (self
->weakreflist
!= NULL
)
326 PyObject_ClearWeakRefs((PyObject
*) self
);
328 if (self
->fd
>= 0 && self
->closefd
) {
329 errno
= internal_close(self
);
331 PySys_WriteStderr("close failed: [Errno %d] %s\n",
332 errno
, strerror(errno
));
336 Py_TYPE(self
)->tp_free((PyObject
*)self
);
342 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file");
347 err_mode(char *action
)
349 PyErr_Format(PyExc_ValueError
, "File not open for %s", action
);
354 fileio_fileno(PyFileIOObject
*self
)
358 return PyInt_FromLong((long) self
->fd
);
362 fileio_readable(PyFileIOObject
*self
)
366 return PyBool_FromLong((long) self
->readable
);
370 fileio_writable(PyFileIOObject
*self
)
374 return PyBool_FromLong((long) self
->writable
);
378 fileio_seekable(PyFileIOObject
*self
)
382 if (self
->seekable
< 0) {
384 Py_BEGIN_ALLOW_THREADS
385 ret
= lseek(self
->fd
, 0, SEEK_CUR
);
392 return PyBool_FromLong((long) self
->seekable
);
396 fileio_readinto(PyFileIOObject
*self
, PyObject
*args
)
404 return err_mode("reading");
406 if (!PyArg_ParseTuple(args
, "w*", &pbuf
))
409 Py_BEGIN_ALLOW_THREADS
411 n
= read(self
->fd
, pbuf
.buf
, pbuf
.len
);
413 PyBuffer_Release(&pbuf
);
417 PyErr_SetFromErrno(PyExc_IOError
);
421 return PyLong_FromSsize_t(n
);
424 #define DEFAULT_BUFFER_SIZE (8*1024)
427 fileio_readall(PyFileIOObject
*self
)
430 Py_ssize_t total
= 0;
433 result
= PyString_FromStringAndSize(NULL
, DEFAULT_BUFFER_SIZE
);
438 Py_ssize_t newsize
= total
+ DEFAULT_BUFFER_SIZE
;
439 if (PyString_GET_SIZE(result
) < newsize
) {
440 if (_PyString_Resize(&result
, newsize
) < 0) {
449 Py_BEGIN_ALLOW_THREADS
452 PyString_AS_STRING(result
) + total
,
460 if (errno
== EAGAIN
) {
465 PyErr_SetFromErrno(PyExc_IOError
);
471 if (PyString_GET_SIZE(result
) > total
) {
472 if (_PyString_Resize(&result
, total
) < 0) {
473 /* This should never happen, but just in case */
482 fileio_read(PyFileIOObject
*self
, PyObject
*args
)
486 Py_ssize_t size
= -1;
492 return err_mode("reading");
494 if (!PyArg_ParseTuple(args
, "|n", &size
))
498 return fileio_readall(self
);
501 bytes
= PyString_FromStringAndSize(NULL
, size
);
504 ptr
= PyString_AS_STRING(bytes
);
506 Py_BEGIN_ALLOW_THREADS
508 n
= read(self
->fd
, ptr
, size
);
514 PyErr_SetFromErrno(PyExc_IOError
);
519 if (_PyString_Resize(&bytes
, n
) < 0) {
525 return (PyObject
*) bytes
;
529 fileio_write(PyFileIOObject
*self
, PyObject
*args
)
537 return err_mode("writing");
539 if (!PyArg_ParseTuple(args
, "s*", &pbuf
))
542 Py_BEGIN_ALLOW_THREADS
544 n
= write(self
->fd
, pbuf
.buf
, pbuf
.len
);
547 PyBuffer_Release(&pbuf
);
552 PyErr_SetFromErrno(PyExc_IOError
);
556 return PyLong_FromSsize_t(n
);
559 /* XXX Windows support below is likely incomplete */
561 #if defined(MS_WIN64) || defined(MS_WINDOWS)
562 typedef PY_LONG_LONG Py_off_t
;
564 typedef off_t Py_off_t
;
567 /* Cribbed from posix_lseek() */
569 portable_lseek(int fd
, PyObject
*posobj
, int whence
)
574 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
577 case 0: whence
= SEEK_SET
; break;
580 case 1: whence
= SEEK_CUR
; break;
583 case 2: whence
= SEEK_END
; break;
586 #endif /* SEEK_SET */
591 if(PyFloat_Check(posobj
)) {
592 PyErr_SetString(PyExc_TypeError
, "an integer is required");
595 #if defined(HAVE_LARGEFILE_SUPPORT)
596 pos
= PyLong_AsLongLong(posobj
);
598 pos
= PyLong_AsLong(posobj
);
600 if (PyErr_Occurred())
604 Py_BEGIN_ALLOW_THREADS
605 #if defined(MS_WIN64) || defined(MS_WINDOWS)
606 res
= _lseeki64(fd
, pos
, whence
);
608 res
= lseek(fd
, pos
, whence
);
612 return PyErr_SetFromErrno(PyExc_IOError
);
614 #if defined(HAVE_LARGEFILE_SUPPORT)
615 return PyLong_FromLongLong(res
);
617 return PyLong_FromLong(res
);
622 fileio_seek(PyFileIOObject
*self
, PyObject
*args
)
630 if (!PyArg_ParseTuple(args
, "O|i", &posobj
, &whence
))
633 return portable_lseek(self
->fd
, posobj
, whence
);
637 fileio_tell(PyFileIOObject
*self
, PyObject
*args
)
642 return portable_lseek(self
->fd
, NULL
, 1);
645 #ifdef HAVE_FTRUNCATE
647 fileio_truncate(PyFileIOObject
*self
, PyObject
*args
)
649 PyObject
*posobj
= NULL
;
658 return err_mode("writing");
660 if (!PyArg_ParseTuple(args
, "|O", &posobj
))
663 if (posobj
== Py_None
|| posobj
== NULL
) {
664 /* Get the current position. */
665 posobj
= portable_lseek(fd
, NULL
, 1);
670 /* Move to the position to be truncated. */
671 posobj
= portable_lseek(fd
, posobj
, 0);
674 #if defined(HAVE_LARGEFILE_SUPPORT)
675 pos
= PyLong_AsLongLong(posobj
);
677 pos
= PyLong_AsLong(posobj
);
679 if (PyErr_Occurred())
683 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
684 so don't even try using it. */
688 /* Truncate. Note that this may grow the file! */
689 Py_BEGIN_ALLOW_THREADS
691 hFile
= (HANDLE
)_get_osfhandle(fd
);
692 ret
= hFile
== (HANDLE
)-1;
694 ret
= SetEndOfFile(hFile
) == 0;
701 Py_BEGIN_ALLOW_THREADS
703 ret
= ftruncate(fd
, pos
);
705 #endif /* !MS_WINDOWS */
708 PyErr_SetFromErrno(PyExc_IOError
);
717 mode_string(PyFileIOObject
*self
)
719 if (self
->readable
) {
730 fileio_repr(PyFileIOObject
*self
)
733 return PyString_FromFormat("_fileio._FileIO(-1)");
735 return PyString_FromFormat("_fileio._FileIO(%d, '%s')",
736 self
->fd
, mode_string(self
));
740 fileio_isatty(PyFileIOObject
*self
)
746 Py_BEGIN_ALLOW_THREADS
747 res
= isatty(self
->fd
);
749 return PyBool_FromLong(res
);
753 PyDoc_STRVAR(fileio_doc
,
754 "file(name: str[, mode: str]) -> file IO object\n"
756 "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
757 "writing or appending. The file will be created if it doesn't exist\n"
758 "when opened for writing or appending; it will be truncated when\n"
759 "opened for writing. Add a '+' to the mode to allow simultaneous\n"
760 "reading and writing.");
762 PyDoc_STRVAR(read_doc
,
763 "read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
765 "Only makes one system call, so less data may be returned than requested\n"
766 "In non-blocking mode, returns None if no data is available.\n"
767 "On end-of-file, returns ''.");
769 PyDoc_STRVAR(readall_doc
,
770 "readall() -> bytes. read all data from the file, returned as bytes.\n"
772 "In non-blocking mode, returns as much as is immediately available,\n"
773 "or None if no data is available. On end-of-file, returns ''.");
775 PyDoc_STRVAR(write_doc
,
776 "write(b: bytes) -> int. Write bytes b to file, return number written.\n"
778 "Only makes one system call, so not all of the data may be written.\n"
779 "The number of bytes actually written is returned.");
781 PyDoc_STRVAR(fileno_doc
,
782 "fileno() -> int. \"file descriptor\".\n"
784 "This is needed for lower-level file interfaces, such the fcntl module.");
786 PyDoc_STRVAR(seek_doc
,
787 "seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
789 "Argument offset is a byte count. Optional argument whence defaults to\n"
790 "0 (offset from start of file, offset should be >= 0); other values are 1\n"
791 "(move relative to current position, positive or negative), and 2 (move\n"
792 "relative to end of file, usually negative, although many platforms allow\n"
793 "seeking beyond the end of a file)."
795 "Note that not all file objects are seekable.");
797 #ifdef HAVE_FTRUNCATE
798 PyDoc_STRVAR(truncate_doc
,
799 "truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
801 "Size defaults to the current file position, as returned by tell()."
802 "The current file position is changed to the value of size.");
805 PyDoc_STRVAR(tell_doc
,
806 "tell() -> int. Current file position");
808 PyDoc_STRVAR(readinto_doc
,
809 "readinto() -> Undocumented. Don't use this; it may go away.");
811 PyDoc_STRVAR(close_doc
,
812 "close() -> None. Close the file.\n"
814 "A closed file cannot be used for further I/O operations. close() may be\n"
815 "called more than once without error. Changes the fileno to -1.");
817 PyDoc_STRVAR(isatty_doc
,
818 "isatty() -> bool. True if the file is connected to a tty device.");
820 PyDoc_STRVAR(seekable_doc
,
821 "seekable() -> bool. True if file supports random-access.");
823 PyDoc_STRVAR(readable_doc
,
824 "readable() -> bool. True if file was opened in a read mode.");
826 PyDoc_STRVAR(writable_doc
,
827 "writable() -> bool. True if file was opened in a write mode.");
829 static PyMethodDef fileio_methods
[] = {
830 {"read", (PyCFunction
)fileio_read
, METH_VARARGS
, read_doc
},
831 {"readall", (PyCFunction
)fileio_readall
, METH_NOARGS
, readall_doc
},
832 {"readinto", (PyCFunction
)fileio_readinto
, METH_VARARGS
, readinto_doc
},
833 {"write", (PyCFunction
)fileio_write
, METH_VARARGS
, write_doc
},
834 {"seek", (PyCFunction
)fileio_seek
, METH_VARARGS
, seek_doc
},
835 {"tell", (PyCFunction
)fileio_tell
, METH_VARARGS
, tell_doc
},
836 #ifdef HAVE_FTRUNCATE
837 {"truncate", (PyCFunction
)fileio_truncate
, METH_VARARGS
, truncate_doc
},
839 {"close", (PyCFunction
)fileio_close
, METH_NOARGS
, close_doc
},
840 {"seekable", (PyCFunction
)fileio_seekable
, METH_NOARGS
, seekable_doc
},
841 {"readable", (PyCFunction
)fileio_readable
, METH_NOARGS
, readable_doc
},
842 {"writable", (PyCFunction
)fileio_writable
, METH_NOARGS
, writable_doc
},
843 {"fileno", (PyCFunction
)fileio_fileno
, METH_NOARGS
, fileno_doc
},
844 {"isatty", (PyCFunction
)fileio_isatty
, METH_NOARGS
, isatty_doc
},
845 {NULL
, NULL
} /* sentinel */
848 /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
851 get_closed(PyFileIOObject
*self
, void *closure
)
853 return PyBool_FromLong((long)(self
->fd
< 0));
857 get_closefd(PyFileIOObject
*self
, void *closure
)
859 return PyBool_FromLong((long)(self
->closefd
));
863 get_mode(PyFileIOObject
*self
, void *closure
)
865 return PyString_FromString(mode_string(self
));
868 static PyGetSetDef fileio_getsetlist
[] = {
869 {"closed", (getter
)get_closed
, NULL
, "True if the file is closed"},
870 {"closefd", (getter
)get_closefd
, NULL
,
871 "True if the file descriptor will be closed"},
872 {"mode", (getter
)get_mode
, NULL
, "String giving the file mode"},
876 PyTypeObject PyFileIO_Type
= {
877 PyVarObject_HEAD_INIT(NULL
, 0)
879 sizeof(PyFileIOObject
),
881 (destructor
)fileio_dealloc
, /* tp_dealloc */
886 (reprfunc
)fileio_repr
, /* tp_repr */
887 0, /* tp_as_number */
888 0, /* tp_as_sequence */
889 0, /* tp_as_mapping */
893 PyObject_GenericGetAttr
, /* tp_getattro */
895 0, /* tp_as_buffer */
896 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
897 fileio_doc
, /* tp_doc */
900 0, /* tp_richcompare */
901 offsetof(PyFileIOObject
, weakreflist
), /* tp_weaklistoffset */
904 fileio_methods
, /* tp_methods */
906 fileio_getsetlist
, /* tp_getset */
909 0, /* tp_descr_get */
910 0, /* tp_descr_set */
911 0, /* tp_dictoffset */
912 fileio_init
, /* tp_init */
913 PyType_GenericAlloc
, /* tp_alloc */
914 fileio_new
, /* tp_new */
915 PyObject_Del
, /* tp_free */
918 static PyMethodDef module_methods
[] = {
925 PyObject
*m
; /* a module object */
927 m
= Py_InitModule3("_fileio", module_methods
,
928 "Fast implementation of io.FileIO.");
931 if (PyType_Ready(&PyFileIO_Type
) < 0)
933 Py_INCREF(&PyFileIO_Type
);
934 PyModule_AddObject(m
, "_FileIO", (PyObject
*) &PyFileIO_Type
);