blob: abd5d19836aa94ab14658e85826f909b42e8f87b [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 Hellerfdeee3a2007-07-12 11:21:36 +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
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000284 Py_Type(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000285}
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 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000340 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000341}
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
Neal Norwitz3c8ba932007-08-08 04:36:17 +0000441 if (!PyArg_ParseTuple(args, "|n", &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;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000593 int ret;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000594 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000595
Guido van Rossum53807da2007-04-10 19:01:47 +0000596 fd = self->fd;
597 if (fd < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000598 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000599 if (!self->writable)
600 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000601
Guido van Rossum53807da2007-04-10 19:01:47 +0000602 if (!PyArg_ParseTuple(args, "|O", &posobj))
603 return NULL;
604
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000605 if (posobj == Py_None || posobj == NULL) {
606 posobj = portable_lseek(fd, NULL, 1);
607 if (posobj == NULL)
608 return NULL;
609 }
610 else {
611 Py_INCREF(posobj);
612 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000613
614#if !defined(HAVE_LARGEFILE_SUPPORT)
615 pos = PyInt_AsLong(posobj);
616#else
617 pos = PyLong_Check(posobj) ?
618 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
619#endif
Guido van Rossum87429772007-04-10 21:06:59 +0000620 if (PyErr_Occurred()) {
621 Py_DECREF(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000622 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000623 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000624
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000625#ifdef MS_WINDOWS
626 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
627 so don't even try using it. */
628 {
629 HANDLE hFile;
630 PyObject *pos2;
631
632 /* Have to move current pos to desired endpoint on Windows. */
633 errno = 0;
634 pos2 = portable_lseek(fd, posobj, SEEK_SET);
635 if (pos2 == NULL)
636 {
637 Py_DECREF(posobj);
638 return NULL;
639 }
640 Py_DECREF(pos2);
641
642 /* Truncate. Note that this may grow the file! */
643 Py_BEGIN_ALLOW_THREADS
644 errno = 0;
645 hFile = (HANDLE)_get_osfhandle(fd);
646 ret = hFile == (HANDLE)-1;
647 if (ret == 0) {
648 ret = SetEndOfFile(hFile) == 0;
649 if (ret)
650 errno = EACCES;
651 }
652 Py_END_ALLOW_THREADS
653 }
654#else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000655 Py_BEGIN_ALLOW_THREADS
656 errno = 0;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000657 ret = ftruncate(fd, pos);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000658 Py_END_ALLOW_THREADS
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000659#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000660
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000661 if (ret != 0) {
Guido van Rossum87429772007-04-10 21:06:59 +0000662 Py_DECREF(posobj);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000663 PyErr_SetFromErrno(PyExc_IOError);
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000664 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000665 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000666
Guido van Rossum87429772007-04-10 21:06:59 +0000667 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000668}
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000669#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000670
671static char *
672mode_string(PyFileIOObject *self)
673{
674 if (self->readable) {
675 if (self->writable)
676 return "r+";
677 else
678 return "r";
679 }
680 else
681 return "w";
682}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000683
684static PyObject *
685fileio_repr(PyFileIOObject *self)
686{
Guido van Rossum53807da2007-04-10 19:01:47 +0000687 if (self->fd < 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000688 return PyUnicode_FromFormat("_fileio._FileIO(-1)");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000689
Walter Dörwald1ab83302007-05-18 17:15:44 +0000690 return PyUnicode_FromFormat("_fileio._FileIO(%d, '%s')",
Guido van Rossum53807da2007-04-10 19:01:47 +0000691 self->fd, mode_string(self));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000692}
693
694static PyObject *
695fileio_isatty(PyFileIOObject *self)
696{
697 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000698
Guido van Rossuma9e20242007-03-08 00:43:48 +0000699 if (self->fd < 0)
700 return err_closed();
701 Py_BEGIN_ALLOW_THREADS
702 res = isatty(self->fd);
703 Py_END_ALLOW_THREADS
704 return PyBool_FromLong(res);
705}
706
Guido van Rossuma9e20242007-03-08 00:43:48 +0000707
708PyDoc_STRVAR(fileio_doc,
709"file(name: str[, mode: str]) -> file IO object\n"
710"\n"
711"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
712"writing or appending. The file will be created if it doesn't exist\n"
713"when opened for writing or appending; it will be truncated when\n"
714"opened for writing. Add a '+' to the mode to allow simultaneous\n"
715"reading and writing.");
716
717PyDoc_STRVAR(read_doc,
718"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
719"\n"
720"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000721"In non-blocking mode, returns None if no data is available.\n"
722"On end-of-file, returns ''.");
723
724PyDoc_STRVAR(readall_doc,
725"readall() -> bytes. read all data from the file, returned as bytes.\n"
726"\n"
727"In non-blocking mode, returns as much as is immediately available,\n"
728"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000729
730PyDoc_STRVAR(write_doc,
731"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
732"\n"
733"Only makes one system call, so not all of the data may be written.\n"
734"The number of bytes actually written is returned.");
735
736PyDoc_STRVAR(fileno_doc,
737"fileno() -> int. \"file descriptor\".\n"
738"\n"
739"This is needed for lower-level file interfaces, such the fcntl module.");
740
741PyDoc_STRVAR(seek_doc,
742"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
743"\n"
744"Argument offset is a byte count. Optional argument whence defaults to\n"
745"0 (offset from start of file, offset should be >= 0); other values are 1\n"
746"(move relative to current position, positive or negative), and 2 (move\n"
747"relative to end of file, usually negative, although many platforms allow\n"
748"seeking beyond the end of a file)."
749"\n"
750"Note that not all file objects are seekable.");
751
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000752#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000753PyDoc_STRVAR(truncate_doc,
754"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
755"\n"
756"Size defaults to the current file position, as returned by tell().");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000757#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000758
759PyDoc_STRVAR(tell_doc,
760"tell() -> int. Current file position");
761
762PyDoc_STRVAR(readinto_doc,
763"readinto() -> Undocumented. Don't use this; it may go away.");
764
765PyDoc_STRVAR(close_doc,
766"close() -> None. Close the file.\n"
767"\n"
768"A closed file cannot be used for further I/O operations. close() may be\n"
769"called more than once without error. Changes the fileno to -1.");
770
771PyDoc_STRVAR(isatty_doc,
772"isatty() -> bool. True if the file is connected to a tty device.");
773
Guido van Rossuma9e20242007-03-08 00:43:48 +0000774PyDoc_STRVAR(seekable_doc,
775"seekable() -> bool. True if file supports random-access.");
776
777PyDoc_STRVAR(readable_doc,
778"readable() -> bool. True if file was opened in a read mode.");
779
780PyDoc_STRVAR(writable_doc,
781"writable() -> bool. True if file was opened in a write mode.");
782
783static PyMethodDef fileio_methods[] = {
784 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
Guido van Rossum7165cb12007-07-10 06:54:34 +0000785 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000786 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
787 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
788 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
789 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000790#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000791 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000792#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000793 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
794 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
795 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
796 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
797 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
798 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000799 {NULL, NULL} /* sentinel */
800};
801
Guido van Rossum53807da2007-04-10 19:01:47 +0000802/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
803
Guido van Rossumb0428152007-04-08 17:44:42 +0000804static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000805get_closed(PyFileIOObject *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +0000806{
Guido van Rossum53807da2007-04-10 19:01:47 +0000807 return PyBool_FromLong((long)(self->fd < 0));
808}
809
810static PyObject *
811get_mode(PyFileIOObject *self, void *closure)
812{
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000813 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +0000814}
815
816static PyGetSetDef fileio_getsetlist[] = {
817 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Guido van Rossum53807da2007-04-10 19:01:47 +0000818 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Guido van Rossumb0428152007-04-08 17:44:42 +0000819 {0},
820};
821
Guido van Rossuma9e20242007-03-08 00:43:48 +0000822PyTypeObject PyFileIO_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000823 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000824 "FileIO",
825 sizeof(PyFileIOObject),
826 0,
827 (destructor)fileio_dealloc, /* tp_dealloc */
828 0, /* tp_print */
829 0, /* tp_getattr */
830 0, /* tp_setattr */
831 0, /* tp_compare */
832 (reprfunc)fileio_repr, /* tp_repr */
833 0, /* tp_as_number */
834 0, /* tp_as_sequence */
835 0, /* tp_as_mapping */
836 0, /* tp_hash */
837 0, /* tp_call */
838 0, /* tp_str */
839 PyObject_GenericGetAttr, /* tp_getattro */
840 0, /* tp_setattro */
841 0, /* tp_as_buffer */
842 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
843 fileio_doc, /* tp_doc */
844 0, /* tp_traverse */
845 0, /* tp_clear */
846 0, /* tp_richcompare */
847 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
848 0, /* tp_iter */
849 0, /* tp_iternext */
850 fileio_methods, /* tp_methods */
851 0, /* tp_members */
Guido van Rossumb0428152007-04-08 17:44:42 +0000852 fileio_getsetlist, /* tp_getset */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000853 0, /* tp_base */
854 0, /* tp_dict */
855 0, /* tp_descr_get */
856 0, /* tp_descr_set */
857 0, /* tp_dictoffset */
858 fileio_init, /* tp_init */
859 PyType_GenericAlloc, /* tp_alloc */
860 fileio_new, /* tp_new */
861 PyObject_Del, /* tp_free */
862};
863
864static PyMethodDef module_methods[] = {
865 {NULL, NULL}
866};
867
868PyMODINIT_FUNC
869init_fileio(void)
870{
871 PyObject *m; /* a module object */
872
873 m = Py_InitModule3("_fileio", module_methods,
874 "Fast implementation of io.FileIO.");
875 if (m == NULL)
876 return;
877 if (PyType_Ready(&PyFileIO_Type) < 0)
878 return;
879 Py_INCREF(&PyFileIO_Type);
880 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
881}