blob: a2c0221dc24b516cc238cb6935bcbc6fa0ede8de [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +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
Guido van Rossuma9e20242007-03-08 00:43:48 +000021 */
22
23#ifdef MS_WINDOWS
24/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerc6a55ee2007-07-11 12:45:46 +000025/* #define HAVE_FTRUNCATE */
Guido van Rossuma9e20242007-03-08 00:43:48 +000026#define WIN32_LEAN_AND_MEAN
27#include <windows.h>
28#endif
29
30typedef struct {
31 PyObject_HEAD
32 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +000033 int readable;
34 int writable;
35 int seekable; /* -1 means unknown */
36 PyObject *weakreflist;
37} PyFileIOObject;
38
Collin Winteraf334382007-03-08 21:46:15 +000039PyTypeObject PyFileIO_Type;
40
Guido van Rossuma9e20242007-03-08 00:43:48 +000041#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
42
43/* Note: if this function is changed so that it can return a true value,
44 * then we need a separate function for __exit__
45 */
46static PyObject *
47fileio_close(PyFileIOObject *self)
48{
49 if (self->fd >= 0) {
Guido van Rossumb0428152007-04-08 17:44:42 +000050 int fd = self->fd;
51 self->fd = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +000052 Py_BEGIN_ALLOW_THREADS
53 errno = 0;
Guido van Rossumb0428152007-04-08 17:44:42 +000054 close(fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +000055 Py_END_ALLOW_THREADS
56 if (errno < 0) {
57 PyErr_SetFromErrno(PyExc_IOError);
58 return NULL;
59 }
Guido van Rossuma9e20242007-03-08 00:43:48 +000060 }
61
62 Py_RETURN_NONE;
63}
64
65static PyObject *
66fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews)
67{
68 PyFileIOObject *self;
69
70 assert(type != NULL && type->tp_alloc != NULL);
71
72 self = (PyFileIOObject *) type->tp_alloc(type, 0);
73 if (self != NULL) {
74 self->fd = -1;
75 self->weakreflist = NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +000076 }
77
78 return (PyObject *) self;
79}
80
81/* On Unix, open will succeed for directories.
82 In Python, there should be no file objects referring to
83 directories, so we need a check. */
84
85static int
86dircheck(PyFileIOObject* self)
87{
88#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
89 struct stat buf;
90 if (self->fd < 0)
91 return 0;
92 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
93#ifdef HAVE_STRERROR
94 char *msg = strerror(EISDIR);
95#else
96 char *msg = "Is a directory";
97#endif
98 PyObject *exc;
99 PyObject *closeresult = fileio_close(self);
100 Py_DECREF(closeresult);
Guido van Rossum53807da2007-04-10 19:01:47 +0000101
Guido van Rossuma9e20242007-03-08 00:43:48 +0000102 exc = PyObject_CallFunction(PyExc_IOError, "(is)",
103 EISDIR, msg);
104 PyErr_SetObject(PyExc_IOError, exc);
105 Py_XDECREF(exc);
106 return -1;
107 }
108#endif
109 return 0;
110}
111
112
113static int
114fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
115{
116 PyFileIOObject *self = (PyFileIOObject *) oself;
Guido van Rossumb0428152007-04-08 17:44:42 +0000117 static char *kwlist[] = {"file", "mode", NULL};
Guido van Rossuma9e20242007-03-08 00:43:48 +0000118 char *name = NULL;
119 char *mode = "r";
Guido van Rossum53807da2007-04-10 19:01:47 +0000120 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000121#ifdef MS_WINDOWS
122 Py_UNICODE *widename = NULL;
123#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000124 int ret = 0;
125 int rwa = 0, plus = 0, append = 0;
126 int flags = 0;
Guido van Rossumb0428152007-04-08 17:44:42 +0000127 int fd = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000128
129 assert(PyFileIO_Check(oself));
130 if (self->fd >= 0)
131 {
132 /* Have to close the existing file first. */
133 PyObject *closeresult = fileio_close(self);
134 if (closeresult == NULL)
135 return -1;
136 Py_DECREF(closeresult);
137 }
138
Guido van Rossumb0428152007-04-08 17:44:42 +0000139 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|s:fileio",
140 kwlist, &fd, &mode)) {
141 if (fd < 0) {
142 PyErr_SetString(PyExc_ValueError,
143 "Negative filedescriptor");
144 return -1;
145 }
146 }
147 else {
148 PyErr_Clear();
149
Guido van Rossuma9e20242007-03-08 00:43:48 +0000150#ifdef Py_WIN_WIDE_FILENAMES
Guido van Rossumb0428152007-04-08 17:44:42 +0000151 if (GetVersion() < 0x80000000) {
152 /* On NT, so wide API available */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000153 PyObject *po;
154 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|s:fileio",
155 kwlist, &po, &mode)) {
Thomas Helleraf2be262007-07-12 11:03:13 +0000156 widename = PyUnicode_AS_UNICODE(po);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000157 } else {
158 /* Drop the argument parsing error as narrow
159 strings are also valid. */
160 PyErr_Clear();
161 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000162 }
Thomas Helleraf2be262007-07-12 11:03:13 +0000163 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000164#endif
Thomas Helleraf2be262007-07-12 11:03:13 +0000165 {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000166 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|s:fileio",
167 kwlist,
168 Py_FileSystemDefaultEncoding,
169 &name, &mode))
170 goto error;
Guido van Rossumb0428152007-04-08 17:44:42 +0000171 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000172 }
173
174 self->readable = self->writable = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000175 self->seekable = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000176 s = mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000177 while (*s) {
178 switch (*s++) {
179 case 'r':
180 if (rwa) {
181 bad_mode:
182 PyErr_SetString(PyExc_ValueError,
183 "Must have exactly one of read/write/append mode");
184 goto error;
185 }
186 rwa = 1;
187 self->readable = 1;
188 break;
189 case 'w':
190 if (rwa)
191 goto bad_mode;
192 rwa = 1;
193 self->writable = 1;
194 flags |= O_CREAT | O_TRUNC;
195 break;
196 case 'a':
197 if (rwa)
198 goto bad_mode;
199 rwa = 1;
200 self->writable = 1;
201 flags |= O_CREAT;
202 append = 1;
203 break;
204 case '+':
205 if (plus)
206 goto bad_mode;
207 self->readable = self->writable = 1;
208 plus = 1;
209 break;
210 default:
211 PyErr_Format(PyExc_ValueError,
212 "invalid mode: %.200s", mode);
213 goto error;
214 }
215 }
216
217 if (!rwa)
218 goto bad_mode;
219
220 if (self->readable && self->writable)
221 flags |= O_RDWR;
222 else if (self->readable)
223 flags |= O_RDONLY;
224 else
225 flags |= O_WRONLY;
226
227#ifdef O_BINARY
228 flags |= O_BINARY;
229#endif
230
Walter Dörwald0e411482007-06-06 16:55:38 +0000231#ifdef O_APPEND
232 if (append)
233 flags |= O_APPEND;
234#endif
235
Guido van Rossumb0428152007-04-08 17:44:42 +0000236 if (fd >= 0) {
237 self->fd = fd;
Guido van Rossumb0428152007-04-08 17:44:42 +0000238 }
239 else {
240 Py_BEGIN_ALLOW_THREADS
241 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000242#ifdef MS_WINDOWS
243 if (widename != NULL)
244 self->fd = _wopen(widename, flags, 0666);
245 else
246#endif
Guido van Rossumb0428152007-04-08 17:44:42 +0000247 self->fd = open(name, flags, 0666);
248 Py_END_ALLOW_THREADS
249 if (self->fd < 0 || dircheck(self) < 0) {
250 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
251 goto error;
252 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000253 }
254
255 goto done;
256
257 error:
258 ret = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000259
Guido van Rossuma9e20242007-03-08 00:43:48 +0000260 done:
261 PyMem_Free(name);
262 return ret;
263}
264
265static void
266fileio_dealloc(PyFileIOObject *self)
267{
268 if (self->weakreflist != NULL)
269 PyObject_ClearWeakRefs((PyObject *) self);
270
Guido van Rossum53807da2007-04-10 19:01:47 +0000271 if (self->fd >= 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000272 PyObject *closeresult = fileio_close(self);
273 if (closeresult == NULL) {
274#ifdef HAVE_STRERROR
Guido van Rossum53807da2007-04-10 19:01:47 +0000275 PySys_WriteStderr("close failed: [Errno %d] %s\n",
276 errno, strerror(errno));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000277#else
278 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
279#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000280 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000281 Py_DECREF(closeresult);
282 }
283
284 self->ob_type->tp_free((PyObject *)self);
285}
286
287static PyObject *
288err_closed(void)
289{
290 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
291 return NULL;
292}
293
294static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000295err_mode(char *action)
296{
297 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
298 return NULL;
299}
300
301static PyObject *
Guido van Rossuma9e20242007-03-08 00:43:48 +0000302fileio_fileno(PyFileIOObject *self)
303{
304 if (self->fd < 0)
305 return err_closed();
306 return PyInt_FromLong((long) self->fd);
307}
308
309static PyObject *
310fileio_readable(PyFileIOObject *self)
311{
312 if (self->fd < 0)
313 return err_closed();
314 return PyInt_FromLong((long) self->readable);
315}
316
317static PyObject *
318fileio_writable(PyFileIOObject *self)
319{
320 if (self->fd < 0)
321 return err_closed();
322 return PyInt_FromLong((long) self->writable);
323}
324
325static PyObject *
326fileio_seekable(PyFileIOObject *self)
327{
328 if (self->fd < 0)
329 return err_closed();
330 if (self->seekable < 0) {
331 int ret;
332 Py_BEGIN_ALLOW_THREADS
333 ret = lseek(self->fd, 0, SEEK_CUR);
334 Py_END_ALLOW_THREADS
335 if (ret < 0)
336 self->seekable = 0;
337 else
338 self->seekable = 1;
339 }
340 return PyInt_FromLong((long) self->seekable);
341}
342
343static PyObject *
344fileio_readinto(PyFileIOObject *self, PyObject *args)
345{
346 char *ptr;
347 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000348
Guido van Rossuma9e20242007-03-08 00:43:48 +0000349 if (self->fd < 0)
350 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000351 if (!self->readable)
352 return err_mode("reading");
353
Guido van Rossuma9e20242007-03-08 00:43:48 +0000354 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
355 return NULL;
356
357 Py_BEGIN_ALLOW_THREADS
358 errno = 0;
359 n = read(self->fd, ptr, n);
360 Py_END_ALLOW_THREADS
361 if (n < 0) {
362 if (errno == EAGAIN)
363 Py_RETURN_NONE;
364 PyErr_SetFromErrno(PyExc_IOError);
365 return NULL;
366 }
367
368 return PyInt_FromLong(n);
369}
370
Guido van Rossum7165cb12007-07-10 06:54:34 +0000371#define DEFAULT_BUFFER_SIZE (8*1024)
372
373static PyObject *
374fileio_readall(PyFileIOObject *self)
375{
376 PyObject *result;
377 Py_ssize_t total = 0;
378 int n;
379
380 result = PyBytes_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
381 if (result == NULL)
382 return NULL;
383
384 while (1) {
385 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
386 if (PyBytes_GET_SIZE(result) < newsize) {
387 if (PyBytes_Resize(result, newsize) < 0) {
388 if (total == 0) {
389 Py_DECREF(result);
390 return NULL;
391 }
392 PyErr_Clear();
393 break;
394 }
395 }
396 Py_BEGIN_ALLOW_THREADS
397 errno = 0;
398 n = read(self->fd,
399 PyBytes_AS_STRING(result) + total,
400 newsize - total);
401 Py_END_ALLOW_THREADS
402 if (n == 0)
403 break;
404 if (n < 0) {
405 if (total > 0)
406 break;
407 if (errno == EAGAIN) {
408 Py_DECREF(result);
409 Py_RETURN_NONE;
410 }
411 Py_DECREF(result);
412 PyErr_SetFromErrno(PyExc_IOError);
413 return NULL;
414 }
415 total += n;
416 }
417
418 if (PyBytes_GET_SIZE(result) > total) {
419 if (PyBytes_Resize(result, total) < 0) {
420 /* This should never happen, but just in case */
421 Py_DECREF(result);
422 return NULL;
423 }
424 }
425 return result;
426}
427
Guido van Rossuma9e20242007-03-08 00:43:48 +0000428static PyObject *
429fileio_read(PyFileIOObject *self, PyObject *args)
430{
431 char *ptr;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000432 Py_ssize_t n;
433 Py_ssize_t size = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000434 PyObject *bytes;
435
436 if (self->fd < 0)
437 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000438 if (!self->readable)
439 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000440
Guido van Rossum7165cb12007-07-10 06:54:34 +0000441 if (!PyArg_ParseTuple(args, "|i", &size))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000442 return NULL;
443
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000444 if (size < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000445 return fileio_readall(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000446 }
447
Guido van Rossuma9e20242007-03-08 00:43:48 +0000448 bytes = PyBytes_FromStringAndSize(NULL, size);
449 if (bytes == NULL)
450 return NULL;
451 ptr = PyBytes_AsString(bytes);
452
453 Py_BEGIN_ALLOW_THREADS
454 errno = 0;
455 n = read(self->fd, ptr, size);
456 Py_END_ALLOW_THREADS
457
458 if (n < 0) {
459 if (errno == EAGAIN)
460 Py_RETURN_NONE;
461 PyErr_SetFromErrno(PyExc_IOError);
462 return NULL;
463 }
464
465 if (n != size) {
466 if (PyBytes_Resize(bytes, n) < 0) {
467 Py_DECREF(bytes);
Guido van Rossum53807da2007-04-10 19:01:47 +0000468 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000469 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000470 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000471
472 return (PyObject *) bytes;
473}
474
475static PyObject *
476fileio_write(PyFileIOObject *self, PyObject *args)
477{
478 Py_ssize_t n;
479 char *ptr;
480
481 if (self->fd < 0)
482 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000483 if (!self->writable)
484 return err_mode("writing");
485
Guido van Rossuma9e20242007-03-08 00:43:48 +0000486 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
487 return NULL;
488
489 Py_BEGIN_ALLOW_THREADS
490 errno = 0;
491 n = write(self->fd, ptr, n);
492 Py_END_ALLOW_THREADS
493
494 if (n < 0) {
495 if (errno == EAGAIN)
496 Py_RETURN_NONE;
497 PyErr_SetFromErrno(PyExc_IOError);
498 return NULL;
499 }
500
501 return PyInt_FromLong(n);
502}
503
Guido van Rossum53807da2007-04-10 19:01:47 +0000504/* XXX Windows support below is likely incomplete */
505
506#if defined(MS_WIN64) || defined(MS_WINDOWS)
507typedef PY_LONG_LONG Py_off_t;
508#else
509typedef off_t Py_off_t;
510#endif
511
512/* Cribbed from posix_lseek() */
513static PyObject *
514portable_lseek(int fd, PyObject *posobj, int whence)
515{
516 Py_off_t pos, res;
517
518#ifdef SEEK_SET
519 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
520 switch (whence) {
521#if SEEK_SET != 0
522 case 0: whence = SEEK_SET; break;
523#endif
524#if SEEK_CUR != 1
525 case 1: whence = SEEK_CUR; break;
526#endif
527#if SEEL_END != 2
528 case 2: whence = SEEK_END; break;
529#endif
530 }
531#endif /* SEEK_SET */
532
533 if (posobj == NULL)
534 pos = 0;
535 else {
536#if !defined(HAVE_LARGEFILE_SUPPORT)
537 pos = PyInt_AsLong(posobj);
538#else
539 pos = PyLong_Check(posobj) ?
540 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
541#endif
542 if (PyErr_Occurred())
543 return NULL;
544 }
545
546 Py_BEGIN_ALLOW_THREADS
547#if defined(MS_WIN64) || defined(MS_WINDOWS)
548 res = _lseeki64(fd, pos, whence);
549#else
550 res = lseek(fd, pos, whence);
551#endif
552 Py_END_ALLOW_THREADS
553 if (res < 0)
554 return PyErr_SetFromErrno(PyExc_IOError);
555
556#if !defined(HAVE_LARGEFILE_SUPPORT)
557 return PyInt_FromLong(res);
558#else
559 return PyLong_FromLongLong(res);
560#endif
561}
562
Guido van Rossuma9e20242007-03-08 00:43:48 +0000563static PyObject *
564fileio_seek(PyFileIOObject *self, PyObject *args)
565{
Guido van Rossum53807da2007-04-10 19:01:47 +0000566 PyObject *posobj;
567 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000568
569 if (self->fd < 0)
570 return err_closed();
571
Guido van Rossum53807da2007-04-10 19:01:47 +0000572 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000573 return NULL;
574
Guido van Rossum53807da2007-04-10 19:01:47 +0000575 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000576}
577
578static PyObject *
579fileio_tell(PyFileIOObject *self, PyObject *args)
580{
Guido van Rossuma9e20242007-03-08 00:43:48 +0000581 if (self->fd < 0)
582 return err_closed();
583
Guido van Rossum53807da2007-04-10 19:01:47 +0000584 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000585}
586
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000587#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000588static PyObject *
589fileio_truncate(PyFileIOObject *self, PyObject *args)
590{
Guido van Rossum53807da2007-04-10 19:01:47 +0000591 PyObject *posobj = NULL;
592 Py_off_t pos;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000593 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000594
Guido van Rossum53807da2007-04-10 19:01:47 +0000595 fd = self->fd;
596 if (fd < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000597 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000598 if (!self->writable)
599 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000600
Guido van Rossum53807da2007-04-10 19:01:47 +0000601 if (!PyArg_ParseTuple(args, "|O", &posobj))
602 return NULL;
603
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000604 if (posobj == Py_None || posobj == NULL) {
605 posobj = portable_lseek(fd, NULL, 1);
606 if (posobj == NULL)
607 return NULL;
608 }
609 else {
610 Py_INCREF(posobj);
611 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000612
613#if !defined(HAVE_LARGEFILE_SUPPORT)
614 pos = PyInt_AsLong(posobj);
615#else
616 pos = PyLong_Check(posobj) ?
617 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
618#endif
Guido van Rossum87429772007-04-10 21:06:59 +0000619 if (PyErr_Occurred()) {
620 Py_DECREF(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000621 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000622 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000623
Guido van Rossuma9e20242007-03-08 00:43:48 +0000624 Py_BEGIN_ALLOW_THREADS
625 errno = 0;
Guido van Rossum53807da2007-04-10 19:01:47 +0000626 pos = ftruncate(fd, pos);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000627 Py_END_ALLOW_THREADS
628
Guido van Rossum87429772007-04-10 21:06:59 +0000629 if (pos < 0) {
630 Py_DECREF(posobj);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000631 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum87429772007-04-10 21:06:59 +0000632 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000633
Guido van Rossum87429772007-04-10 21:06:59 +0000634 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000635}
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000636#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000637
638static char *
639mode_string(PyFileIOObject *self)
640{
641 if (self->readable) {
642 if (self->writable)
643 return "r+";
644 else
645 return "r";
646 }
647 else
648 return "w";
649}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000650
651static PyObject *
652fileio_repr(PyFileIOObject *self)
653{
Guido van Rossum53807da2007-04-10 19:01:47 +0000654 if (self->fd < 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000655 return PyUnicode_FromFormat("_fileio._FileIO(-1)");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000656
Walter Dörwald1ab83302007-05-18 17:15:44 +0000657 return PyUnicode_FromFormat("_fileio._FileIO(%d, '%s')",
Guido van Rossum53807da2007-04-10 19:01:47 +0000658 self->fd, mode_string(self));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000659}
660
661static PyObject *
662fileio_isatty(PyFileIOObject *self)
663{
664 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000665
Guido van Rossuma9e20242007-03-08 00:43:48 +0000666 if (self->fd < 0)
667 return err_closed();
668 Py_BEGIN_ALLOW_THREADS
669 res = isatty(self->fd);
670 Py_END_ALLOW_THREADS
671 return PyBool_FromLong(res);
672}
673
Guido van Rossuma9e20242007-03-08 00:43:48 +0000674
675PyDoc_STRVAR(fileio_doc,
676"file(name: str[, mode: str]) -> file IO object\n"
677"\n"
678"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
679"writing or appending. The file will be created if it doesn't exist\n"
680"when opened for writing or appending; it will be truncated when\n"
681"opened for writing. Add a '+' to the mode to allow simultaneous\n"
682"reading and writing.");
683
684PyDoc_STRVAR(read_doc,
685"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
686"\n"
687"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000688"In non-blocking mode, returns None if no data is available.\n"
689"On end-of-file, returns ''.");
690
691PyDoc_STRVAR(readall_doc,
692"readall() -> bytes. read all data from the file, returned as bytes.\n"
693"\n"
694"In non-blocking mode, returns as much as is immediately available,\n"
695"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000696
697PyDoc_STRVAR(write_doc,
698"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
699"\n"
700"Only makes one system call, so not all of the data may be written.\n"
701"The number of bytes actually written is returned.");
702
703PyDoc_STRVAR(fileno_doc,
704"fileno() -> int. \"file descriptor\".\n"
705"\n"
706"This is needed for lower-level file interfaces, such the fcntl module.");
707
708PyDoc_STRVAR(seek_doc,
709"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
710"\n"
711"Argument offset is a byte count. Optional argument whence defaults to\n"
712"0 (offset from start of file, offset should be >= 0); other values are 1\n"
713"(move relative to current position, positive or negative), and 2 (move\n"
714"relative to end of file, usually negative, although many platforms allow\n"
715"seeking beyond the end of a file)."
716"\n"
717"Note that not all file objects are seekable.");
718
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000719#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000720PyDoc_STRVAR(truncate_doc,
721"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
722"\n"
723"Size defaults to the current file position, as returned by tell().");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000724#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000725
726PyDoc_STRVAR(tell_doc,
727"tell() -> int. Current file position");
728
729PyDoc_STRVAR(readinto_doc,
730"readinto() -> Undocumented. Don't use this; it may go away.");
731
732PyDoc_STRVAR(close_doc,
733"close() -> None. Close the file.\n"
734"\n"
735"A closed file cannot be used for further I/O operations. close() may be\n"
736"called more than once without error. Changes the fileno to -1.");
737
738PyDoc_STRVAR(isatty_doc,
739"isatty() -> bool. True if the file is connected to a tty device.");
740
Guido van Rossuma9e20242007-03-08 00:43:48 +0000741PyDoc_STRVAR(seekable_doc,
742"seekable() -> bool. True if file supports random-access.");
743
744PyDoc_STRVAR(readable_doc,
745"readable() -> bool. True if file was opened in a read mode.");
746
747PyDoc_STRVAR(writable_doc,
748"writable() -> bool. True if file was opened in a write mode.");
749
750static PyMethodDef fileio_methods[] = {
751 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
Guido van Rossum7165cb12007-07-10 06:54:34 +0000752 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000753 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
754 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
755 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
756 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000757#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000758 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000759#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000760 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
761 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
762 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
763 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
764 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
765 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000766 {NULL, NULL} /* sentinel */
767};
768
Guido van Rossum53807da2007-04-10 19:01:47 +0000769/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
770
Guido van Rossumb0428152007-04-08 17:44:42 +0000771static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000772get_closed(PyFileIOObject *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +0000773{
Guido van Rossum53807da2007-04-10 19:01:47 +0000774 return PyBool_FromLong((long)(self->fd < 0));
775}
776
777static PyObject *
778get_mode(PyFileIOObject *self, void *closure)
779{
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000780 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +0000781}
782
783static PyGetSetDef fileio_getsetlist[] = {
784 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Guido van Rossum53807da2007-04-10 19:01:47 +0000785 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Guido van Rossumb0428152007-04-08 17:44:42 +0000786 {0},
787};
788
Guido van Rossuma9e20242007-03-08 00:43:48 +0000789PyTypeObject PyFileIO_Type = {
790 PyObject_HEAD_INIT(&PyType_Type)
791 0,
792 "FileIO",
793 sizeof(PyFileIOObject),
794 0,
795 (destructor)fileio_dealloc, /* tp_dealloc */
796 0, /* tp_print */
797 0, /* tp_getattr */
798 0, /* tp_setattr */
799 0, /* tp_compare */
800 (reprfunc)fileio_repr, /* tp_repr */
801 0, /* tp_as_number */
802 0, /* tp_as_sequence */
803 0, /* tp_as_mapping */
804 0, /* tp_hash */
805 0, /* tp_call */
806 0, /* tp_str */
807 PyObject_GenericGetAttr, /* tp_getattro */
808 0, /* tp_setattro */
809 0, /* tp_as_buffer */
810 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
811 fileio_doc, /* tp_doc */
812 0, /* tp_traverse */
813 0, /* tp_clear */
814 0, /* tp_richcompare */
815 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
816 0, /* tp_iter */
817 0, /* tp_iternext */
818 fileio_methods, /* tp_methods */
819 0, /* tp_members */
Guido van Rossumb0428152007-04-08 17:44:42 +0000820 fileio_getsetlist, /* tp_getset */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000821 0, /* tp_base */
822 0, /* tp_dict */
823 0, /* tp_descr_get */
824 0, /* tp_descr_set */
825 0, /* tp_dictoffset */
826 fileio_init, /* tp_init */
827 PyType_GenericAlloc, /* tp_alloc */
828 fileio_new, /* tp_new */
829 PyObject_Del, /* tp_free */
830};
831
832static PyMethodDef module_methods[] = {
833 {NULL, NULL}
834};
835
836PyMODINIT_FUNC
837init_fileio(void)
838{
839 PyObject *m; /* a module object */
840
841 m = Py_InitModule3("_fileio", module_methods,
842 "Fast implementation of io.FileIO.");
843 if (m == NULL)
844 return;
845 if (PyType_Ready(&PyFileIO_Type) < 0)
846 return;
847 Py_INCREF(&PyFileIO_Type);
848 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
849}