blob: 7757af97892f67e3ed1ac521b0b69008a0af1dfb [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 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000341 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000342}
343
344static PyObject *
345fileio_readinto(PyFileIOObject *self, PyObject *args)
346{
347 char *ptr;
348 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000349
Guido van Rossuma9e20242007-03-08 00:43:48 +0000350 if (self->fd < 0)
351 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000352 if (!self->readable)
353 return err_mode("reading");
354
Guido van Rossuma9e20242007-03-08 00:43:48 +0000355 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
356 return NULL;
357
358 Py_BEGIN_ALLOW_THREADS
359 errno = 0;
360 n = read(self->fd, ptr, n);
361 Py_END_ALLOW_THREADS
362 if (n < 0) {
363 if (errno == EAGAIN)
364 Py_RETURN_NONE;
365 PyErr_SetFromErrno(PyExc_IOError);
366 return NULL;
367 }
368
Neal Norwitz88b44da2007-08-12 17:23:54 +0000369 return PyInt_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000370}
371
Guido van Rossum7165cb12007-07-10 06:54:34 +0000372#define DEFAULT_BUFFER_SIZE (8*1024)
373
374static PyObject *
375fileio_readall(PyFileIOObject *self)
376{
377 PyObject *result;
378 Py_ssize_t total = 0;
379 int n;
380
381 result = PyBytes_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
382 if (result == NULL)
383 return NULL;
384
385 while (1) {
386 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
387 if (PyBytes_GET_SIZE(result) < newsize) {
388 if (PyBytes_Resize(result, newsize) < 0) {
389 if (total == 0) {
390 Py_DECREF(result);
391 return NULL;
392 }
393 PyErr_Clear();
394 break;
395 }
396 }
397 Py_BEGIN_ALLOW_THREADS
398 errno = 0;
399 n = read(self->fd,
400 PyBytes_AS_STRING(result) + total,
401 newsize - total);
402 Py_END_ALLOW_THREADS
403 if (n == 0)
404 break;
405 if (n < 0) {
406 if (total > 0)
407 break;
408 if (errno == EAGAIN) {
409 Py_DECREF(result);
410 Py_RETURN_NONE;
411 }
412 Py_DECREF(result);
413 PyErr_SetFromErrno(PyExc_IOError);
414 return NULL;
415 }
416 total += n;
417 }
418
419 if (PyBytes_GET_SIZE(result) > total) {
420 if (PyBytes_Resize(result, total) < 0) {
421 /* This should never happen, but just in case */
422 Py_DECREF(result);
423 return NULL;
424 }
425 }
426 return result;
427}
428
Guido van Rossuma9e20242007-03-08 00:43:48 +0000429static PyObject *
430fileio_read(PyFileIOObject *self, PyObject *args)
431{
432 char *ptr;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000433 Py_ssize_t n;
434 Py_ssize_t size = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000435 PyObject *bytes;
436
437 if (self->fd < 0)
438 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000439 if (!self->readable)
440 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000441
Neal Norwitz3c8ba932007-08-08 04:36:17 +0000442 if (!PyArg_ParseTuple(args, "|n", &size))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000443 return NULL;
444
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000445 if (size < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000446 return fileio_readall(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000447 }
448
Guido van Rossuma9e20242007-03-08 00:43:48 +0000449 bytes = PyBytes_FromStringAndSize(NULL, size);
450 if (bytes == NULL)
451 return NULL;
452 ptr = PyBytes_AsString(bytes);
453
454 Py_BEGIN_ALLOW_THREADS
455 errno = 0;
456 n = read(self->fd, ptr, size);
457 Py_END_ALLOW_THREADS
458
459 if (n < 0) {
460 if (errno == EAGAIN)
461 Py_RETURN_NONE;
462 PyErr_SetFromErrno(PyExc_IOError);
463 return NULL;
464 }
465
466 if (n != size) {
467 if (PyBytes_Resize(bytes, n) < 0) {
468 Py_DECREF(bytes);
Guido van Rossum53807da2007-04-10 19:01:47 +0000469 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000470 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000471 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000472
473 return (PyObject *) bytes;
474}
475
476static PyObject *
477fileio_write(PyFileIOObject *self, PyObject *args)
478{
479 Py_ssize_t n;
480 char *ptr;
481
482 if (self->fd < 0)
483 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000484 if (!self->writable)
485 return err_mode("writing");
486
Guido van Rossuma9e20242007-03-08 00:43:48 +0000487 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
488 return NULL;
489
490 Py_BEGIN_ALLOW_THREADS
491 errno = 0;
492 n = write(self->fd, ptr, n);
493 Py_END_ALLOW_THREADS
494
495 if (n < 0) {
496 if (errno == EAGAIN)
497 Py_RETURN_NONE;
498 PyErr_SetFromErrno(PyExc_IOError);
499 return NULL;
500 }
501
Neal Norwitz88b44da2007-08-12 17:23:54 +0000502 return PyInt_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000503}
504
Guido van Rossum53807da2007-04-10 19:01:47 +0000505/* XXX Windows support below is likely incomplete */
506
507#if defined(MS_WIN64) || defined(MS_WINDOWS)
508typedef PY_LONG_LONG Py_off_t;
509#else
510typedef off_t Py_off_t;
511#endif
512
513/* Cribbed from posix_lseek() */
514static PyObject *
515portable_lseek(int fd, PyObject *posobj, int whence)
516{
517 Py_off_t pos, res;
518
519#ifdef SEEK_SET
520 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
521 switch (whence) {
522#if SEEK_SET != 0
523 case 0: whence = SEEK_SET; break;
524#endif
525#if SEEK_CUR != 1
526 case 1: whence = SEEK_CUR; break;
527#endif
528#if SEEL_END != 2
529 case 2: whence = SEEK_END; break;
530#endif
531 }
532#endif /* SEEK_SET */
533
534 if (posobj == NULL)
535 pos = 0;
536 else {
537#if !defined(HAVE_LARGEFILE_SUPPORT)
538 pos = PyInt_AsLong(posobj);
539#else
540 pos = PyLong_Check(posobj) ?
541 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
542#endif
543 if (PyErr_Occurred())
544 return NULL;
545 }
546
547 Py_BEGIN_ALLOW_THREADS
548#if defined(MS_WIN64) || defined(MS_WINDOWS)
549 res = _lseeki64(fd, pos, whence);
550#else
551 res = lseek(fd, pos, whence);
552#endif
553 Py_END_ALLOW_THREADS
554 if (res < 0)
555 return PyErr_SetFromErrno(PyExc_IOError);
556
557#if !defined(HAVE_LARGEFILE_SUPPORT)
558 return PyInt_FromLong(res);
559#else
560 return PyLong_FromLongLong(res);
561#endif
562}
563
Guido van Rossuma9e20242007-03-08 00:43:48 +0000564static PyObject *
565fileio_seek(PyFileIOObject *self, PyObject *args)
566{
Guido van Rossum53807da2007-04-10 19:01:47 +0000567 PyObject *posobj;
568 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000569
570 if (self->fd < 0)
571 return err_closed();
572
Guido van Rossum53807da2007-04-10 19:01:47 +0000573 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000574 return NULL;
575
Guido van Rossum53807da2007-04-10 19:01:47 +0000576 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000577}
578
579static PyObject *
580fileio_tell(PyFileIOObject *self, PyObject *args)
581{
Guido van Rossuma9e20242007-03-08 00:43:48 +0000582 if (self->fd < 0)
583 return err_closed();
584
Guido van Rossum53807da2007-04-10 19:01:47 +0000585 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000586}
587
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000588#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000589static PyObject *
590fileio_truncate(PyFileIOObject *self, PyObject *args)
591{
Guido van Rossum53807da2007-04-10 19:01:47 +0000592 PyObject *posobj = NULL;
593 Py_off_t pos;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000594 int ret;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000595 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000596
Guido van Rossum53807da2007-04-10 19:01:47 +0000597 fd = self->fd;
598 if (fd < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000599 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000600 if (!self->writable)
601 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000602
Guido van Rossum53807da2007-04-10 19:01:47 +0000603 if (!PyArg_ParseTuple(args, "|O", &posobj))
604 return NULL;
605
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000606 if (posobj == Py_None || posobj == NULL) {
607 posobj = portable_lseek(fd, NULL, 1);
608 if (posobj == NULL)
609 return NULL;
610 }
611 else {
612 Py_INCREF(posobj);
613 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000614
615#if !defined(HAVE_LARGEFILE_SUPPORT)
616 pos = PyInt_AsLong(posobj);
617#else
618 pos = PyLong_Check(posobj) ?
619 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
620#endif
Guido van Rossum87429772007-04-10 21:06:59 +0000621 if (PyErr_Occurred()) {
622 Py_DECREF(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000623 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000624 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000625
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000626#ifdef MS_WINDOWS
627 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
628 so don't even try using it. */
629 {
630 HANDLE hFile;
631 PyObject *pos2;
632
633 /* Have to move current pos to desired endpoint on Windows. */
634 errno = 0;
635 pos2 = portable_lseek(fd, posobj, SEEK_SET);
636 if (pos2 == NULL)
637 {
638 Py_DECREF(posobj);
639 return NULL;
640 }
641 Py_DECREF(pos2);
642
643 /* Truncate. Note that this may grow the file! */
644 Py_BEGIN_ALLOW_THREADS
645 errno = 0;
646 hFile = (HANDLE)_get_osfhandle(fd);
647 ret = hFile == (HANDLE)-1;
648 if (ret == 0) {
649 ret = SetEndOfFile(hFile) == 0;
650 if (ret)
651 errno = EACCES;
652 }
653 Py_END_ALLOW_THREADS
654 }
655#else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000656 Py_BEGIN_ALLOW_THREADS
657 errno = 0;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000658 ret = ftruncate(fd, pos);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000659 Py_END_ALLOW_THREADS
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000660#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000661
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000662 if (ret != 0) {
Guido van Rossum87429772007-04-10 21:06:59 +0000663 Py_DECREF(posobj);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000664 PyErr_SetFromErrno(PyExc_IOError);
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000665 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000666 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000667
Guido van Rossum87429772007-04-10 21:06:59 +0000668 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000669}
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000670#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000671
672static char *
673mode_string(PyFileIOObject *self)
674{
675 if (self->readable) {
676 if (self->writable)
677 return "r+";
678 else
679 return "r";
680 }
681 else
682 return "w";
683}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000684
685static PyObject *
686fileio_repr(PyFileIOObject *self)
687{
Guido van Rossum53807da2007-04-10 19:01:47 +0000688 if (self->fd < 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000689 return PyUnicode_FromFormat("_fileio._FileIO(-1)");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000690
Walter Dörwald1ab83302007-05-18 17:15:44 +0000691 return PyUnicode_FromFormat("_fileio._FileIO(%d, '%s')",
Guido van Rossum53807da2007-04-10 19:01:47 +0000692 self->fd, mode_string(self));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000693}
694
695static PyObject *
696fileio_isatty(PyFileIOObject *self)
697{
698 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000699
Guido van Rossuma9e20242007-03-08 00:43:48 +0000700 if (self->fd < 0)
701 return err_closed();
702 Py_BEGIN_ALLOW_THREADS
703 res = isatty(self->fd);
704 Py_END_ALLOW_THREADS
705 return PyBool_FromLong(res);
706}
707
Guido van Rossuma9e20242007-03-08 00:43:48 +0000708
709PyDoc_STRVAR(fileio_doc,
710"file(name: str[, mode: str]) -> file IO object\n"
711"\n"
712"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
713"writing or appending. The file will be created if it doesn't exist\n"
714"when opened for writing or appending; it will be truncated when\n"
715"opened for writing. Add a '+' to the mode to allow simultaneous\n"
716"reading and writing.");
717
718PyDoc_STRVAR(read_doc,
719"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
720"\n"
721"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000722"In non-blocking mode, returns None if no data is available.\n"
723"On end-of-file, returns ''.");
724
725PyDoc_STRVAR(readall_doc,
726"readall() -> bytes. read all data from the file, returned as bytes.\n"
727"\n"
728"In non-blocking mode, returns as much as is immediately available,\n"
729"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000730
731PyDoc_STRVAR(write_doc,
732"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
733"\n"
734"Only makes one system call, so not all of the data may be written.\n"
735"The number of bytes actually written is returned.");
736
737PyDoc_STRVAR(fileno_doc,
738"fileno() -> int. \"file descriptor\".\n"
739"\n"
740"This is needed for lower-level file interfaces, such the fcntl module.");
741
742PyDoc_STRVAR(seek_doc,
743"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
744"\n"
745"Argument offset is a byte count. Optional argument whence defaults to\n"
746"0 (offset from start of file, offset should be >= 0); other values are 1\n"
747"(move relative to current position, positive or negative), and 2 (move\n"
748"relative to end of file, usually negative, although many platforms allow\n"
749"seeking beyond the end of a file)."
750"\n"
751"Note that not all file objects are seekable.");
752
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000753#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000754PyDoc_STRVAR(truncate_doc,
755"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
756"\n"
757"Size defaults to the current file position, as returned by tell().");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000758#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000759
760PyDoc_STRVAR(tell_doc,
761"tell() -> int. Current file position");
762
763PyDoc_STRVAR(readinto_doc,
764"readinto() -> Undocumented. Don't use this; it may go away.");
765
766PyDoc_STRVAR(close_doc,
767"close() -> None. Close the file.\n"
768"\n"
769"A closed file cannot be used for further I/O operations. close() may be\n"
770"called more than once without error. Changes the fileno to -1.");
771
772PyDoc_STRVAR(isatty_doc,
773"isatty() -> bool. True if the file is connected to a tty device.");
774
Guido van Rossuma9e20242007-03-08 00:43:48 +0000775PyDoc_STRVAR(seekable_doc,
776"seekable() -> bool. True if file supports random-access.");
777
778PyDoc_STRVAR(readable_doc,
779"readable() -> bool. True if file was opened in a read mode.");
780
781PyDoc_STRVAR(writable_doc,
782"writable() -> bool. True if file was opened in a write mode.");
783
784static PyMethodDef fileio_methods[] = {
785 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
Guido van Rossum7165cb12007-07-10 06:54:34 +0000786 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000787 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
788 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
789 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
790 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000791#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000792 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000793#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000794 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
795 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
796 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
797 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
798 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
799 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000800 {NULL, NULL} /* sentinel */
801};
802
Guido van Rossum53807da2007-04-10 19:01:47 +0000803/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
804
Guido van Rossumb0428152007-04-08 17:44:42 +0000805static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000806get_closed(PyFileIOObject *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +0000807{
Guido van Rossum53807da2007-04-10 19:01:47 +0000808 return PyBool_FromLong((long)(self->fd < 0));
809}
810
811static PyObject *
812get_mode(PyFileIOObject *self, void *closure)
813{
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000814 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +0000815}
816
817static PyGetSetDef fileio_getsetlist[] = {
818 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Guido van Rossum53807da2007-04-10 19:01:47 +0000819 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Guido van Rossumb0428152007-04-08 17:44:42 +0000820 {0},
821};
822
Guido van Rossuma9e20242007-03-08 00:43:48 +0000823PyTypeObject PyFileIO_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000824 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000825 "FileIO",
826 sizeof(PyFileIOObject),
827 0,
828 (destructor)fileio_dealloc, /* tp_dealloc */
829 0, /* tp_print */
830 0, /* tp_getattr */
831 0, /* tp_setattr */
832 0, /* tp_compare */
833 (reprfunc)fileio_repr, /* tp_repr */
834 0, /* tp_as_number */
835 0, /* tp_as_sequence */
836 0, /* tp_as_mapping */
837 0, /* tp_hash */
838 0, /* tp_call */
839 0, /* tp_str */
840 PyObject_GenericGetAttr, /* tp_getattro */
841 0, /* tp_setattro */
842 0, /* tp_as_buffer */
843 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
844 fileio_doc, /* tp_doc */
845 0, /* tp_traverse */
846 0, /* tp_clear */
847 0, /* tp_richcompare */
848 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
849 0, /* tp_iter */
850 0, /* tp_iternext */
851 fileio_methods, /* tp_methods */
852 0, /* tp_members */
Guido van Rossumb0428152007-04-08 17:44:42 +0000853 fileio_getsetlist, /* tp_getset */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000854 0, /* tp_base */
855 0, /* tp_dict */
856 0, /* tp_descr_get */
857 0, /* tp_descr_set */
858 0, /* tp_dictoffset */
859 fileio_init, /* tp_init */
860 PyType_GenericAlloc, /* tp_alloc */
861 fileio_new, /* tp_new */
862 PyObject_Del, /* tp_free */
863};
864
865static PyMethodDef module_methods[] = {
866 {NULL, NULL}
867};
868
869PyMODINIT_FUNC
870init_fileio(void)
871{
872 PyObject *m; /* a module object */
873
874 m = Py_InitModule3("_fileio", module_methods,
875 "Fast implementation of io.FileIO.");
876 if (m == NULL)
877 return;
878 if (PyType_Ready(&PyFileIO_Type) < 0)
879 return;
880 Py_INCREF(&PyFileIO_Type);
881 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
882}