blob: 2895b286bf5a535eeaba174678d3576e927be065 [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;
Neal Norwitz88b44da2007-08-12 17:23:54 +000033 unsigned readable : 1;
34 unsigned writable : 1;
35 int seekable : 2; /* -1 means unknown */
Guido van Rossuma9e20242007-03-08 00:43:48 +000036 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
Neal Norwitz88b44da2007-08-12 17:23:54 +000043/* Returns 0 on success, errno (which is < 0) on failure. */
44static int
45internal_close(PyFileIOObject *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000046{
Neal Norwitz88b44da2007-08-12 17:23:54 +000047 int save_errno = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +000048 if (self->fd >= 0) {
Guido van Rossumb0428152007-04-08 17:44:42 +000049 int fd = self->fd;
50 self->fd = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +000051 Py_BEGIN_ALLOW_THREADS
Neal Norwitz88b44da2007-08-12 17:23:54 +000052 if (close(fd) < 0)
53 save_errno = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +000054 Py_END_ALLOW_THREADS
Neal Norwitz88b44da2007-08-12 17:23:54 +000055 }
56 return save_errno;
57}
58
59static PyObject *
60fileio_close(PyFileIOObject *self)
61{
62 errno = internal_close(self);
63 if (errno < 0) {
64 PyErr_SetFromErrno(PyExc_IOError);
65 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +000066 }
67
68 Py_RETURN_NONE;
69}
70
71static PyObject *
72fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews)
73{
74 PyFileIOObject *self;
75
76 assert(type != NULL && type->tp_alloc != NULL);
77
78 self = (PyFileIOObject *) type->tp_alloc(type, 0);
79 if (self != NULL) {
80 self->fd = -1;
81 self->weakreflist = NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +000082 }
83
84 return (PyObject *) self;
85}
86
87/* On Unix, open will succeed for directories.
88 In Python, there should be no file objects referring to
89 directories, so we need a check. */
90
91static int
92dircheck(PyFileIOObject* self)
93{
94#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
95 struct stat buf;
96 if (self->fd < 0)
97 return 0;
98 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
99#ifdef HAVE_STRERROR
100 char *msg = strerror(EISDIR);
101#else
102 char *msg = "Is a directory";
103#endif
104 PyObject *exc;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000105 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000106
Guido van Rossuma9e20242007-03-08 00:43:48 +0000107 exc = PyObject_CallFunction(PyExc_IOError, "(is)",
108 EISDIR, msg);
109 PyErr_SetObject(PyExc_IOError, exc);
110 Py_XDECREF(exc);
111 return -1;
112 }
113#endif
114 return 0;
115}
116
117
118static int
119fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
120{
121 PyFileIOObject *self = (PyFileIOObject *) oself;
Guido van Rossumb0428152007-04-08 17:44:42 +0000122 static char *kwlist[] = {"file", "mode", NULL};
Guido van Rossuma9e20242007-03-08 00:43:48 +0000123 char *name = NULL;
124 char *mode = "r";
Guido van Rossum53807da2007-04-10 19:01:47 +0000125 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000126#ifdef MS_WINDOWS
127 Py_UNICODE *widename = NULL;
128#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000129 int ret = 0;
130 int rwa = 0, plus = 0, append = 0;
131 int flags = 0;
Guido van Rossumb0428152007-04-08 17:44:42 +0000132 int fd = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000133
134 assert(PyFileIO_Check(oself));
Neal Norwitz88b44da2007-08-12 17:23:54 +0000135 if (self->fd >= 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000136 /* Have to close the existing file first. */
Neal Norwitz88b44da2007-08-12 17:23:54 +0000137 if (internal_close(self) < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000138 return -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000139 }
140
Guido van Rossumb0428152007-04-08 17:44:42 +0000141 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|s:fileio",
142 kwlist, &fd, &mode)) {
143 if (fd < 0) {
144 PyErr_SetString(PyExc_ValueError,
145 "Negative filedescriptor");
146 return -1;
147 }
148 }
149 else {
150 PyErr_Clear();
151
Guido van Rossuma9e20242007-03-08 00:43:48 +0000152#ifdef Py_WIN_WIDE_FILENAMES
Guido van Rossumb0428152007-04-08 17:44:42 +0000153 if (GetVersion() < 0x80000000) {
154 /* On NT, so wide API available */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000155 PyObject *po;
156 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|s:fileio",
157 kwlist, &po, &mode)) {
Thomas Helleraf2be262007-07-12 11:03:13 +0000158 widename = PyUnicode_AS_UNICODE(po);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000159 } else {
160 /* Drop the argument parsing error as narrow
161 strings are also valid. */
162 PyErr_Clear();
163 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000164 }
Thomas Helleraf2be262007-07-12 11:03:13 +0000165 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000166#endif
Thomas Helleraf2be262007-07-12 11:03:13 +0000167 {
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;
Thomas Helleraf2be262007-07-12 11:03:13 +0000177 self->seekable = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000178 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;
Thomas Helleraf2be262007-07-12 11:03:13 +0000244#ifdef MS_WINDOWS
245 if (widename != NULL)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000246 self->fd = _wopen(widename, flags, 0666);
Thomas Helleraf2be262007-07-12 11:03:13 +0000247 else
248#endif
Neal Norwitz88b44da2007-08-12 17:23:54 +0000249 self->fd = open(name, flags, 0666);
Guido van Rossumb0428152007-04-08 17:44:42 +0000250 Py_END_ALLOW_THREADS
251 if (self->fd < 0 || dircheck(self) < 0) {
252 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
253 goto error;
254 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000255 }
256
257 goto done;
258
259 error:
260 ret = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000261
Guido van Rossuma9e20242007-03-08 00:43:48 +0000262 done:
263 PyMem_Free(name);
264 return ret;
265}
266
267static void
268fileio_dealloc(PyFileIOObject *self)
269{
270 if (self->weakreflist != NULL)
271 PyObject_ClearWeakRefs((PyObject *) self);
272
Guido van Rossum53807da2007-04-10 19:01:47 +0000273 if (self->fd >= 0) {
Neal Norwitz88b44da2007-08-12 17:23:54 +0000274 errno = internal_close(self);
275 if (errno < 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000276#ifdef HAVE_STRERROR
Guido van Rossum53807da2007-04-10 19:01:47 +0000277 PySys_WriteStderr("close failed: [Errno %d] %s\n",
278 errno, strerror(errno));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000279#else
280 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
281#endif
Neal Norwitz88b44da2007-08-12 17:23:54 +0000282 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000283 }
284
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000285 Py_Type(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000286}
287
288static PyObject *
289err_closed(void)
290{
291 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
292 return NULL;
293}
294
295static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000296err_mode(char *action)
297{
298 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
299 return NULL;
300}
301
302static PyObject *
Guido van Rossuma9e20242007-03-08 00:43:48 +0000303fileio_fileno(PyFileIOObject *self)
304{
305 if (self->fd < 0)
306 return err_closed();
307 return PyInt_FromLong((long) self->fd);
308}
309
310static PyObject *
311fileio_readable(PyFileIOObject *self)
312{
313 if (self->fd < 0)
314 return err_closed();
Neal Norwitz88b44da2007-08-12 17:23:54 +0000315 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000316}
317
318static PyObject *
319fileio_writable(PyFileIOObject *self)
320{
321 if (self->fd < 0)
322 return err_closed();
Neal Norwitz88b44da2007-08-12 17:23:54 +0000323 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000324}
325
326static PyObject *
327fileio_seekable(PyFileIOObject *self)
328{
329 if (self->fd < 0)
330 return err_closed();
331 if (self->seekable < 0) {
332 int ret;
333 Py_BEGIN_ALLOW_THREADS
334 ret = lseek(self->fd, 0, SEEK_CUR);
335 Py_END_ALLOW_THREADS
336 if (ret < 0)
337 self->seekable = 0;
338 else
339 self->seekable = 1;
340 }
Neal Norwitz88b44da2007-08-12 17:23:54 +0000341 /* XXX(nnorwitz): should this return an int rather than a bool,
342 since seekable could be -1, 0, or 1? */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000343 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000344}
345
346static PyObject *
347fileio_readinto(PyFileIOObject *self, PyObject *args)
348{
349 char *ptr;
350 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000351
Guido van Rossuma9e20242007-03-08 00:43:48 +0000352 if (self->fd < 0)
353 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000354 if (!self->readable)
355 return err_mode("reading");
356
Guido van Rossuma9e20242007-03-08 00:43:48 +0000357 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
358 return NULL;
359
360 Py_BEGIN_ALLOW_THREADS
361 errno = 0;
362 n = read(self->fd, ptr, n);
363 Py_END_ALLOW_THREADS
364 if (n < 0) {
365 if (errno == EAGAIN)
366 Py_RETURN_NONE;
367 PyErr_SetFromErrno(PyExc_IOError);
368 return NULL;
369 }
370
Neal Norwitz88b44da2007-08-12 17:23:54 +0000371 return PyInt_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000372}
373
Guido van Rossum7165cb12007-07-10 06:54:34 +0000374#define DEFAULT_BUFFER_SIZE (8*1024)
375
376static PyObject *
377fileio_readall(PyFileIOObject *self)
378{
379 PyObject *result;
380 Py_ssize_t total = 0;
381 int n;
382
383 result = PyBytes_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
384 if (result == NULL)
385 return NULL;
386
387 while (1) {
388 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
389 if (PyBytes_GET_SIZE(result) < newsize) {
390 if (PyBytes_Resize(result, newsize) < 0) {
391 if (total == 0) {
392 Py_DECREF(result);
393 return NULL;
394 }
395 PyErr_Clear();
396 break;
397 }
398 }
399 Py_BEGIN_ALLOW_THREADS
400 errno = 0;
401 n = read(self->fd,
402 PyBytes_AS_STRING(result) + total,
403 newsize - total);
404 Py_END_ALLOW_THREADS
405 if (n == 0)
406 break;
407 if (n < 0) {
408 if (total > 0)
409 break;
410 if (errno == EAGAIN) {
411 Py_DECREF(result);
412 Py_RETURN_NONE;
413 }
414 Py_DECREF(result);
415 PyErr_SetFromErrno(PyExc_IOError);
416 return NULL;
417 }
418 total += n;
419 }
420
421 if (PyBytes_GET_SIZE(result) > total) {
422 if (PyBytes_Resize(result, total) < 0) {
423 /* This should never happen, but just in case */
424 Py_DECREF(result);
425 return NULL;
426 }
427 }
428 return result;
429}
430
Guido van Rossuma9e20242007-03-08 00:43:48 +0000431static PyObject *
432fileio_read(PyFileIOObject *self, PyObject *args)
433{
434 char *ptr;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000435 Py_ssize_t n;
436 Py_ssize_t size = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000437 PyObject *bytes;
438
439 if (self->fd < 0)
440 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000441 if (!self->readable)
442 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000443
Neal Norwitz3c8ba932007-08-08 04:36:17 +0000444 if (!PyArg_ParseTuple(args, "|n", &size))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000445 return NULL;
446
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000447 if (size < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000448 return fileio_readall(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000449 }
450
Guido van Rossuma9e20242007-03-08 00:43:48 +0000451 bytes = PyBytes_FromStringAndSize(NULL, size);
452 if (bytes == NULL)
453 return NULL;
454 ptr = PyBytes_AsString(bytes);
455
456 Py_BEGIN_ALLOW_THREADS
457 errno = 0;
458 n = read(self->fd, ptr, size);
459 Py_END_ALLOW_THREADS
460
461 if (n < 0) {
462 if (errno == EAGAIN)
463 Py_RETURN_NONE;
464 PyErr_SetFromErrno(PyExc_IOError);
465 return NULL;
466 }
467
468 if (n != size) {
469 if (PyBytes_Resize(bytes, n) < 0) {
470 Py_DECREF(bytes);
Guido van Rossum53807da2007-04-10 19:01:47 +0000471 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000472 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000473 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000474
475 return (PyObject *) bytes;
476}
477
478static PyObject *
479fileio_write(PyFileIOObject *self, PyObject *args)
480{
481 Py_ssize_t n;
482 char *ptr;
483
484 if (self->fd < 0)
485 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000486 if (!self->writable)
487 return err_mode("writing");
488
Guido van Rossuma9e20242007-03-08 00:43:48 +0000489 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
490 return NULL;
491
492 Py_BEGIN_ALLOW_THREADS
493 errno = 0;
494 n = write(self->fd, ptr, n);
495 Py_END_ALLOW_THREADS
496
497 if (n < 0) {
498 if (errno == EAGAIN)
499 Py_RETURN_NONE;
500 PyErr_SetFromErrno(PyExc_IOError);
501 return NULL;
502 }
503
Neal Norwitz88b44da2007-08-12 17:23:54 +0000504 return PyInt_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000505}
506
Guido van Rossum53807da2007-04-10 19:01:47 +0000507/* XXX Windows support below is likely incomplete */
508
509#if defined(MS_WIN64) || defined(MS_WINDOWS)
510typedef PY_LONG_LONG Py_off_t;
511#else
512typedef off_t Py_off_t;
513#endif
514
515/* Cribbed from posix_lseek() */
516static PyObject *
517portable_lseek(int fd, PyObject *posobj, int whence)
518{
519 Py_off_t pos, res;
520
521#ifdef SEEK_SET
522 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
523 switch (whence) {
524#if SEEK_SET != 0
525 case 0: whence = SEEK_SET; break;
526#endif
527#if SEEK_CUR != 1
528 case 1: whence = SEEK_CUR; break;
529#endif
530#if SEEL_END != 2
531 case 2: whence = SEEK_END; break;
532#endif
533 }
534#endif /* SEEK_SET */
535
536 if (posobj == NULL)
537 pos = 0;
538 else {
539#if !defined(HAVE_LARGEFILE_SUPPORT)
540 pos = PyInt_AsLong(posobj);
541#else
542 pos = PyLong_Check(posobj) ?
543 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
544#endif
545 if (PyErr_Occurred())
546 return NULL;
547 }
548
549 Py_BEGIN_ALLOW_THREADS
550#if defined(MS_WIN64) || defined(MS_WINDOWS)
551 res = _lseeki64(fd, pos, whence);
552#else
553 res = lseek(fd, pos, whence);
554#endif
555 Py_END_ALLOW_THREADS
556 if (res < 0)
557 return PyErr_SetFromErrno(PyExc_IOError);
558
559#if !defined(HAVE_LARGEFILE_SUPPORT)
560 return PyInt_FromLong(res);
561#else
562 return PyLong_FromLongLong(res);
563#endif
564}
565
Guido van Rossuma9e20242007-03-08 00:43:48 +0000566static PyObject *
567fileio_seek(PyFileIOObject *self, PyObject *args)
568{
Guido van Rossum53807da2007-04-10 19:01:47 +0000569 PyObject *posobj;
570 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000571
572 if (self->fd < 0)
573 return err_closed();
574
Guido van Rossum53807da2007-04-10 19:01:47 +0000575 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000576 return NULL;
577
Guido van Rossum53807da2007-04-10 19:01:47 +0000578 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000579}
580
581static PyObject *
582fileio_tell(PyFileIOObject *self, PyObject *args)
583{
Guido van Rossuma9e20242007-03-08 00:43:48 +0000584 if (self->fd < 0)
585 return err_closed();
586
Guido van Rossum53807da2007-04-10 19:01:47 +0000587 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000588}
589
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000590#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000591static PyObject *
592fileio_truncate(PyFileIOObject *self, PyObject *args)
593{
Guido van Rossum53807da2007-04-10 19:01:47 +0000594 PyObject *posobj = NULL;
595 Py_off_t pos;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000596 int ret;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000597 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000598
Guido van Rossum53807da2007-04-10 19:01:47 +0000599 fd = self->fd;
600 if (fd < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000601 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000602 if (!self->writable)
603 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000604
Guido van Rossum53807da2007-04-10 19:01:47 +0000605 if (!PyArg_ParseTuple(args, "|O", &posobj))
606 return NULL;
607
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000608 if (posobj == Py_None || posobj == NULL) {
609 posobj = portable_lseek(fd, NULL, 1);
610 if (posobj == NULL)
611 return NULL;
612 }
613 else {
614 Py_INCREF(posobj);
615 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000616
617#if !defined(HAVE_LARGEFILE_SUPPORT)
618 pos = PyInt_AsLong(posobj);
619#else
620 pos = PyLong_Check(posobj) ?
621 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
622#endif
Guido van Rossum87429772007-04-10 21:06:59 +0000623 if (PyErr_Occurred()) {
624 Py_DECREF(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000625 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000626 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000627
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000628#ifdef MS_WINDOWS
629 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
630 so don't even try using it. */
631 {
632 HANDLE hFile;
633 PyObject *pos2;
634
635 /* Have to move current pos to desired endpoint on Windows. */
636 errno = 0;
637 pos2 = portable_lseek(fd, posobj, SEEK_SET);
638 if (pos2 == NULL)
639 {
640 Py_DECREF(posobj);
641 return NULL;
642 }
643 Py_DECREF(pos2);
644
645 /* Truncate. Note that this may grow the file! */
646 Py_BEGIN_ALLOW_THREADS
647 errno = 0;
648 hFile = (HANDLE)_get_osfhandle(fd);
649 ret = hFile == (HANDLE)-1;
650 if (ret == 0) {
651 ret = SetEndOfFile(hFile) == 0;
652 if (ret)
653 errno = EACCES;
654 }
655 Py_END_ALLOW_THREADS
656 }
657#else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000658 Py_BEGIN_ALLOW_THREADS
659 errno = 0;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000660 ret = ftruncate(fd, pos);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000661 Py_END_ALLOW_THREADS
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000662#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000663
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000664 if (ret != 0) {
Guido van Rossum87429772007-04-10 21:06:59 +0000665 Py_DECREF(posobj);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000666 PyErr_SetFromErrno(PyExc_IOError);
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000667 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000668 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000669
Guido van Rossum87429772007-04-10 21:06:59 +0000670 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000671}
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000672#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000673
674static char *
675mode_string(PyFileIOObject *self)
676{
677 if (self->readable) {
678 if (self->writable)
679 return "r+";
680 else
681 return "r";
682 }
683 else
684 return "w";
685}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000686
687static PyObject *
688fileio_repr(PyFileIOObject *self)
689{
Guido van Rossum53807da2007-04-10 19:01:47 +0000690 if (self->fd < 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000691 return PyUnicode_FromFormat("_fileio._FileIO(-1)");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000692
Walter Dörwald1ab83302007-05-18 17:15:44 +0000693 return PyUnicode_FromFormat("_fileio._FileIO(%d, '%s')",
Guido van Rossum53807da2007-04-10 19:01:47 +0000694 self->fd, mode_string(self));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000695}
696
697static PyObject *
698fileio_isatty(PyFileIOObject *self)
699{
700 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000701
Guido van Rossuma9e20242007-03-08 00:43:48 +0000702 if (self->fd < 0)
703 return err_closed();
704 Py_BEGIN_ALLOW_THREADS
705 res = isatty(self->fd);
706 Py_END_ALLOW_THREADS
707 return PyBool_FromLong(res);
708}
709
Guido van Rossuma9e20242007-03-08 00:43:48 +0000710
711PyDoc_STRVAR(fileio_doc,
712"file(name: str[, mode: str]) -> file IO object\n"
713"\n"
714"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
715"writing or appending. The file will be created if it doesn't exist\n"
716"when opened for writing or appending; it will be truncated when\n"
717"opened for writing. Add a '+' to the mode to allow simultaneous\n"
718"reading and writing.");
719
720PyDoc_STRVAR(read_doc,
721"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
722"\n"
723"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000724"In non-blocking mode, returns None if no data is available.\n"
725"On end-of-file, returns ''.");
726
727PyDoc_STRVAR(readall_doc,
728"readall() -> bytes. read all data from the file, returned as bytes.\n"
729"\n"
730"In non-blocking mode, returns as much as is immediately available,\n"
731"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000732
733PyDoc_STRVAR(write_doc,
734"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
735"\n"
736"Only makes one system call, so not all of the data may be written.\n"
737"The number of bytes actually written is returned.");
738
739PyDoc_STRVAR(fileno_doc,
740"fileno() -> int. \"file descriptor\".\n"
741"\n"
742"This is needed for lower-level file interfaces, such the fcntl module.");
743
744PyDoc_STRVAR(seek_doc,
745"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
746"\n"
747"Argument offset is a byte count. Optional argument whence defaults to\n"
748"0 (offset from start of file, offset should be >= 0); other values are 1\n"
749"(move relative to current position, positive or negative), and 2 (move\n"
750"relative to end of file, usually negative, although many platforms allow\n"
751"seeking beyond the end of a file)."
752"\n"
753"Note that not all file objects are seekable.");
754
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000755#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000756PyDoc_STRVAR(truncate_doc,
757"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
758"\n"
759"Size defaults to the current file position, as returned by tell().");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000760#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000761
762PyDoc_STRVAR(tell_doc,
763"tell() -> int. Current file position");
764
765PyDoc_STRVAR(readinto_doc,
766"readinto() -> Undocumented. Don't use this; it may go away.");
767
768PyDoc_STRVAR(close_doc,
769"close() -> None. Close the file.\n"
770"\n"
771"A closed file cannot be used for further I/O operations. close() may be\n"
772"called more than once without error. Changes the fileno to -1.");
773
774PyDoc_STRVAR(isatty_doc,
775"isatty() -> bool. True if the file is connected to a tty device.");
776
Guido van Rossuma9e20242007-03-08 00:43:48 +0000777PyDoc_STRVAR(seekable_doc,
778"seekable() -> bool. True if file supports random-access.");
779
780PyDoc_STRVAR(readable_doc,
781"readable() -> bool. True if file was opened in a read mode.");
782
783PyDoc_STRVAR(writable_doc,
784"writable() -> bool. True if file was opened in a write mode.");
785
786static PyMethodDef fileio_methods[] = {
787 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
Guido van Rossum7165cb12007-07-10 06:54:34 +0000788 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000789 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
790 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
791 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
792 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000793#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000794 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000795#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000796 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
797 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
798 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
799 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
800 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
801 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000802 {NULL, NULL} /* sentinel */
803};
804
Guido van Rossum53807da2007-04-10 19:01:47 +0000805/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
806
Guido van Rossumb0428152007-04-08 17:44:42 +0000807static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000808get_closed(PyFileIOObject *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +0000809{
Guido van Rossum53807da2007-04-10 19:01:47 +0000810 return PyBool_FromLong((long)(self->fd < 0));
811}
812
813static PyObject *
814get_mode(PyFileIOObject *self, void *closure)
815{
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000816 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +0000817}
818
819static PyGetSetDef fileio_getsetlist[] = {
820 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Guido van Rossum53807da2007-04-10 19:01:47 +0000821 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Guido van Rossumb0428152007-04-08 17:44:42 +0000822 {0},
823};
824
Guido van Rossuma9e20242007-03-08 00:43:48 +0000825PyTypeObject PyFileIO_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000826 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000827 "FileIO",
828 sizeof(PyFileIOObject),
829 0,
830 (destructor)fileio_dealloc, /* tp_dealloc */
831 0, /* tp_print */
832 0, /* tp_getattr */
833 0, /* tp_setattr */
834 0, /* tp_compare */
835 (reprfunc)fileio_repr, /* tp_repr */
836 0, /* tp_as_number */
837 0, /* tp_as_sequence */
838 0, /* tp_as_mapping */
839 0, /* tp_hash */
840 0, /* tp_call */
841 0, /* tp_str */
842 PyObject_GenericGetAttr, /* tp_getattro */
843 0, /* tp_setattro */
844 0, /* tp_as_buffer */
845 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
846 fileio_doc, /* tp_doc */
847 0, /* tp_traverse */
848 0, /* tp_clear */
849 0, /* tp_richcompare */
850 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
851 0, /* tp_iter */
852 0, /* tp_iternext */
853 fileio_methods, /* tp_methods */
854 0, /* tp_members */
Guido van Rossumb0428152007-04-08 17:44:42 +0000855 fileio_getsetlist, /* tp_getset */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000856 0, /* tp_base */
857 0, /* tp_dict */
858 0, /* tp_descr_get */
859 0, /* tp_descr_set */
860 0, /* tp_dictoffset */
861 fileio_init, /* tp_init */
862 PyType_GenericAlloc, /* tp_alloc */
863 fileio_new, /* tp_new */
864 PyObject_Del, /* tp_free */
865};
866
867static PyMethodDef module_methods[] = {
868 {NULL, NULL}
869};
870
871PyMODINIT_FUNC
872init_fileio(void)
873{
874 PyObject *m; /* a module object */
875
876 m = Py_InitModule3("_fileio", module_methods,
877 "Fast implementation of io.FileIO.");
878 if (m == NULL)
879 return;
880 if (PyType_Ready(&PyFileIO_Type) < 0)
881 return;
882 Py_INCREF(&PyFileIO_Type);
883 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
884}