blob: b33b745ab1bbe6108ef778e2b6a5eef86ef3f895 [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)) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000107 char *msg = strerror(EISDIR);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000108 PyObject *exc;
109 internal_close(self);
110
111 exc = PyObject_CallFunction(PyExc_IOError, "(is)",
112 EISDIR, msg);
113 PyErr_SetObject(PyExc_IOError, exc);
114 Py_XDECREF(exc);
115 return -1;
116 }
117#endif
118 return 0;
119}
120
121
122static int
123fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
124{
125 PyFileIOObject *self = (PyFileIOObject *) oself;
126 static char *kwlist[] = {"file", "mode", "closefd", NULL};
127 char *name = NULL;
128 char *mode = "r";
129 char *s;
130#ifdef MS_WINDOWS
131 Py_UNICODE *widename = NULL;
132#endif
133 int ret = 0;
134 int rwa = 0, plus = 0, append = 0;
135 int flags = 0;
136 int fd = -1;
137 int closefd = 1;
138
139 assert(PyFileIO_Check(oself));
140 if (self->fd >= 0) {
141 /* Have to close the existing file first. */
142 if (internal_close(self) < 0)
143 return -1;
144 }
145
146 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio",
147 kwlist, &fd, &mode, &closefd)) {
148 if (fd < 0) {
149 PyErr_SetString(PyExc_ValueError,
150 "Negative filedescriptor");
151 return -1;
152 }
153 }
154 else {
155 PyErr_Clear();
156
157#ifdef Py_WIN_WIDE_FILENAMES
158 if (GetVersion() < 0x80000000) {
159 /* On NT, so wide API available */
160 PyObject *po;
161 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio",
162 kwlist, &po, &mode, &closefd)
163 ) {
164 widename = PyUnicode_AS_UNICODE(po);
165 } else {
166 /* Drop the argument parsing error as narrow
167 strings are also valid. */
168 PyErr_Clear();
169 }
170 }
171 if (widename == NULL)
172#endif
173 {
174 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio",
175 kwlist,
176 Py_FileSystemDefaultEncoding,
177 &name, &mode, &closefd))
Neal Norwitz901e4712008-08-24 22:03:05 +0000178 return -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000179 }
180 }
181
182 self->readable = self->writable = 0;
183 self->seekable = -1;
184 s = mode;
185 while (*s) {
186 switch (*s++) {
187 case 'r':
188 if (rwa) {
189 bad_mode:
190 PyErr_SetString(PyExc_ValueError,
191 "Must have exactly one of read/write/append mode");
192 goto error;
193 }
194 rwa = 1;
195 self->readable = 1;
196 break;
197 case 'w':
198 if (rwa)
199 goto bad_mode;
200 rwa = 1;
201 self->writable = 1;
202 flags |= O_CREAT | O_TRUNC;
203 break;
204 case 'a':
205 if (rwa)
206 goto bad_mode;
207 rwa = 1;
208 self->writable = 1;
209 flags |= O_CREAT;
210 append = 1;
211 break;
212 case '+':
213 if (plus)
214 goto bad_mode;
215 self->readable = self->writable = 1;
216 plus = 1;
217 break;
218 default:
219 PyErr_Format(PyExc_ValueError,
220 "invalid mode: %.200s", mode);
221 goto error;
222 }
223 }
224
225 if (!rwa)
226 goto bad_mode;
227
228 if (self->readable && self->writable)
229 flags |= O_RDWR;
230 else if (self->readable)
231 flags |= O_RDONLY;
232 else
233 flags |= O_WRONLY;
234
235#ifdef O_BINARY
236 flags |= O_BINARY;
237#endif
238
239#ifdef O_APPEND
240 if (append)
241 flags |= O_APPEND;
242#endif
243
244 if (fd >= 0) {
245 self->fd = fd;
246 self->closefd = closefd;
247 }
248 else {
249 self->closefd = 1;
250 if (!closefd) {
251 PyErr_SetString(PyExc_ValueError,
Amaury Forgeot d'Arc9f616f42008-10-29 23:15:57 +0000252 "Cannot use closefd=False with file name");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000253 goto error;
254 }
255
256 Py_BEGIN_ALLOW_THREADS
257 errno = 0;
258#ifdef MS_WINDOWS
259 if (widename != NULL)
260 self->fd = _wopen(widename, flags, 0666);
261 else
262#endif
263 self->fd = open(name, flags, 0666);
264 Py_END_ALLOW_THREADS
Benjamin Petersonf22c26e2008-09-01 14:13:43 +0000265 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000266#ifdef MS_WINDOWS
267 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
268#else
269 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
270#endif
271 goto error;
272 }
Benjamin Petersonf22c26e2008-09-01 14:13:43 +0000273 if(dircheck(self) < 0)
274 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000275 }
276
277 goto done;
278
279 error:
280 ret = -1;
281
282 done:
Neal Norwitz18aa3882008-08-24 05:04:52 +0000283 PyMem_Free(name);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000284 return ret;
285}
286
287static void
288fileio_dealloc(PyFileIOObject *self)
289{
290 if (self->weakreflist != NULL)
291 PyObject_ClearWeakRefs((PyObject *) self);
292
293 if (self->fd >= 0 && self->closefd) {
294 errno = internal_close(self);
295 if (errno < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000296 PySys_WriteStderr("close failed: [Errno %d] %s\n",
297 errno, strerror(errno));
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000298 }
299 }
300
301 Py_TYPE(self)->tp_free((PyObject *)self);
302}
303
304static PyObject *
305err_closed(void)
306{
307 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
308 return NULL;
309}
310
311static PyObject *
312err_mode(char *action)
313{
314 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
315 return NULL;
316}
317
318static PyObject *
319fileio_fileno(PyFileIOObject *self)
320{
321 if (self->fd < 0)
322 return err_closed();
323 return PyInt_FromLong((long) self->fd);
324}
325
326static PyObject *
327fileio_readable(PyFileIOObject *self)
328{
329 if (self->fd < 0)
330 return err_closed();
331 return PyBool_FromLong((long) self->readable);
332}
333
334static PyObject *
335fileio_writable(PyFileIOObject *self)
336{
337 if (self->fd < 0)
338 return err_closed();
339 return PyBool_FromLong((long) self->writable);
340}
341
342static PyObject *
343fileio_seekable(PyFileIOObject *self)
344{
345 if (self->fd < 0)
346 return err_closed();
347 if (self->seekable < 0) {
348 int ret;
349 Py_BEGIN_ALLOW_THREADS
350 ret = lseek(self->fd, 0, SEEK_CUR);
351 Py_END_ALLOW_THREADS
352 if (ret < 0)
353 self->seekable = 0;
354 else
355 self->seekable = 1;
356 }
357 return PyBool_FromLong((long) self->seekable);
358}
359
360static PyObject *
361fileio_readinto(PyFileIOObject *self, PyObject *args)
362{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000363 Py_buffer pbuf;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000364 Py_ssize_t n;
365
366 if (self->fd < 0)
367 return err_closed();
368 if (!self->readable)
369 return err_mode("reading");
370
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000371 if (!PyArg_ParseTuple(args, "w*", &pbuf))
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000372 return NULL;
373
374 Py_BEGIN_ALLOW_THREADS
375 errno = 0;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000376 n = read(self->fd, pbuf.buf, pbuf.len);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000377 Py_END_ALLOW_THREADS
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000378 PyBuffer_Release(&pbuf);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000379 if (n < 0) {
380 if (errno == EAGAIN)
381 Py_RETURN_NONE;
382 PyErr_SetFromErrno(PyExc_IOError);
383 return NULL;
384 }
385
386 return PyLong_FromSsize_t(n);
387}
388
389#define DEFAULT_BUFFER_SIZE (8*1024)
390
391static PyObject *
392fileio_readall(PyFileIOObject *self)
393{
394 PyObject *result;
395 Py_ssize_t total = 0;
396 int n;
397
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000398 result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000399 if (result == NULL)
400 return NULL;
401
402 while (1) {
403 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000404 if (PyString_GET_SIZE(result) < newsize) {
405 if (_PyString_Resize(&result, newsize) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000406 if (total == 0) {
407 Py_DECREF(result);
408 return NULL;
409 }
410 PyErr_Clear();
411 break;
412 }
413 }
414 Py_BEGIN_ALLOW_THREADS
415 errno = 0;
416 n = read(self->fd,
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000417 PyString_AS_STRING(result) + total,
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000418 newsize - total);
419 Py_END_ALLOW_THREADS
420 if (n == 0)
421 break;
422 if (n < 0) {
423 if (total > 0)
424 break;
425 if (errno == EAGAIN) {
426 Py_DECREF(result);
427 Py_RETURN_NONE;
428 }
429 Py_DECREF(result);
430 PyErr_SetFromErrno(PyExc_IOError);
431 return NULL;
432 }
433 total += n;
434 }
435
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000436 if (PyString_GET_SIZE(result) > total) {
437 if (_PyString_Resize(&result, total) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000438 /* This should never happen, but just in case */
439 Py_DECREF(result);
440 return NULL;
441 }
442 }
443 return result;
444}
445
446static PyObject *
447fileio_read(PyFileIOObject *self, PyObject *args)
448{
449 char *ptr;
450 Py_ssize_t n;
451 Py_ssize_t size = -1;
452 PyObject *bytes;
453
454 if (self->fd < 0)
455 return err_closed();
456 if (!self->readable)
457 return err_mode("reading");
458
459 if (!PyArg_ParseTuple(args, "|n", &size))
460 return NULL;
461
462 if (size < 0) {
463 return fileio_readall(self);
464 }
465
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000466 bytes = PyString_FromStringAndSize(NULL, size);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000467 if (bytes == NULL)
468 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000469 ptr = PyString_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000470
471 Py_BEGIN_ALLOW_THREADS
472 errno = 0;
473 n = read(self->fd, ptr, size);
474 Py_END_ALLOW_THREADS
475
476 if (n < 0) {
477 if (errno == EAGAIN)
478 Py_RETURN_NONE;
479 PyErr_SetFromErrno(PyExc_IOError);
480 return NULL;
481 }
482
483 if (n != size) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000484 if (_PyString_Resize(&bytes, n) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000485 Py_DECREF(bytes);
486 return NULL;
487 }
488 }
489
490 return (PyObject *) bytes;
491}
492
493static PyObject *
494fileio_write(PyFileIOObject *self, PyObject *args)
495{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000496 Py_buffer pbuf;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000497 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000498
499 if (self->fd < 0)
500 return err_closed();
501 if (!self->writable)
502 return err_mode("writing");
503
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000504 if (!PyArg_ParseTuple(args, "s*", &pbuf))
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000505 return NULL;
506
507 Py_BEGIN_ALLOW_THREADS
508 errno = 0;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000509 n = write(self->fd, pbuf.buf, pbuf.len);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000510 Py_END_ALLOW_THREADS
511
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000512 PyBuffer_Release(&pbuf);
513
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000514 if (n < 0) {
515 if (errno == EAGAIN)
516 Py_RETURN_NONE;
517 PyErr_SetFromErrno(PyExc_IOError);
518 return NULL;
519 }
520
521 return PyLong_FromSsize_t(n);
522}
523
524/* XXX Windows support below is likely incomplete */
525
526#if defined(MS_WIN64) || defined(MS_WINDOWS)
527typedef PY_LONG_LONG Py_off_t;
528#else
529typedef off_t Py_off_t;
530#endif
531
532/* Cribbed from posix_lseek() */
533static PyObject *
534portable_lseek(int fd, PyObject *posobj, int whence)
535{
536 Py_off_t pos, res;
537
538#ifdef SEEK_SET
539 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
540 switch (whence) {
541#if SEEK_SET != 0
542 case 0: whence = SEEK_SET; break;
543#endif
544#if SEEK_CUR != 1
545 case 1: whence = SEEK_CUR; break;
546#endif
547#if SEEL_END != 2
548 case 2: whence = SEEK_END; break;
549#endif
550 }
551#endif /* SEEK_SET */
552
553 if (posobj == NULL)
554 pos = 0;
555 else {
556 if(PyFloat_Check(posobj)) {
557 PyErr_SetString(PyExc_TypeError, "an integer is required");
558 return NULL;
559 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000560#if defined(HAVE_LARGEFILE_SUPPORT)
561 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000562#else
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000563 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000564#endif
565 if (PyErr_Occurred())
566 return NULL;
567 }
568
569 Py_BEGIN_ALLOW_THREADS
570#if defined(MS_WIN64) || defined(MS_WINDOWS)
571 res = _lseeki64(fd, pos, whence);
572#else
573 res = lseek(fd, pos, whence);
574#endif
575 Py_END_ALLOW_THREADS
576 if (res < 0)
577 return PyErr_SetFromErrno(PyExc_IOError);
578
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000579#if defined(HAVE_LARGEFILE_SUPPORT)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000580 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000581#else
582 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000583#endif
584}
585
586static PyObject *
587fileio_seek(PyFileIOObject *self, PyObject *args)
588{
589 PyObject *posobj;
590 int whence = 0;
591
592 if (self->fd < 0)
593 return err_closed();
594
595 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
596 return NULL;
597
598 return portable_lseek(self->fd, posobj, whence);
599}
600
601static PyObject *
602fileio_tell(PyFileIOObject *self, PyObject *args)
603{
604 if (self->fd < 0)
605 return err_closed();
606
607 return portable_lseek(self->fd, NULL, 1);
608}
609
610#ifdef HAVE_FTRUNCATE
611static PyObject *
612fileio_truncate(PyFileIOObject *self, PyObject *args)
613{
614 PyObject *posobj = NULL;
615 Py_off_t pos;
616 int ret;
617 int fd;
618
619 fd = self->fd;
620 if (fd < 0)
621 return err_closed();
622 if (!self->writable)
623 return err_mode("writing");
624
625 if (!PyArg_ParseTuple(args, "|O", &posobj))
626 return NULL;
627
628 if (posobj == Py_None || posobj == NULL) {
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000629 /* Get the current position. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000630 posobj = portable_lseek(fd, NULL, 1);
631 if (posobj == NULL)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000632 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000633 }
634 else {
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000635 /* Move to the position to be truncated. */
636 posobj = portable_lseek(fd, posobj, 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000637 }
638
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000639#if defined(HAVE_LARGEFILE_SUPPORT)
640 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000641#else
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000642 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000643#endif
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000644 if (PyErr_Occurred())
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000645 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000646
647#ifdef MS_WINDOWS
648 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
649 so don't even try using it. */
650 {
651 HANDLE hFile;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000652
653 /* Truncate. Note that this may grow the file! */
654 Py_BEGIN_ALLOW_THREADS
655 errno = 0;
656 hFile = (HANDLE)_get_osfhandle(fd);
657 ret = hFile == (HANDLE)-1;
658 if (ret == 0) {
659 ret = SetEndOfFile(hFile) == 0;
660 if (ret)
661 errno = EACCES;
662 }
663 Py_END_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000664 }
665#else
666 Py_BEGIN_ALLOW_THREADS
667 errno = 0;
668 ret = ftruncate(fd, pos);
669 Py_END_ALLOW_THREADS
670#endif /* !MS_WINDOWS */
671
672 if (ret != 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000673 PyErr_SetFromErrno(PyExc_IOError);
674 return NULL;
675 }
676
677 return posobj;
678}
679#endif
680
681static char *
682mode_string(PyFileIOObject *self)
683{
684 if (self->readable) {
685 if (self->writable)
686 return "r+";
687 else
688 return "r";
689 }
690 else
691 return "w";
692}
693
694static PyObject *
695fileio_repr(PyFileIOObject *self)
696{
697 if (self->fd < 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000698 return PyString_FromFormat("_fileio._FileIO(-1)");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000699
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000700 return PyString_FromFormat("_fileio._FileIO(%d, '%s')",
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000701 self->fd, mode_string(self));
702}
703
704static PyObject *
705fileio_isatty(PyFileIOObject *self)
706{
707 long res;
708
709 if (self->fd < 0)
710 return err_closed();
711 Py_BEGIN_ALLOW_THREADS
712 res = isatty(self->fd);
713 Py_END_ALLOW_THREADS
714 return PyBool_FromLong(res);
715}
716
717
718PyDoc_STRVAR(fileio_doc,
719"file(name: str[, mode: str]) -> file IO object\n"
720"\n"
721"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
722"writing or appending. The file will be created if it doesn't exist\n"
723"when opened for writing or appending; it will be truncated when\n"
724"opened for writing. Add a '+' to the mode to allow simultaneous\n"
725"reading and writing.");
726
727PyDoc_STRVAR(read_doc,
728"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
729"\n"
730"Only makes one system call, so less data may be returned than requested\n"
731"In non-blocking mode, returns None if no data is available.\n"
732"On end-of-file, returns ''.");
733
734PyDoc_STRVAR(readall_doc,
735"readall() -> bytes. read all data from the file, returned as bytes.\n"
736"\n"
737"In non-blocking mode, returns as much as is immediately available,\n"
738"or None if no data is available. On end-of-file, returns ''.");
739
740PyDoc_STRVAR(write_doc,
741"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
742"\n"
743"Only makes one system call, so not all of the data may be written.\n"
744"The number of bytes actually written is returned.");
745
746PyDoc_STRVAR(fileno_doc,
747"fileno() -> int. \"file descriptor\".\n"
748"\n"
749"This is needed for lower-level file interfaces, such the fcntl module.");
750
751PyDoc_STRVAR(seek_doc,
752"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
753"\n"
754"Argument offset is a byte count. Optional argument whence defaults to\n"
755"0 (offset from start of file, offset should be >= 0); other values are 1\n"
756"(move relative to current position, positive or negative), and 2 (move\n"
757"relative to end of file, usually negative, although many platforms allow\n"
758"seeking beyond the end of a file)."
759"\n"
760"Note that not all file objects are seekable.");
761
762#ifdef HAVE_FTRUNCATE
763PyDoc_STRVAR(truncate_doc,
764"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
765"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000766"Size defaults to the current file position, as returned by tell()."
767"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000768#endif
769
770PyDoc_STRVAR(tell_doc,
771"tell() -> int. Current file position");
772
773PyDoc_STRVAR(readinto_doc,
774"readinto() -> Undocumented. Don't use this; it may go away.");
775
776PyDoc_STRVAR(close_doc,
777"close() -> None. Close the file.\n"
778"\n"
779"A closed file cannot be used for further I/O operations. close() may be\n"
780"called more than once without error. Changes the fileno to -1.");
781
782PyDoc_STRVAR(isatty_doc,
783"isatty() -> bool. True if the file is connected to a tty device.");
784
785PyDoc_STRVAR(seekable_doc,
786"seekable() -> bool. True if file supports random-access.");
787
788PyDoc_STRVAR(readable_doc,
789"readable() -> bool. True if file was opened in a read mode.");
790
791PyDoc_STRVAR(writable_doc,
792"writable() -> bool. True if file was opened in a write mode.");
793
794static PyMethodDef fileio_methods[] = {
795 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
796 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
797 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
798 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
799 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
800 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
801#ifdef HAVE_FTRUNCATE
802 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
803#endif
804 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
805 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
806 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
807 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
808 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
809 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
810 {NULL, NULL} /* sentinel */
811};
812
813/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
814
815static PyObject *
816get_closed(PyFileIOObject *self, void *closure)
817{
818 return PyBool_FromLong((long)(self->fd < 0));
819}
820
821static PyObject *
822get_mode(PyFileIOObject *self, void *closure)
823{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000824 return PyString_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000825}
826
827static PyGetSetDef fileio_getsetlist[] = {
828 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
829 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
830 {0},
831};
832
833PyTypeObject PyFileIO_Type = {
Hirokazu Yamamoto09979a12008-09-23 16:11:09 +0000834 PyVarObject_HEAD_INIT(NULL, 0)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000835 "_FileIO",
836 sizeof(PyFileIOObject),
837 0,
838 (destructor)fileio_dealloc, /* tp_dealloc */
839 0, /* tp_print */
840 0, /* tp_getattr */
841 0, /* tp_setattr */
842 0, /* tp_compare */
843 (reprfunc)fileio_repr, /* tp_repr */
844 0, /* tp_as_number */
845 0, /* tp_as_sequence */
846 0, /* tp_as_mapping */
847 0, /* tp_hash */
848 0, /* tp_call */
849 0, /* tp_str */
850 PyObject_GenericGetAttr, /* tp_getattro */
851 0, /* tp_setattro */
852 0, /* tp_as_buffer */
853 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
854 fileio_doc, /* tp_doc */
855 0, /* tp_traverse */
856 0, /* tp_clear */
857 0, /* tp_richcompare */
858 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
859 0, /* tp_iter */
860 0, /* tp_iternext */
861 fileio_methods, /* tp_methods */
862 0, /* tp_members */
863 fileio_getsetlist, /* tp_getset */
864 0, /* tp_base */
865 0, /* tp_dict */
866 0, /* tp_descr_get */
867 0, /* tp_descr_set */
868 0, /* tp_dictoffset */
869 fileio_init, /* tp_init */
870 PyType_GenericAlloc, /* tp_alloc */
871 fileio_new, /* tp_new */
872 PyObject_Del, /* tp_free */
873};
874
875static PyMethodDef module_methods[] = {
876 {NULL, NULL}
877};
878
879PyMODINIT_FUNC
880init_fileio(void)
881{
882 PyObject *m; /* a module object */
883
884 m = Py_InitModule3("_fileio", module_methods,
885 "Fast implementation of io.FileIO.");
886 if (m == NULL)
887 return;
888 if (PyType_Ready(&PyFileIO_Type) < 0)
889 return;
890 Py_INCREF(&PyFileIO_Type);
891 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
892}