blob: feae5130200aef3ff0b79b083be8bfcaa9c140b6 [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;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000121 int wideargument = 0;
122 int ret = 0;
123 int rwa = 0, plus = 0, append = 0;
124 int flags = 0;
Guido van Rossumb0428152007-04-08 17:44:42 +0000125 int fd = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000126
127 assert(PyFileIO_Check(oself));
128 if (self->fd >= 0)
129 {
130 /* Have to close the existing file first. */
131 PyObject *closeresult = fileio_close(self);
132 if (closeresult == NULL)
133 return -1;
134 Py_DECREF(closeresult);
135 }
136
Guido van Rossumb0428152007-04-08 17:44:42 +0000137 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|s:fileio",
138 kwlist, &fd, &mode)) {
139 if (fd < 0) {
140 PyErr_SetString(PyExc_ValueError,
141 "Negative filedescriptor");
142 return -1;
143 }
144 }
145 else {
146 PyErr_Clear();
147
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148#ifdef Py_WIN_WIDE_FILENAMES
Guido van Rossumb0428152007-04-08 17:44:42 +0000149 if (GetVersion() < 0x80000000) {
150 /* On NT, so wide API available */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000151 PyObject *po;
152 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|s:fileio",
153 kwlist, &po, &mode)) {
154 wideargument = 1;
155 } else {
156 /* Drop the argument parsing error as narrow
157 strings are also valid. */
158 PyErr_Clear();
159 }
160
161 PyErr_SetString(PyExc_NotImplementedError,
Guido van Rossumb0428152007-04-08 17:44:42 +0000162 "Windows wide filenames are not yet supported");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000163 goto error;
Guido van Rossumb0428152007-04-08 17:44:42 +0000164 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000165#endif
166
Guido van Rossumb0428152007-04-08 17:44:42 +0000167 if (!wideargument) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000168 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|s:fileio",
169 kwlist,
170 Py_FileSystemDefaultEncoding,
171 &name, &mode))
172 goto error;
Guido van Rossumb0428152007-04-08 17:44:42 +0000173 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000174 }
175
176 self->readable = self->writable = 0;
Guido van Rossum53807da2007-04-10 19:01:47 +0000177 self->seekable = -1;
178 s = mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000179 while (*s) {
180 switch (*s++) {
181 case 'r':
182 if (rwa) {
183 bad_mode:
184 PyErr_SetString(PyExc_ValueError,
185 "Must have exactly one of read/write/append mode");
186 goto error;
187 }
188 rwa = 1;
189 self->readable = 1;
190 break;
191 case 'w':
192 if (rwa)
193 goto bad_mode;
194 rwa = 1;
195 self->writable = 1;
196 flags |= O_CREAT | O_TRUNC;
197 break;
198 case 'a':
199 if (rwa)
200 goto bad_mode;
201 rwa = 1;
202 self->writable = 1;
203 flags |= O_CREAT;
204 append = 1;
205 break;
206 case '+':
207 if (plus)
208 goto bad_mode;
209 self->readable = self->writable = 1;
210 plus = 1;
211 break;
212 default:
213 PyErr_Format(PyExc_ValueError,
214 "invalid mode: %.200s", mode);
215 goto error;
216 }
217 }
218
219 if (!rwa)
220 goto bad_mode;
221
222 if (self->readable && self->writable)
223 flags |= O_RDWR;
224 else if (self->readable)
225 flags |= O_RDONLY;
226 else
227 flags |= O_WRONLY;
228
229#ifdef O_BINARY
230 flags |= O_BINARY;
231#endif
232
Walter Dörwald0e411482007-06-06 16:55:38 +0000233#ifdef O_APPEND
234 if (append)
235 flags |= O_APPEND;
236#endif
237
Guido van Rossumb0428152007-04-08 17:44:42 +0000238 if (fd >= 0) {
239 self->fd = fd;
Guido van Rossumb0428152007-04-08 17:44:42 +0000240 }
241 else {
242 Py_BEGIN_ALLOW_THREADS
243 errno = 0;
244 self->fd = open(name, flags, 0666);
245 Py_END_ALLOW_THREADS
246 if (self->fd < 0 || dircheck(self) < 0) {
247 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
248 goto error;
249 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000250 }
251
252 goto done;
253
254 error:
255 ret = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000256
Guido van Rossuma9e20242007-03-08 00:43:48 +0000257 done:
258 PyMem_Free(name);
259 return ret;
260}
261
262static void
263fileio_dealloc(PyFileIOObject *self)
264{
265 if (self->weakreflist != NULL)
266 PyObject_ClearWeakRefs((PyObject *) self);
267
Guido van Rossum53807da2007-04-10 19:01:47 +0000268 if (self->fd >= 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000269 PyObject *closeresult = fileio_close(self);
270 if (closeresult == NULL) {
271#ifdef HAVE_STRERROR
Guido van Rossum53807da2007-04-10 19:01:47 +0000272 PySys_WriteStderr("close failed: [Errno %d] %s\n",
273 errno, strerror(errno));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000274#else
275 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
276#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000277 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000278 Py_DECREF(closeresult);
279 }
280
281 self->ob_type->tp_free((PyObject *)self);
282}
283
284static PyObject *
285err_closed(void)
286{
287 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
288 return NULL;
289}
290
291static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000292err_mode(char *action)
293{
294 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
295 return NULL;
296}
297
298static PyObject *
Guido van Rossuma9e20242007-03-08 00:43:48 +0000299fileio_fileno(PyFileIOObject *self)
300{
301 if (self->fd < 0)
302 return err_closed();
303 return PyInt_FromLong((long) self->fd);
304}
305
306static PyObject *
307fileio_readable(PyFileIOObject *self)
308{
309 if (self->fd < 0)
310 return err_closed();
311 return PyInt_FromLong((long) self->readable);
312}
313
314static PyObject *
315fileio_writable(PyFileIOObject *self)
316{
317 if (self->fd < 0)
318 return err_closed();
319 return PyInt_FromLong((long) self->writable);
320}
321
322static PyObject *
323fileio_seekable(PyFileIOObject *self)
324{
325 if (self->fd < 0)
326 return err_closed();
327 if (self->seekable < 0) {
328 int ret;
329 Py_BEGIN_ALLOW_THREADS
330 ret = lseek(self->fd, 0, SEEK_CUR);
331 Py_END_ALLOW_THREADS
332 if (ret < 0)
333 self->seekable = 0;
334 else
335 self->seekable = 1;
336 }
337 return PyInt_FromLong((long) self->seekable);
338}
339
340static PyObject *
341fileio_readinto(PyFileIOObject *self, PyObject *args)
342{
343 char *ptr;
344 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000345
Guido van Rossuma9e20242007-03-08 00:43:48 +0000346 if (self->fd < 0)
347 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000348 if (!self->readable)
349 return err_mode("reading");
350
Guido van Rossuma9e20242007-03-08 00:43:48 +0000351 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
352 return NULL;
353
354 Py_BEGIN_ALLOW_THREADS
355 errno = 0;
356 n = read(self->fd, ptr, n);
357 Py_END_ALLOW_THREADS
358 if (n < 0) {
359 if (errno == EAGAIN)
360 Py_RETURN_NONE;
361 PyErr_SetFromErrno(PyExc_IOError);
362 return NULL;
363 }
364
365 return PyInt_FromLong(n);
366}
367
Guido van Rossum7165cb12007-07-10 06:54:34 +0000368#define DEFAULT_BUFFER_SIZE (8*1024)
369
370static PyObject *
371fileio_readall(PyFileIOObject *self)
372{
373 PyObject *result;
374 Py_ssize_t total = 0;
375 int n;
376
377 result = PyBytes_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
378 if (result == NULL)
379 return NULL;
380
381 while (1) {
382 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
383 if (PyBytes_GET_SIZE(result) < newsize) {
384 if (PyBytes_Resize(result, newsize) < 0) {
385 if (total == 0) {
386 Py_DECREF(result);
387 return NULL;
388 }
389 PyErr_Clear();
390 break;
391 }
392 }
393 Py_BEGIN_ALLOW_THREADS
394 errno = 0;
395 n = read(self->fd,
396 PyBytes_AS_STRING(result) + total,
397 newsize - total);
398 Py_END_ALLOW_THREADS
399 if (n == 0)
400 break;
401 if (n < 0) {
402 if (total > 0)
403 break;
404 if (errno == EAGAIN) {
405 Py_DECREF(result);
406 Py_RETURN_NONE;
407 }
408 Py_DECREF(result);
409 PyErr_SetFromErrno(PyExc_IOError);
410 return NULL;
411 }
412 total += n;
413 }
414
415 if (PyBytes_GET_SIZE(result) > total) {
416 if (PyBytes_Resize(result, total) < 0) {
417 /* This should never happen, but just in case */
418 Py_DECREF(result);
419 return NULL;
420 }
421 }
422 return result;
423}
424
Guido van Rossuma9e20242007-03-08 00:43:48 +0000425static PyObject *
426fileio_read(PyFileIOObject *self, PyObject *args)
427{
428 char *ptr;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000429 Py_ssize_t n;
430 Py_ssize_t size = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000431 PyObject *bytes;
432
433 if (self->fd < 0)
434 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000435 if (!self->readable)
436 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000437
Guido van Rossum7165cb12007-07-10 06:54:34 +0000438 if (!PyArg_ParseTuple(args, "|i", &size))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000439 return NULL;
440
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000441 if (size < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000442 return fileio_readall(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000443 }
444
Guido van Rossuma9e20242007-03-08 00:43:48 +0000445 bytes = PyBytes_FromStringAndSize(NULL, size);
446 if (bytes == NULL)
447 return NULL;
448 ptr = PyBytes_AsString(bytes);
449
450 Py_BEGIN_ALLOW_THREADS
451 errno = 0;
452 n = read(self->fd, ptr, size);
453 Py_END_ALLOW_THREADS
454
455 if (n < 0) {
456 if (errno == EAGAIN)
457 Py_RETURN_NONE;
458 PyErr_SetFromErrno(PyExc_IOError);
459 return NULL;
460 }
461
462 if (n != size) {
463 if (PyBytes_Resize(bytes, n) < 0) {
464 Py_DECREF(bytes);
Guido van Rossum53807da2007-04-10 19:01:47 +0000465 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000466 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000467 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000468
469 return (PyObject *) bytes;
470}
471
472static PyObject *
473fileio_write(PyFileIOObject *self, PyObject *args)
474{
475 Py_ssize_t n;
476 char *ptr;
477
478 if (self->fd < 0)
479 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000480 if (!self->writable)
481 return err_mode("writing");
482
Guido van Rossuma9e20242007-03-08 00:43:48 +0000483 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
484 return NULL;
485
486 Py_BEGIN_ALLOW_THREADS
487 errno = 0;
488 n = write(self->fd, ptr, n);
489 Py_END_ALLOW_THREADS
490
491 if (n < 0) {
492 if (errno == EAGAIN)
493 Py_RETURN_NONE;
494 PyErr_SetFromErrno(PyExc_IOError);
495 return NULL;
496 }
497
498 return PyInt_FromLong(n);
499}
500
Guido van Rossum53807da2007-04-10 19:01:47 +0000501/* XXX Windows support below is likely incomplete */
502
503#if defined(MS_WIN64) || defined(MS_WINDOWS)
504typedef PY_LONG_LONG Py_off_t;
505#else
506typedef off_t Py_off_t;
507#endif
508
509/* Cribbed from posix_lseek() */
510static PyObject *
511portable_lseek(int fd, PyObject *posobj, int whence)
512{
513 Py_off_t pos, res;
514
515#ifdef SEEK_SET
516 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
517 switch (whence) {
518#if SEEK_SET != 0
519 case 0: whence = SEEK_SET; break;
520#endif
521#if SEEK_CUR != 1
522 case 1: whence = SEEK_CUR; break;
523#endif
524#if SEEL_END != 2
525 case 2: whence = SEEK_END; break;
526#endif
527 }
528#endif /* SEEK_SET */
529
530 if (posobj == NULL)
531 pos = 0;
532 else {
533#if !defined(HAVE_LARGEFILE_SUPPORT)
534 pos = PyInt_AsLong(posobj);
535#else
536 pos = PyLong_Check(posobj) ?
537 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
538#endif
539 if (PyErr_Occurred())
540 return NULL;
541 }
542
543 Py_BEGIN_ALLOW_THREADS
544#if defined(MS_WIN64) || defined(MS_WINDOWS)
545 res = _lseeki64(fd, pos, whence);
546#else
547 res = lseek(fd, pos, whence);
548#endif
549 Py_END_ALLOW_THREADS
550 if (res < 0)
551 return PyErr_SetFromErrno(PyExc_IOError);
552
553#if !defined(HAVE_LARGEFILE_SUPPORT)
554 return PyInt_FromLong(res);
555#else
556 return PyLong_FromLongLong(res);
557#endif
558}
559
Guido van Rossuma9e20242007-03-08 00:43:48 +0000560static PyObject *
561fileio_seek(PyFileIOObject *self, PyObject *args)
562{
Guido van Rossum53807da2007-04-10 19:01:47 +0000563 PyObject *posobj;
564 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000565
566 if (self->fd < 0)
567 return err_closed();
568
Guido van Rossum53807da2007-04-10 19:01:47 +0000569 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000570 return NULL;
571
Guido van Rossum53807da2007-04-10 19:01:47 +0000572 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000573}
574
575static PyObject *
576fileio_tell(PyFileIOObject *self, PyObject *args)
577{
Guido van Rossuma9e20242007-03-08 00:43:48 +0000578 if (self->fd < 0)
579 return err_closed();
580
Guido van Rossum53807da2007-04-10 19:01:47 +0000581 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000582}
583
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000584#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000585static PyObject *
586fileio_truncate(PyFileIOObject *self, PyObject *args)
587{
Guido van Rossum53807da2007-04-10 19:01:47 +0000588 PyObject *posobj = NULL;
589 Py_off_t pos;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000590 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000591
Guido van Rossum53807da2007-04-10 19:01:47 +0000592 fd = self->fd;
593 if (fd < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000594 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000595 if (!self->writable)
596 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000597
Guido van Rossum53807da2007-04-10 19:01:47 +0000598 if (!PyArg_ParseTuple(args, "|O", &posobj))
599 return NULL;
600
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000601 if (posobj == Py_None || posobj == NULL) {
602 posobj = portable_lseek(fd, NULL, 1);
603 if (posobj == NULL)
604 return NULL;
605 }
606 else {
607 Py_INCREF(posobj);
608 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000609
610#if !defined(HAVE_LARGEFILE_SUPPORT)
611 pos = PyInt_AsLong(posobj);
612#else
613 pos = PyLong_Check(posobj) ?
614 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
615#endif
Guido van Rossum87429772007-04-10 21:06:59 +0000616 if (PyErr_Occurred()) {
617 Py_DECREF(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000618 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000619 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000620
Guido van Rossuma9e20242007-03-08 00:43:48 +0000621 Py_BEGIN_ALLOW_THREADS
622 errno = 0;
Guido van Rossum53807da2007-04-10 19:01:47 +0000623 pos = ftruncate(fd, pos);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000624 Py_END_ALLOW_THREADS
625
Guido van Rossum87429772007-04-10 21:06:59 +0000626 if (pos < 0) {
627 Py_DECREF(posobj);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000628 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum87429772007-04-10 21:06:59 +0000629 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000630
Guido van Rossum87429772007-04-10 21:06:59 +0000631 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000632}
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000633#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000634
635static char *
636mode_string(PyFileIOObject *self)
637{
638 if (self->readable) {
639 if (self->writable)
640 return "r+";
641 else
642 return "r";
643 }
644 else
645 return "w";
646}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000647
648static PyObject *
649fileio_repr(PyFileIOObject *self)
650{
Guido van Rossum53807da2007-04-10 19:01:47 +0000651 if (self->fd < 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000652 return PyUnicode_FromFormat("_fileio._FileIO(-1)");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000653
Walter Dörwald1ab83302007-05-18 17:15:44 +0000654 return PyUnicode_FromFormat("_fileio._FileIO(%d, '%s')",
Guido van Rossum53807da2007-04-10 19:01:47 +0000655 self->fd, mode_string(self));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000656}
657
658static PyObject *
659fileio_isatty(PyFileIOObject *self)
660{
661 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000662
Guido van Rossuma9e20242007-03-08 00:43:48 +0000663 if (self->fd < 0)
664 return err_closed();
665 Py_BEGIN_ALLOW_THREADS
666 res = isatty(self->fd);
667 Py_END_ALLOW_THREADS
668 return PyBool_FromLong(res);
669}
670
Guido van Rossuma9e20242007-03-08 00:43:48 +0000671
672PyDoc_STRVAR(fileio_doc,
673"file(name: str[, mode: str]) -> file IO object\n"
674"\n"
675"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
676"writing or appending. The file will be created if it doesn't exist\n"
677"when opened for writing or appending; it will be truncated when\n"
678"opened for writing. Add a '+' to the mode to allow simultaneous\n"
679"reading and writing.");
680
681PyDoc_STRVAR(read_doc,
682"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
683"\n"
684"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000685"In non-blocking mode, returns None if no data is available.\n"
686"On end-of-file, returns ''.");
687
688PyDoc_STRVAR(readall_doc,
689"readall() -> bytes. read all data from the file, returned as bytes.\n"
690"\n"
691"In non-blocking mode, returns as much as is immediately available,\n"
692"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000693
694PyDoc_STRVAR(write_doc,
695"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
696"\n"
697"Only makes one system call, so not all of the data may be written.\n"
698"The number of bytes actually written is returned.");
699
700PyDoc_STRVAR(fileno_doc,
701"fileno() -> int. \"file descriptor\".\n"
702"\n"
703"This is needed for lower-level file interfaces, such the fcntl module.");
704
705PyDoc_STRVAR(seek_doc,
706"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
707"\n"
708"Argument offset is a byte count. Optional argument whence defaults to\n"
709"0 (offset from start of file, offset should be >= 0); other values are 1\n"
710"(move relative to current position, positive or negative), and 2 (move\n"
711"relative to end of file, usually negative, although many platforms allow\n"
712"seeking beyond the end of a file)."
713"\n"
714"Note that not all file objects are seekable.");
715
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000716#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000717PyDoc_STRVAR(truncate_doc,
718"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
719"\n"
720"Size defaults to the current file position, as returned by tell().");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000721#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000722
723PyDoc_STRVAR(tell_doc,
724"tell() -> int. Current file position");
725
726PyDoc_STRVAR(readinto_doc,
727"readinto() -> Undocumented. Don't use this; it may go away.");
728
729PyDoc_STRVAR(close_doc,
730"close() -> None. Close the file.\n"
731"\n"
732"A closed file cannot be used for further I/O operations. close() may be\n"
733"called more than once without error. Changes the fileno to -1.");
734
735PyDoc_STRVAR(isatty_doc,
736"isatty() -> bool. True if the file is connected to a tty device.");
737
Guido van Rossuma9e20242007-03-08 00:43:48 +0000738PyDoc_STRVAR(seekable_doc,
739"seekable() -> bool. True if file supports random-access.");
740
741PyDoc_STRVAR(readable_doc,
742"readable() -> bool. True if file was opened in a read mode.");
743
744PyDoc_STRVAR(writable_doc,
745"writable() -> bool. True if file was opened in a write mode.");
746
747static PyMethodDef fileio_methods[] = {
748 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
Guido van Rossum7165cb12007-07-10 06:54:34 +0000749 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000750 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
751 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
752 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
753 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000754#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000755 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000756#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000757 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
758 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
759 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
760 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
761 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
762 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000763 {NULL, NULL} /* sentinel */
764};
765
Guido van Rossum53807da2007-04-10 19:01:47 +0000766/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
767
Guido van Rossumb0428152007-04-08 17:44:42 +0000768static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000769get_closed(PyFileIOObject *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +0000770{
Guido van Rossum53807da2007-04-10 19:01:47 +0000771 return PyBool_FromLong((long)(self->fd < 0));
772}
773
774static PyObject *
775get_mode(PyFileIOObject *self, void *closure)
776{
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000777 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +0000778}
779
780static PyGetSetDef fileio_getsetlist[] = {
781 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Guido van Rossum53807da2007-04-10 19:01:47 +0000782 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Guido van Rossumb0428152007-04-08 17:44:42 +0000783 {0},
784};
785
Guido van Rossuma9e20242007-03-08 00:43:48 +0000786PyTypeObject PyFileIO_Type = {
787 PyObject_HEAD_INIT(&PyType_Type)
788 0,
789 "FileIO",
790 sizeof(PyFileIOObject),
791 0,
792 (destructor)fileio_dealloc, /* tp_dealloc */
793 0, /* tp_print */
794 0, /* tp_getattr */
795 0, /* tp_setattr */
796 0, /* tp_compare */
797 (reprfunc)fileio_repr, /* tp_repr */
798 0, /* tp_as_number */
799 0, /* tp_as_sequence */
800 0, /* tp_as_mapping */
801 0, /* tp_hash */
802 0, /* tp_call */
803 0, /* tp_str */
804 PyObject_GenericGetAttr, /* tp_getattro */
805 0, /* tp_setattro */
806 0, /* tp_as_buffer */
807 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
808 fileio_doc, /* tp_doc */
809 0, /* tp_traverse */
810 0, /* tp_clear */
811 0, /* tp_richcompare */
812 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
813 0, /* tp_iter */
814 0, /* tp_iternext */
815 fileio_methods, /* tp_methods */
816 0, /* tp_members */
Guido van Rossumb0428152007-04-08 17:44:42 +0000817 fileio_getsetlist, /* tp_getset */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000818 0, /* tp_base */
819 0, /* tp_dict */
820 0, /* tp_descr_get */
821 0, /* tp_descr_set */
822 0, /* tp_dictoffset */
823 fileio_init, /* tp_init */
824 PyType_GenericAlloc, /* tp_alloc */
825 fileio_new, /* tp_new */
826 PyObject_Del, /* tp_free */
827};
828
829static PyMethodDef module_methods[] = {
830 {NULL, NULL}
831};
832
833PyMODINIT_FUNC
834init_fileio(void)
835{
836 PyObject *m; /* a module object */
837
838 m = Py_InitModule3("_fileio", module_methods,
839 "Fast implementation of io.FileIO.");
840 if (m == NULL)
841 return;
842 if (PyType_Ready(&PyFileIO_Type) < 0)
843 return;
844 Py_INCREF(&PyFileIO_Type);
845 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
846}