blob: 2a86e07e4369f707a7b044e812ce99050c67ca10 [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) {
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +000064 self->fd = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000065 Py_RETURN_NONE;
66 }
67 errno = internal_close(self);
68 if (errno < 0) {
69 PyErr_SetFromErrno(PyExc_IOError);
70 return NULL;
71 }
72
73 Py_RETURN_NONE;
74}
75
76static PyObject *
77fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews)
78{
79 PyFileIOObject *self;
80
81 assert(type != NULL && type->tp_alloc != NULL);
82
83 self = (PyFileIOObject *) type->tp_alloc(type, 0);
84 if (self != NULL) {
85 self->fd = -1;
Christian Heimesab5f8792008-10-30 21:26:15 +000086 self->readable = 0;
87 self->writable = 0;
88 self->seekable = -1;
89 self->closefd = 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000090 self->weakreflist = NULL;
91 }
92
93 return (PyObject *) self;
94}
95
96/* On Unix, open will succeed for directories.
97 In Python, there should be no file objects referring to
98 directories, so we need a check. */
99
100static int
Benjamin Peterson7af65562008-12-29 17:56:58 +0000101dircheck(PyFileIOObject* self, char *name)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000102{
103#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
104 struct stat buf;
105 if (self->fd < 0)
106 return 0;
107 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000108 char *msg = strerror(EISDIR);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000109 PyObject *exc;
110 internal_close(self);
111
Benjamin Peterson7af65562008-12-29 17:56:58 +0000112 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
113 EISDIR, msg, name);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000114 PyErr_SetObject(PyExc_IOError, exc);
115 Py_XDECREF(exc);
116 return -1;
117 }
118#endif
119 return 0;
120}
121
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000122static int
123check_fd(int fd)
124{
125#if defined(HAVE_FSTAT)
126 struct stat buf;
127 if (fstat(fd, &buf) < 0 && errno == EBADF) {
128 PyObject *exc;
129 char *msg = strerror(EBADF);
130 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
131 EBADF, msg);
132 PyErr_SetObject(PyExc_OSError, exc);
133 Py_XDECREF(exc);
134 return -1;
135 }
136#endif
137 return 0;
138}
139
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000140
141static int
142fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
143{
144 PyFileIOObject *self = (PyFileIOObject *) oself;
145 static char *kwlist[] = {"file", "mode", "closefd", NULL};
146 char *name = NULL;
147 char *mode = "r";
148 char *s;
149#ifdef MS_WINDOWS
150 Py_UNICODE *widename = NULL;
151#endif
152 int ret = 0;
153 int rwa = 0, plus = 0, append = 0;
154 int flags = 0;
155 int fd = -1;
156 int closefd = 1;
157
158 assert(PyFileIO_Check(oself));
159 if (self->fd >= 0) {
160 /* Have to close the existing file first. */
161 if (internal_close(self) < 0)
162 return -1;
163 }
164
165 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio",
166 kwlist, &fd, &mode, &closefd)) {
167 if (fd < 0) {
168 PyErr_SetString(PyExc_ValueError,
169 "Negative filedescriptor");
170 return -1;
171 }
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000172 if (check_fd(fd))
173 return -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000174 }
175 else {
176 PyErr_Clear();
177
178#ifdef Py_WIN_WIDE_FILENAMES
179 if (GetVersion() < 0x80000000) {
180 /* On NT, so wide API available */
181 PyObject *po;
182 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio",
183 kwlist, &po, &mode, &closefd)
184 ) {
185 widename = PyUnicode_AS_UNICODE(po);
186 } else {
187 /* Drop the argument parsing error as narrow
188 strings are also valid. */
189 PyErr_Clear();
190 }
191 }
192 if (widename == NULL)
193#endif
194 {
195 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio",
196 kwlist,
197 Py_FileSystemDefaultEncoding,
198 &name, &mode, &closefd))
Neal Norwitz901e4712008-08-24 22:03:05 +0000199 return -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000200 }
201 }
202
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000203 s = mode;
204 while (*s) {
205 switch (*s++) {
206 case 'r':
207 if (rwa) {
208 bad_mode:
209 PyErr_SetString(PyExc_ValueError,
210 "Must have exactly one of read/write/append mode");
211 goto error;
212 }
213 rwa = 1;
214 self->readable = 1;
215 break;
216 case 'w':
217 if (rwa)
218 goto bad_mode;
219 rwa = 1;
220 self->writable = 1;
221 flags |= O_CREAT | O_TRUNC;
222 break;
223 case 'a':
224 if (rwa)
225 goto bad_mode;
226 rwa = 1;
227 self->writable = 1;
228 flags |= O_CREAT;
229 append = 1;
230 break;
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000231 case 'b':
232 break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000233 case '+':
234 if (plus)
235 goto bad_mode;
236 self->readable = self->writable = 1;
237 plus = 1;
238 break;
239 default:
240 PyErr_Format(PyExc_ValueError,
241 "invalid mode: %.200s", mode);
242 goto error;
243 }
244 }
245
246 if (!rwa)
247 goto bad_mode;
248
249 if (self->readable && self->writable)
250 flags |= O_RDWR;
251 else if (self->readable)
252 flags |= O_RDONLY;
253 else
254 flags |= O_WRONLY;
255
256#ifdef O_BINARY
257 flags |= O_BINARY;
258#endif
259
260#ifdef O_APPEND
261 if (append)
262 flags |= O_APPEND;
263#endif
264
265 if (fd >= 0) {
266 self->fd = fd;
267 self->closefd = closefd;
268 }
269 else {
270 self->closefd = 1;
271 if (!closefd) {
272 PyErr_SetString(PyExc_ValueError,
Amaury Forgeot d'Arc9f616f42008-10-29 23:15:57 +0000273 "Cannot use closefd=False with file name");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000274 goto error;
275 }
276
277 Py_BEGIN_ALLOW_THREADS
278 errno = 0;
279#ifdef MS_WINDOWS
280 if (widename != NULL)
281 self->fd = _wopen(widename, flags, 0666);
282 else
283#endif
284 self->fd = open(name, flags, 0666);
285 Py_END_ALLOW_THREADS
Benjamin Petersonf22c26e2008-09-01 14:13:43 +0000286 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000287#ifdef MS_WINDOWS
Hirokazu Yamamoto99a1b202009-01-01 15:45:39 +0000288 if (widename != NULL)
289 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
290 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000291#endif
Hirokazu Yamamoto99a1b202009-01-01 15:45:39 +0000292 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000293 goto error;
294 }
Benjamin Peterson7af65562008-12-29 17:56:58 +0000295 if(dircheck(self, name) < 0)
Benjamin Petersonf22c26e2008-09-01 14:13:43 +0000296 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000297 }
298
299 goto done;
300
301 error:
302 ret = -1;
303
304 done:
Neal Norwitz18aa3882008-08-24 05:04:52 +0000305 PyMem_Free(name);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000306 return ret;
307}
308
309static void
310fileio_dealloc(PyFileIOObject *self)
311{
312 if (self->weakreflist != NULL)
313 PyObject_ClearWeakRefs((PyObject *) self);
314
315 if (self->fd >= 0 && self->closefd) {
316 errno = internal_close(self);
317 if (errno < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000318 PySys_WriteStderr("close failed: [Errno %d] %s\n",
319 errno, strerror(errno));
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000320 }
321 }
322
323 Py_TYPE(self)->tp_free((PyObject *)self);
324}
325
326static PyObject *
327err_closed(void)
328{
329 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
330 return NULL;
331}
332
333static PyObject *
334err_mode(char *action)
335{
336 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
337 return NULL;
338}
339
340static PyObject *
341fileio_fileno(PyFileIOObject *self)
342{
343 if (self->fd < 0)
344 return err_closed();
345 return PyInt_FromLong((long) self->fd);
346}
347
348static PyObject *
349fileio_readable(PyFileIOObject *self)
350{
351 if (self->fd < 0)
352 return err_closed();
353 return PyBool_FromLong((long) self->readable);
354}
355
356static PyObject *
357fileio_writable(PyFileIOObject *self)
358{
359 if (self->fd < 0)
360 return err_closed();
361 return PyBool_FromLong((long) self->writable);
362}
363
364static PyObject *
365fileio_seekable(PyFileIOObject *self)
366{
367 if (self->fd < 0)
368 return err_closed();
369 if (self->seekable < 0) {
370 int ret;
371 Py_BEGIN_ALLOW_THREADS
372 ret = lseek(self->fd, 0, SEEK_CUR);
373 Py_END_ALLOW_THREADS
374 if (ret < 0)
375 self->seekable = 0;
376 else
377 self->seekable = 1;
378 }
379 return PyBool_FromLong((long) self->seekable);
380}
381
382static PyObject *
383fileio_readinto(PyFileIOObject *self, PyObject *args)
384{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000385 Py_buffer pbuf;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000386 Py_ssize_t n;
387
388 if (self->fd < 0)
389 return err_closed();
390 if (!self->readable)
391 return err_mode("reading");
392
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000393 if (!PyArg_ParseTuple(args, "w*", &pbuf))
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000394 return NULL;
395
396 Py_BEGIN_ALLOW_THREADS
397 errno = 0;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000398 n = read(self->fd, pbuf.buf, pbuf.len);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000399 Py_END_ALLOW_THREADS
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000400 PyBuffer_Release(&pbuf);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000401 if (n < 0) {
402 if (errno == EAGAIN)
403 Py_RETURN_NONE;
404 PyErr_SetFromErrno(PyExc_IOError);
405 return NULL;
406 }
407
408 return PyLong_FromSsize_t(n);
409}
410
411#define DEFAULT_BUFFER_SIZE (8*1024)
412
413static PyObject *
414fileio_readall(PyFileIOObject *self)
415{
416 PyObject *result;
417 Py_ssize_t total = 0;
418 int n;
419
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000420 result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000421 if (result == NULL)
422 return NULL;
423
424 while (1) {
425 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000426 if (PyString_GET_SIZE(result) < newsize) {
427 if (_PyString_Resize(&result, newsize) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000428 if (total == 0) {
429 Py_DECREF(result);
430 return NULL;
431 }
432 PyErr_Clear();
433 break;
434 }
435 }
436 Py_BEGIN_ALLOW_THREADS
437 errno = 0;
438 n = read(self->fd,
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000439 PyString_AS_STRING(result) + total,
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000440 newsize - total);
441 Py_END_ALLOW_THREADS
442 if (n == 0)
443 break;
444 if (n < 0) {
445 if (total > 0)
446 break;
447 if (errno == EAGAIN) {
448 Py_DECREF(result);
449 Py_RETURN_NONE;
450 }
451 Py_DECREF(result);
452 PyErr_SetFromErrno(PyExc_IOError);
453 return NULL;
454 }
455 total += n;
456 }
457
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000458 if (PyString_GET_SIZE(result) > total) {
459 if (_PyString_Resize(&result, total) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000460 /* This should never happen, but just in case */
461 Py_DECREF(result);
462 return NULL;
463 }
464 }
465 return result;
466}
467
468static PyObject *
469fileio_read(PyFileIOObject *self, PyObject *args)
470{
471 char *ptr;
472 Py_ssize_t n;
473 Py_ssize_t size = -1;
474 PyObject *bytes;
475
476 if (self->fd < 0)
477 return err_closed();
478 if (!self->readable)
479 return err_mode("reading");
480
481 if (!PyArg_ParseTuple(args, "|n", &size))
482 return NULL;
483
484 if (size < 0) {
485 return fileio_readall(self);
486 }
487
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000488 bytes = PyString_FromStringAndSize(NULL, size);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000489 if (bytes == NULL)
490 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000491 ptr = PyString_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000492
493 Py_BEGIN_ALLOW_THREADS
494 errno = 0;
495 n = read(self->fd, ptr, size);
496 Py_END_ALLOW_THREADS
497
498 if (n < 0) {
499 if (errno == EAGAIN)
500 Py_RETURN_NONE;
501 PyErr_SetFromErrno(PyExc_IOError);
502 return NULL;
503 }
504
505 if (n != size) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000506 if (_PyString_Resize(&bytes, n) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000507 Py_DECREF(bytes);
508 return NULL;
509 }
510 }
511
512 return (PyObject *) bytes;
513}
514
515static PyObject *
516fileio_write(PyFileIOObject *self, PyObject *args)
517{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000518 Py_buffer pbuf;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000519 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000520
521 if (self->fd < 0)
522 return err_closed();
523 if (!self->writable)
524 return err_mode("writing");
525
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000526 if (!PyArg_ParseTuple(args, "s*", &pbuf))
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000527 return NULL;
528
529 Py_BEGIN_ALLOW_THREADS
530 errno = 0;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000531 n = write(self->fd, pbuf.buf, pbuf.len);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000532 Py_END_ALLOW_THREADS
533
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000534 PyBuffer_Release(&pbuf);
535
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000536 if (n < 0) {
537 if (errno == EAGAIN)
538 Py_RETURN_NONE;
539 PyErr_SetFromErrno(PyExc_IOError);
540 return NULL;
541 }
542
543 return PyLong_FromSsize_t(n);
544}
545
546/* XXX Windows support below is likely incomplete */
547
548#if defined(MS_WIN64) || defined(MS_WINDOWS)
549typedef PY_LONG_LONG Py_off_t;
550#else
551typedef off_t Py_off_t;
552#endif
553
554/* Cribbed from posix_lseek() */
555static PyObject *
556portable_lseek(int fd, PyObject *posobj, int whence)
557{
558 Py_off_t pos, res;
559
560#ifdef SEEK_SET
561 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
562 switch (whence) {
563#if SEEK_SET != 0
564 case 0: whence = SEEK_SET; break;
565#endif
566#if SEEK_CUR != 1
567 case 1: whence = SEEK_CUR; break;
568#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000569#if SEEK_END != 2
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000570 case 2: whence = SEEK_END; break;
571#endif
572 }
573#endif /* SEEK_SET */
574
575 if (posobj == NULL)
576 pos = 0;
577 else {
578 if(PyFloat_Check(posobj)) {
579 PyErr_SetString(PyExc_TypeError, "an integer is required");
580 return NULL;
581 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000582#if defined(HAVE_LARGEFILE_SUPPORT)
583 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000584#else
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000585 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000586#endif
587 if (PyErr_Occurred())
588 return NULL;
589 }
590
591 Py_BEGIN_ALLOW_THREADS
592#if defined(MS_WIN64) || defined(MS_WINDOWS)
593 res = _lseeki64(fd, pos, whence);
594#else
595 res = lseek(fd, pos, whence);
596#endif
597 Py_END_ALLOW_THREADS
598 if (res < 0)
599 return PyErr_SetFromErrno(PyExc_IOError);
600
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000601#if defined(HAVE_LARGEFILE_SUPPORT)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000602 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000603#else
604 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000605#endif
606}
607
608static PyObject *
609fileio_seek(PyFileIOObject *self, PyObject *args)
610{
611 PyObject *posobj;
612 int whence = 0;
613
614 if (self->fd < 0)
615 return err_closed();
616
617 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
618 return NULL;
619
620 return portable_lseek(self->fd, posobj, whence);
621}
622
623static PyObject *
624fileio_tell(PyFileIOObject *self, PyObject *args)
625{
626 if (self->fd < 0)
627 return err_closed();
628
629 return portable_lseek(self->fd, NULL, 1);
630}
631
632#ifdef HAVE_FTRUNCATE
633static PyObject *
634fileio_truncate(PyFileIOObject *self, PyObject *args)
635{
636 PyObject *posobj = NULL;
637 Py_off_t pos;
638 int ret;
639 int fd;
640
641 fd = self->fd;
642 if (fd < 0)
643 return err_closed();
644 if (!self->writable)
645 return err_mode("writing");
646
647 if (!PyArg_ParseTuple(args, "|O", &posobj))
648 return NULL;
649
650 if (posobj == Py_None || posobj == NULL) {
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000651 /* Get the current position. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000652 posobj = portable_lseek(fd, NULL, 1);
653 if (posobj == NULL)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000654 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000655 }
656 else {
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000657 /* Move to the position to be truncated. */
658 posobj = portable_lseek(fd, posobj, 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000659 }
660
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000661#if defined(HAVE_LARGEFILE_SUPPORT)
662 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000663#else
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000664 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000665#endif
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000666 if (PyErr_Occurred())
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000667 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000668
669#ifdef MS_WINDOWS
670 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
671 so don't even try using it. */
672 {
673 HANDLE hFile;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000674
675 /* Truncate. Note that this may grow the file! */
676 Py_BEGIN_ALLOW_THREADS
677 errno = 0;
678 hFile = (HANDLE)_get_osfhandle(fd);
679 ret = hFile == (HANDLE)-1;
680 if (ret == 0) {
681 ret = SetEndOfFile(hFile) == 0;
682 if (ret)
683 errno = EACCES;
684 }
685 Py_END_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000686 }
687#else
688 Py_BEGIN_ALLOW_THREADS
689 errno = 0;
690 ret = ftruncate(fd, pos);
691 Py_END_ALLOW_THREADS
692#endif /* !MS_WINDOWS */
693
694 if (ret != 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000695 PyErr_SetFromErrno(PyExc_IOError);
696 return NULL;
697 }
698
699 return posobj;
700}
701#endif
702
703static char *
704mode_string(PyFileIOObject *self)
705{
706 if (self->readable) {
707 if (self->writable)
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000708 return "rb+";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000709 else
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000710 return "rb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000711 }
712 else
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000713 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000714}
715
716static PyObject *
717fileio_repr(PyFileIOObject *self)
718{
719 if (self->fd < 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000720 return PyString_FromFormat("_fileio._FileIO(-1)");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000721
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000722 return PyString_FromFormat("_fileio._FileIO(%d, '%s')",
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000723 self->fd, mode_string(self));
724}
725
726static PyObject *
727fileio_isatty(PyFileIOObject *self)
728{
729 long res;
730
731 if (self->fd < 0)
732 return err_closed();
733 Py_BEGIN_ALLOW_THREADS
734 res = isatty(self->fd);
735 Py_END_ALLOW_THREADS
736 return PyBool_FromLong(res);
737}
738
739
740PyDoc_STRVAR(fileio_doc,
741"file(name: str[, mode: str]) -> file IO object\n"
742"\n"
743"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
744"writing or appending. The file will be created if it doesn't exist\n"
745"when opened for writing or appending; it will be truncated when\n"
746"opened for writing. Add a '+' to the mode to allow simultaneous\n"
747"reading and writing.");
748
749PyDoc_STRVAR(read_doc,
750"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
751"\n"
752"Only makes one system call, so less data may be returned than requested\n"
753"In non-blocking mode, returns None if no data is available.\n"
754"On end-of-file, returns ''.");
755
756PyDoc_STRVAR(readall_doc,
757"readall() -> bytes. read all data from the file, returned as bytes.\n"
758"\n"
759"In non-blocking mode, returns as much as is immediately available,\n"
760"or None if no data is available. On end-of-file, returns ''.");
761
762PyDoc_STRVAR(write_doc,
763"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
764"\n"
765"Only makes one system call, so not all of the data may be written.\n"
766"The number of bytes actually written is returned.");
767
768PyDoc_STRVAR(fileno_doc,
769"fileno() -> int. \"file descriptor\".\n"
770"\n"
771"This is needed for lower-level file interfaces, such the fcntl module.");
772
773PyDoc_STRVAR(seek_doc,
774"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
775"\n"
776"Argument offset is a byte count. Optional argument whence defaults to\n"
777"0 (offset from start of file, offset should be >= 0); other values are 1\n"
778"(move relative to current position, positive or negative), and 2 (move\n"
779"relative to end of file, usually negative, although many platforms allow\n"
780"seeking beyond the end of a file)."
781"\n"
782"Note that not all file objects are seekable.");
783
784#ifdef HAVE_FTRUNCATE
785PyDoc_STRVAR(truncate_doc,
786"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
787"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000788"Size defaults to the current file position, as returned by tell()."
789"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000790#endif
791
792PyDoc_STRVAR(tell_doc,
793"tell() -> int. Current file position");
794
795PyDoc_STRVAR(readinto_doc,
796"readinto() -> Undocumented. Don't use this; it may go away.");
797
798PyDoc_STRVAR(close_doc,
799"close() -> None. Close the file.\n"
800"\n"
801"A closed file cannot be used for further I/O operations. close() may be\n"
802"called more than once without error. Changes the fileno to -1.");
803
804PyDoc_STRVAR(isatty_doc,
805"isatty() -> bool. True if the file is connected to a tty device.");
806
807PyDoc_STRVAR(seekable_doc,
808"seekable() -> bool. True if file supports random-access.");
809
810PyDoc_STRVAR(readable_doc,
811"readable() -> bool. True if file was opened in a read mode.");
812
813PyDoc_STRVAR(writable_doc,
814"writable() -> bool. True if file was opened in a write mode.");
815
816static PyMethodDef fileio_methods[] = {
817 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
818 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
819 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
820 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
821 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
822 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
823#ifdef HAVE_FTRUNCATE
824 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
825#endif
826 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
827 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
828 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
829 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
830 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
831 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
832 {NULL, NULL} /* sentinel */
833};
834
835/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
836
837static PyObject *
838get_closed(PyFileIOObject *self, void *closure)
839{
840 return PyBool_FromLong((long)(self->fd < 0));
841}
842
843static PyObject *
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000844get_closefd(PyFileIOObject *self, void *closure)
845{
846 return PyBool_FromLong((long)(self->closefd));
847}
848
849static PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000850get_mode(PyFileIOObject *self, void *closure)
851{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000852 return PyString_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000853}
854
855static PyGetSetDef fileio_getsetlist[] = {
856 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000857 {"closefd", (getter)get_closefd, NULL,
858 "True if the file descriptor will be closed"},
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000859 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
860 {0},
861};
862
863PyTypeObject PyFileIO_Type = {
Hirokazu Yamamoto09979a12008-09-23 16:11:09 +0000864 PyVarObject_HEAD_INIT(NULL, 0)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000865 "_FileIO",
866 sizeof(PyFileIOObject),
867 0,
868 (destructor)fileio_dealloc, /* tp_dealloc */
869 0, /* tp_print */
870 0, /* tp_getattr */
871 0, /* tp_setattr */
872 0, /* tp_compare */
873 (reprfunc)fileio_repr, /* tp_repr */
874 0, /* tp_as_number */
875 0, /* tp_as_sequence */
876 0, /* tp_as_mapping */
877 0, /* tp_hash */
878 0, /* tp_call */
879 0, /* tp_str */
880 PyObject_GenericGetAttr, /* tp_getattro */
881 0, /* tp_setattro */
882 0, /* tp_as_buffer */
883 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
884 fileio_doc, /* tp_doc */
885 0, /* tp_traverse */
886 0, /* tp_clear */
887 0, /* tp_richcompare */
888 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
889 0, /* tp_iter */
890 0, /* tp_iternext */
891 fileio_methods, /* tp_methods */
892 0, /* tp_members */
893 fileio_getsetlist, /* tp_getset */
894 0, /* tp_base */
895 0, /* tp_dict */
896 0, /* tp_descr_get */
897 0, /* tp_descr_set */
898 0, /* tp_dictoffset */
899 fileio_init, /* tp_init */
900 PyType_GenericAlloc, /* tp_alloc */
901 fileio_new, /* tp_new */
902 PyObject_Del, /* tp_free */
903};
904
905static PyMethodDef module_methods[] = {
906 {NULL, NULL}
907};
908
909PyMODINIT_FUNC
910init_fileio(void)
911{
912 PyObject *m; /* a module object */
913
914 m = Py_InitModule3("_fileio", module_methods,
915 "Fast implementation of io.FileIO.");
916 if (m == NULL)
917 return;
918 if (PyType_Ready(&PyFileIO_Type) < 0)
919 return;
920 Py_INCREF(&PyFileIO_Type);
921 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
922}