blob: bf527073481119ff77bbb3e2e89159fb36c1cd26 [file] [log] [blame]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
5#include <sys/types.h>
6#include <sys/stat.h>
7#include <fcntl.h>
8#include <stddef.h> /* For offsetof */
9
10/*
11 * Known likely problems:
12 *
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
17 *
18 * To Do:
19 *
20 * - autoconfify header file inclusion
21 */
22
23#ifdef MS_WINDOWS
24/* can simulate truncate with Win32 API functions; see file_truncate */
25#define HAVE_FTRUNCATE
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28#endif
29
30typedef struct {
31 PyObject_HEAD
32 int fd;
33 unsigned readable : 1;
34 unsigned writable : 1;
35 int seekable : 2; /* -1 means unknown */
36 int closefd : 1;
37 PyObject *weakreflist;
38} PyFileIOObject;
39
40PyTypeObject PyFileIO_Type;
41
42#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
43
44/* Returns 0 on success, errno (which is < 0) on failure. */
45static int
46internal_close(PyFileIOObject *self)
47{
48 int save_errno = 0;
49 if (self->fd >= 0) {
50 int fd = self->fd;
51 self->fd = -1;
52 Py_BEGIN_ALLOW_THREADS
53 if (close(fd) < 0)
54 save_errno = errno;
55 Py_END_ALLOW_THREADS
56 }
57 return save_errno;
58}
59
60static PyObject *
61fileio_close(PyFileIOObject *self)
62{
63 if (!self->closefd) {
64 if (PyErr_WarnEx(PyExc_RuntimeWarning,
65 "Trying to close unclosable fd!", 3) < 0) {
66 return NULL;
67 }
68 Py_RETURN_NONE;
69 }
70 errno = internal_close(self);
71 if (errno < 0) {
72 PyErr_SetFromErrno(PyExc_IOError);
73 return NULL;
74 }
75
76 Py_RETURN_NONE;
77}
78
79static PyObject *
80fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews)
81{
82 PyFileIOObject *self;
83
84 assert(type != NULL && type->tp_alloc != NULL);
85
86 self = (PyFileIOObject *) type->tp_alloc(type, 0);
87 if (self != NULL) {
88 self->fd = -1;
89 self->weakreflist = NULL;
90 }
91
92 return (PyObject *) self;
93}
94
95/* On Unix, open will succeed for directories.
96 In Python, there should be no file objects referring to
97 directories, so we need a check. */
98
99static int
100dircheck(PyFileIOObject* self)
101{
102#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
103 struct stat buf;
104 if (self->fd < 0)
105 return 0;
106 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
107#ifdef HAVE_STRERROR
108 char *msg = strerror(EISDIR);
109#else
110 char *msg = "Is a directory";
111#endif
112 PyObject *exc;
113 internal_close(self);
114
115 exc = PyObject_CallFunction(PyExc_IOError, "(is)",
116 EISDIR, msg);
117 PyErr_SetObject(PyExc_IOError, exc);
118 Py_XDECREF(exc);
119 return -1;
120 }
121#endif
122 return 0;
123}
124
125
126static int
127fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
128{
129 PyFileIOObject *self = (PyFileIOObject *) oself;
130 static char *kwlist[] = {"file", "mode", "closefd", NULL};
131 char *name = NULL;
132 char *mode = "r";
133 char *s;
134#ifdef MS_WINDOWS
135 Py_UNICODE *widename = NULL;
136#endif
137 int ret = 0;
138 int rwa = 0, plus = 0, append = 0;
139 int flags = 0;
140 int fd = -1;
141 int closefd = 1;
142
143 assert(PyFileIO_Check(oself));
144 if (self->fd >= 0) {
145 /* Have to close the existing file first. */
146 if (internal_close(self) < 0)
147 return -1;
148 }
149
150 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio",
151 kwlist, &fd, &mode, &closefd)) {
152 if (fd < 0) {
153 PyErr_SetString(PyExc_ValueError,
154 "Negative filedescriptor");
155 return -1;
156 }
157 }
158 else {
159 PyErr_Clear();
160
161#ifdef Py_WIN_WIDE_FILENAMES
162 if (GetVersion() < 0x80000000) {
163 /* On NT, so wide API available */
164 PyObject *po;
165 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio",
166 kwlist, &po, &mode, &closefd)
167 ) {
168 widename = PyUnicode_AS_UNICODE(po);
169 } else {
170 /* Drop the argument parsing error as narrow
171 strings are also valid. */
172 PyErr_Clear();
173 }
174 }
175 if (widename == NULL)
176#endif
177 {
178 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio",
179 kwlist,
180 Py_FileSystemDefaultEncoding,
181 &name, &mode, &closefd))
182 goto error;
183 }
184 }
185
186 self->readable = self->writable = 0;
187 self->seekable = -1;
188 s = mode;
189 while (*s) {
190 switch (*s++) {
191 case 'r':
192 if (rwa) {
193 bad_mode:
194 PyErr_SetString(PyExc_ValueError,
195 "Must have exactly one of read/write/append mode");
196 goto error;
197 }
198 rwa = 1;
199 self->readable = 1;
200 break;
201 case 'w':
202 if (rwa)
203 goto bad_mode;
204 rwa = 1;
205 self->writable = 1;
206 flags |= O_CREAT | O_TRUNC;
207 break;
208 case 'a':
209 if (rwa)
210 goto bad_mode;
211 rwa = 1;
212 self->writable = 1;
213 flags |= O_CREAT;
214 append = 1;
215 break;
216 case '+':
217 if (plus)
218 goto bad_mode;
219 self->readable = self->writable = 1;
220 plus = 1;
221 break;
222 default:
223 PyErr_Format(PyExc_ValueError,
224 "invalid mode: %.200s", mode);
225 goto error;
226 }
227 }
228
229 if (!rwa)
230 goto bad_mode;
231
232 if (self->readable && self->writable)
233 flags |= O_RDWR;
234 else if (self->readable)
235 flags |= O_RDONLY;
236 else
237 flags |= O_WRONLY;
238
239#ifdef O_BINARY
240 flags |= O_BINARY;
241#endif
242
243#ifdef O_APPEND
244 if (append)
245 flags |= O_APPEND;
246#endif
247
248 if (fd >= 0) {
249 self->fd = fd;
250 self->closefd = closefd;
251 }
252 else {
253 self->closefd = 1;
254 if (!closefd) {
255 PyErr_SetString(PyExc_ValueError,
256 "Cannot use closefd=True with file name");
257 goto error;
258 }
259
260 Py_BEGIN_ALLOW_THREADS
261 errno = 0;
262#ifdef MS_WINDOWS
263 if (widename != NULL)
264 self->fd = _wopen(widename, flags, 0666);
265 else
266#endif
267 self->fd = open(name, flags, 0666);
268 Py_END_ALLOW_THREADS
269 if (self->fd < 0 || dircheck(self) < 0) {
270#ifdef MS_WINDOWS
271 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
272#else
273 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
274#endif
275 goto error;
276 }
277 }
278
279 goto done;
280
281 error:
282 ret = -1;
283
284 done:
285 PyMem_Free(name);
286 return ret;
287}
288
289static void
290fileio_dealloc(PyFileIOObject *self)
291{
292 if (self->weakreflist != NULL)
293 PyObject_ClearWeakRefs((PyObject *) self);
294
295 if (self->fd >= 0 && self->closefd) {
296 errno = internal_close(self);
297 if (errno < 0) {
298#ifdef HAVE_STRERROR
299 PySys_WriteStderr("close failed: [Errno %d] %s\n",
300 errno, strerror(errno));
301#else
302 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
303#endif
304 }
305 }
306
307 Py_TYPE(self)->tp_free((PyObject *)self);
308}
309
310static PyObject *
311err_closed(void)
312{
313 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
314 return NULL;
315}
316
317static PyObject *
318err_mode(char *action)
319{
320 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
321 return NULL;
322}
323
324static PyObject *
325fileio_fileno(PyFileIOObject *self)
326{
327 if (self->fd < 0)
328 return err_closed();
329 return PyInt_FromLong((long) self->fd);
330}
331
332static PyObject *
333fileio_readable(PyFileIOObject *self)
334{
335 if (self->fd < 0)
336 return err_closed();
337 return PyBool_FromLong((long) self->readable);
338}
339
340static PyObject *
341fileio_writable(PyFileIOObject *self)
342{
343 if (self->fd < 0)
344 return err_closed();
345 return PyBool_FromLong((long) self->writable);
346}
347
348static PyObject *
349fileio_seekable(PyFileIOObject *self)
350{
351 if (self->fd < 0)
352 return err_closed();
353 if (self->seekable < 0) {
354 int ret;
355 Py_BEGIN_ALLOW_THREADS
356 ret = lseek(self->fd, 0, SEEK_CUR);
357 Py_END_ALLOW_THREADS
358 if (ret < 0)
359 self->seekable = 0;
360 else
361 self->seekable = 1;
362 }
363 return PyBool_FromLong((long) self->seekable);
364}
365
366static PyObject *
367fileio_readinto(PyFileIOObject *self, PyObject *args)
368{
369 char *ptr;
370 Py_ssize_t n;
371
372 if (self->fd < 0)
373 return err_closed();
374 if (!self->readable)
375 return err_mode("reading");
376
377 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
378 return NULL;
379
380 Py_BEGIN_ALLOW_THREADS
381 errno = 0;
382 n = read(self->fd, ptr, n);
383 Py_END_ALLOW_THREADS
384 if (n < 0) {
385 if (errno == EAGAIN)
386 Py_RETURN_NONE;
387 PyErr_SetFromErrno(PyExc_IOError);
388 return NULL;
389 }
390
391 return PyLong_FromSsize_t(n);
392}
393
394#define DEFAULT_BUFFER_SIZE (8*1024)
395
396static PyObject *
397fileio_readall(PyFileIOObject *self)
398{
399 PyObject *result;
400 Py_ssize_t total = 0;
401 int n;
402
403 result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
404 if (result == NULL)
405 return NULL;
406
407 while (1) {
408 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
409 if (PyString_GET_SIZE(result) < newsize) {
410 if (_PyString_Resize(&result, newsize) < 0) {
411 if (total == 0) {
412 Py_DECREF(result);
413 return NULL;
414 }
415 PyErr_Clear();
416 break;
417 }
418 }
419 Py_BEGIN_ALLOW_THREADS
420 errno = 0;
421 n = read(self->fd,
422 PyString_AS_STRING(result) + total,
423 newsize - total);
424 Py_END_ALLOW_THREADS
425 if (n == 0)
426 break;
427 if (n < 0) {
428 if (total > 0)
429 break;
430 if (errno == EAGAIN) {
431 Py_DECREF(result);
432 Py_RETURN_NONE;
433 }
434 Py_DECREF(result);
435 PyErr_SetFromErrno(PyExc_IOError);
436 return NULL;
437 }
438 total += n;
439 }
440
441 if (PyString_GET_SIZE(result) > total) {
442 if (_PyString_Resize(&result, total) < 0) {
443 /* This should never happen, but just in case */
444 Py_DECREF(result);
445 return NULL;
446 }
447 }
448 return result;
449}
450
451static PyObject *
452fileio_read(PyFileIOObject *self, PyObject *args)
453{
454 char *ptr;
455 Py_ssize_t n;
456 Py_ssize_t size = -1;
457 PyObject *bytes;
458
459 if (self->fd < 0)
460 return err_closed();
461 if (!self->readable)
462 return err_mode("reading");
463
464 if (!PyArg_ParseTuple(args, "|n", &size))
465 return NULL;
466
467 if (size < 0) {
468 return fileio_readall(self);
469 }
470
471 bytes = PyString_FromStringAndSize(NULL, size);
472 if (bytes == NULL)
473 return NULL;
474 ptr = PyString_AS_STRING(bytes);
475
476 Py_BEGIN_ALLOW_THREADS
477 errno = 0;
478 n = read(self->fd, ptr, size);
479 Py_END_ALLOW_THREADS
480
481 if (n < 0) {
482 if (errno == EAGAIN)
483 Py_RETURN_NONE;
484 PyErr_SetFromErrno(PyExc_IOError);
485 return NULL;
486 }
487
488 if (n != size) {
489 if (_PyString_Resize(&bytes, n) < 0) {
490 Py_DECREF(bytes);
491 return NULL;
492 }
493 }
494
495 return (PyObject *) bytes;
496}
497
498static PyObject *
499fileio_write(PyFileIOObject *self, PyObject *args)
500{
501 Py_ssize_t n;
502 char *ptr;
503
504 if (self->fd < 0)
505 return err_closed();
506 if (!self->writable)
507 return err_mode("writing");
508
509 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
510 return NULL;
511
512 Py_BEGIN_ALLOW_THREADS
513 errno = 0;
514 n = write(self->fd, ptr, n);
515 Py_END_ALLOW_THREADS
516
517 if (n < 0) {
518 if (errno == EAGAIN)
519 Py_RETURN_NONE;
520 PyErr_SetFromErrno(PyExc_IOError);
521 return NULL;
522 }
523
524 return PyLong_FromSsize_t(n);
525}
526
527/* XXX Windows support below is likely incomplete */
528
529#if defined(MS_WIN64) || defined(MS_WINDOWS)
530typedef PY_LONG_LONG Py_off_t;
531#else
532typedef off_t Py_off_t;
533#endif
534
535/* Cribbed from posix_lseek() */
536static PyObject *
537portable_lseek(int fd, PyObject *posobj, int whence)
538{
539 Py_off_t pos, res;
540
541#ifdef SEEK_SET
542 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
543 switch (whence) {
544#if SEEK_SET != 0
545 case 0: whence = SEEK_SET; break;
546#endif
547#if SEEK_CUR != 1
548 case 1: whence = SEEK_CUR; break;
549#endif
550#if SEEL_END != 2
551 case 2: whence = SEEK_END; break;
552#endif
553 }
554#endif /* SEEK_SET */
555
556 if (posobj == NULL)
557 pos = 0;
558 else {
559 if(PyFloat_Check(posobj)) {
560 PyErr_SetString(PyExc_TypeError, "an integer is required");
561 return NULL;
562 }
563#if !defined(HAVE_LARGEFILE_SUPPORT)
564 pos = PyLong_AsLong(posobj);
565#else
566 pos = PyLong_Check(posobj) ?
567 PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj);
568#endif
569 if (PyErr_Occurred())
570 return NULL;
571 }
572
573 Py_BEGIN_ALLOW_THREADS
574#if defined(MS_WIN64) || defined(MS_WINDOWS)
575 res = _lseeki64(fd, pos, whence);
576#else
577 res = lseek(fd, pos, whence);
578#endif
579 Py_END_ALLOW_THREADS
580 if (res < 0)
581 return PyErr_SetFromErrno(PyExc_IOError);
582
583#if !defined(HAVE_LARGEFILE_SUPPORT)
584 return PyLong_FromLong(res);
585#else
586 return PyLong_FromLongLong(res);
587#endif
588}
589
590static PyObject *
591fileio_seek(PyFileIOObject *self, PyObject *args)
592{
593 PyObject *posobj;
594 int whence = 0;
595
596 if (self->fd < 0)
597 return err_closed();
598
599 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
600 return NULL;
601
602 return portable_lseek(self->fd, posobj, whence);
603}
604
605static PyObject *
606fileio_tell(PyFileIOObject *self, PyObject *args)
607{
608 if (self->fd < 0)
609 return err_closed();
610
611 return portable_lseek(self->fd, NULL, 1);
612}
613
614#ifdef HAVE_FTRUNCATE
615static PyObject *
616fileio_truncate(PyFileIOObject *self, PyObject *args)
617{
618 PyObject *posobj = NULL;
619 Py_off_t pos;
620 int ret;
621 int fd;
622
623 fd = self->fd;
624 if (fd < 0)
625 return err_closed();
626 if (!self->writable)
627 return err_mode("writing");
628
629 if (!PyArg_ParseTuple(args, "|O", &posobj))
630 return NULL;
631
632 if (posobj == Py_None || posobj == NULL) {
633 posobj = portable_lseek(fd, NULL, 1);
634 if (posobj == NULL)
635 return NULL;
636 }
637 else {
638 Py_INCREF(posobj);
639 }
640
641#if !defined(HAVE_LARGEFILE_SUPPORT)
642 pos = PyLong_AsLong(posobj);
643#else
644 pos = PyLong_Check(posobj) ?
645 PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj);
646#endif
647 if (PyErr_Occurred()) {
648 Py_DECREF(posobj);
649 return NULL;
650 }
651
652#ifdef MS_WINDOWS
653 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
654 so don't even try using it. */
655 {
656 HANDLE hFile;
657 PyObject *pos2, *oldposobj;
658
659 /* store the current position */
660 oldposobj = portable_lseek(self->fd, NULL, 1);
661 if (oldposobj == NULL) {
662 Py_DECREF(posobj);
663 return NULL;
664 }
665
666 /* Have to move current pos to desired endpoint on Windows. */
667 errno = 0;
668 pos2 = portable_lseek(fd, posobj, SEEK_SET);
669 if (pos2 == NULL) {
670 Py_DECREF(posobj);
671 Py_DECREF(oldposobj);
672 return NULL;
673 }
674 Py_DECREF(pos2);
675
676 /* Truncate. Note that this may grow the file! */
677 Py_BEGIN_ALLOW_THREADS
678 errno = 0;
679 hFile = (HANDLE)_get_osfhandle(fd);
680 ret = hFile == (HANDLE)-1;
681 if (ret == 0) {
682 ret = SetEndOfFile(hFile) == 0;
683 if (ret)
684 errno = EACCES;
685 }
686 Py_END_ALLOW_THREADS
687
688 if (ret == 0) {
689 /* Move to the previous position in the file */
690 pos2 = portable_lseek(fd, oldposobj, SEEK_SET);
691 if (pos2 == NULL) {
692 Py_DECREF(posobj);
693 Py_DECREF(oldposobj);
694 return NULL;
695 }
696 }
697 Py_DECREF(pos2);
698 Py_DECREF(oldposobj);
699 }
700#else
701 Py_BEGIN_ALLOW_THREADS
702 errno = 0;
703 ret = ftruncate(fd, pos);
704 Py_END_ALLOW_THREADS
705#endif /* !MS_WINDOWS */
706
707 if (ret != 0) {
708 Py_DECREF(posobj);
709 PyErr_SetFromErrno(PyExc_IOError);
710 return NULL;
711 }
712
713 return posobj;
714}
715#endif
716
717static char *
718mode_string(PyFileIOObject *self)
719{
720 if (self->readable) {
721 if (self->writable)
722 return "r+";
723 else
724 return "r";
725 }
726 else
727 return "w";
728}
729
730static PyObject *
731fileio_repr(PyFileIOObject *self)
732{
733 if (self->fd < 0)
734 return PyString_FromFormat("_fileio._FileIO(-1)");
735
736 return PyString_FromFormat("_fileio._FileIO(%d, '%s')",
737 self->fd, mode_string(self));
738}
739
740static PyObject *
741fileio_isatty(PyFileIOObject *self)
742{
743 long res;
744
745 if (self->fd < 0)
746 return err_closed();
747 Py_BEGIN_ALLOW_THREADS
748 res = isatty(self->fd);
749 Py_END_ALLOW_THREADS
750 return PyBool_FromLong(res);
751}
752
753
754PyDoc_STRVAR(fileio_doc,
755"file(name: str[, mode: str]) -> file IO object\n"
756"\n"
757"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
758"writing or appending. The file will be created if it doesn't exist\n"
759"when opened for writing or appending; it will be truncated when\n"
760"opened for writing. Add a '+' to the mode to allow simultaneous\n"
761"reading and writing.");
762
763PyDoc_STRVAR(read_doc,
764"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
765"\n"
766"Only makes one system call, so less data may be returned than requested\n"
767"In non-blocking mode, returns None if no data is available.\n"
768"On end-of-file, returns ''.");
769
770PyDoc_STRVAR(readall_doc,
771"readall() -> bytes. read all data from the file, returned as bytes.\n"
772"\n"
773"In non-blocking mode, returns as much as is immediately available,\n"
774"or None if no data is available. On end-of-file, returns ''.");
775
776PyDoc_STRVAR(write_doc,
777"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
778"\n"
779"Only makes one system call, so not all of the data may be written.\n"
780"The number of bytes actually written is returned.");
781
782PyDoc_STRVAR(fileno_doc,
783"fileno() -> int. \"file descriptor\".\n"
784"\n"
785"This is needed for lower-level file interfaces, such the fcntl module.");
786
787PyDoc_STRVAR(seek_doc,
788"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
789"\n"
790"Argument offset is a byte count. Optional argument whence defaults to\n"
791"0 (offset from start of file, offset should be >= 0); other values are 1\n"
792"(move relative to current position, positive or negative), and 2 (move\n"
793"relative to end of file, usually negative, although many platforms allow\n"
794"seeking beyond the end of a file)."
795"\n"
796"Note that not all file objects are seekable.");
797
798#ifdef HAVE_FTRUNCATE
799PyDoc_STRVAR(truncate_doc,
800"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
801"\n"
802"Size defaults to the current file position, as returned by tell().");
803#endif
804
805PyDoc_STRVAR(tell_doc,
806"tell() -> int. Current file position");
807
808PyDoc_STRVAR(readinto_doc,
809"readinto() -> Undocumented. Don't use this; it may go away.");
810
811PyDoc_STRVAR(close_doc,
812"close() -> None. Close the file.\n"
813"\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.");
816
817PyDoc_STRVAR(isatty_doc,
818"isatty() -> bool. True if the file is connected to a tty device.");
819
820PyDoc_STRVAR(seekable_doc,
821"seekable() -> bool. True if file supports random-access.");
822
823PyDoc_STRVAR(readable_doc,
824"readable() -> bool. True if file was opened in a read mode.");
825
826PyDoc_STRVAR(writable_doc,
827"writable() -> bool. True if file was opened in a write mode.");
828
829static 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},
838#endif
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 */
846};
847
848/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
849
850static PyObject *
851get_closed(PyFileIOObject *self, void *closure)
852{
853 return PyBool_FromLong((long)(self->fd < 0));
854}
855
856static PyObject *
857get_mode(PyFileIOObject *self, void *closure)
858{
859 return PyString_FromString(mode_string(self));
860}
861
862static PyGetSetDef fileio_getsetlist[] = {
863 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
864 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
865 {0},
866};
867
868PyTypeObject PyFileIO_Type = {
869 PyVarObject_HEAD_INIT(&PyType_Type, 0)
870 "_FileIO",
871 sizeof(PyFileIOObject),
872 0,
873 (destructor)fileio_dealloc, /* tp_dealloc */
874 0, /* tp_print */
875 0, /* tp_getattr */
876 0, /* tp_setattr */
877 0, /* tp_compare */
878 (reprfunc)fileio_repr, /* tp_repr */
879 0, /* tp_as_number */
880 0, /* tp_as_sequence */
881 0, /* tp_as_mapping */
882 0, /* tp_hash */
883 0, /* tp_call */
884 0, /* tp_str */
885 PyObject_GenericGetAttr, /* tp_getattro */
886 0, /* tp_setattro */
887 0, /* tp_as_buffer */
888 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
889 fileio_doc, /* tp_doc */
890 0, /* tp_traverse */
891 0, /* tp_clear */
892 0, /* tp_richcompare */
893 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
894 0, /* tp_iter */
895 0, /* tp_iternext */
896 fileio_methods, /* tp_methods */
897 0, /* tp_members */
898 fileio_getsetlist, /* tp_getset */
899 0, /* tp_base */
900 0, /* tp_dict */
901 0, /* tp_descr_get */
902 0, /* tp_descr_set */
903 0, /* tp_dictoffset */
904 fileio_init, /* tp_init */
905 PyType_GenericAlloc, /* tp_alloc */
906 fileio_new, /* tp_new */
907 PyObject_Del, /* tp_free */
908};
909
910static PyMethodDef module_methods[] = {
911 {NULL, NULL}
912};
913
914PyMODINIT_FUNC
915init_fileio(void)
916{
917 PyObject *m; /* a module object */
918
919 m = Py_InitModule3("_fileio", module_methods,
920 "Fast implementation of io.FileIO.");
921 if (m == NULL)
922 return;
923 if (PyType_Ready(&PyFileIO_Type) < 0)
924 return;
925 Py_INCREF(&PyFileIO_Type);
926 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
927}