blob: 8469bb248f27ac1fc4b6e4df94c69c915e78f4b8 [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 Rossum2dced8b2007-10-30 17:27:30 +000036 int closefd : 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +000037 PyObject *weakreflist;
38} PyFileIOObject;
39
Collin Winteraf334382007-03-08 21:46:15 +000040PyTypeObject PyFileIO_Type;
41
Guido van Rossuma9e20242007-03-08 00:43:48 +000042#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
43
Neal Norwitz88b44da2007-08-12 17:23:54 +000044/* Returns 0 on success, errno (which is < 0) on failure. */
45static int
46internal_close(PyFileIOObject *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000047{
Neal Norwitz88b44da2007-08-12 17:23:54 +000048 int save_errno = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +000049 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
Neal Norwitz88b44da2007-08-12 17:23:54 +000053 if (close(fd) < 0)
54 save_errno = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +000055 Py_END_ALLOW_THREADS
Neal Norwitz88b44da2007-08-12 17:23:54 +000056 }
57 return save_errno;
58}
59
60static PyObject *
61fileio_close(PyFileIOObject *self)
62{
Guido van Rossum2dced8b2007-10-30 17:27:30 +000063 if (!self->closefd) {
64 if (PyErr_WarnEx(PyExc_RuntimeWarning,
65 "Trying to close unclosable fd!", 3) < 0) {
66 return NULL;
67 }
68 Py_RETURN_NONE;
69 }
Neal Norwitz88b44da2007-08-12 17:23:54 +000070 errno = internal_close(self);
71 if (errno < 0) {
72 PyErr_SetFromErrno(PyExc_IOError);
73 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +000074 }
75
76 Py_RETURN_NONE;
77}
78
79static PyObject *
80fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews)
81{
82 PyFileIOObject *self;
83
84 assert(type != NULL && type->tp_alloc != NULL);
85
86 self = (PyFileIOObject *) type->tp_alloc(type, 0);
87 if (self != NULL) {
88 self->fd = -1;
89 self->weakreflist = NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +000090 }
91
92 return (PyObject *) self;
93}
94
95/* On Unix, open will succeed for directories.
96 In Python, there should be no file objects referring to
97 directories, so we need a check. */
98
99static int
100dircheck(PyFileIOObject* self)
101{
102#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
103 struct stat buf;
104 if (self->fd < 0)
105 return 0;
106 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
107#ifdef HAVE_STRERROR
108 char *msg = strerror(EISDIR);
109#else
110 char *msg = "Is a directory";
111#endif
112 PyObject *exc;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000113 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000114
Guido van Rossuma9e20242007-03-08 00:43:48 +0000115 exc = PyObject_CallFunction(PyExc_IOError, "(is)",
116 EISDIR, msg);
117 PyErr_SetObject(PyExc_IOError, exc);
118 Py_XDECREF(exc);
119 return -1;
120 }
121#endif
122 return 0;
123}
124
125
126static int
127fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
128{
129 PyFileIOObject *self = (PyFileIOObject *) oself;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000130 static char *kwlist[] = {"file", "mode", "closefd", NULL};
Guido van Rossuma9e20242007-03-08 00:43:48 +0000131 char *name = NULL;
132 char *mode = "r";
Guido van Rossum53807da2007-04-10 19:01:47 +0000133 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000134#ifdef MS_WINDOWS
135 Py_UNICODE *widename = NULL;
136#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000137 int ret = 0;
138 int rwa = 0, plus = 0, append = 0;
139 int flags = 0;
Guido van Rossumb0428152007-04-08 17:44:42 +0000140 int fd = -1;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000141 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000142
143 assert(PyFileIO_Check(oself));
Neal Norwitz88b44da2007-08-12 17:23:54 +0000144 if (self->fd >= 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000145 /* Have to close the existing file first. */
Neal Norwitz88b44da2007-08-12 17:23:54 +0000146 if (internal_close(self) < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000147 return -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148 }
149
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000150 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio",
151 kwlist, &fd, &mode, &closefd)) {
Guido van Rossumb0428152007-04-08 17:44:42 +0000152 if (fd < 0) {
153 PyErr_SetString(PyExc_ValueError,
154 "Negative filedescriptor");
155 return -1;
156 }
157 }
158 else {
159 PyErr_Clear();
160
Guido van Rossuma9e20242007-03-08 00:43:48 +0000161#ifdef Py_WIN_WIDE_FILENAMES
Guido van Rossumb0428152007-04-08 17:44:42 +0000162 if (GetVersion() < 0x80000000) {
163 /* On NT, so wide API available */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000164 PyObject *po;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000165 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio",
166 kwlist, &po, &mode, &closefd)
167 ) {
Thomas Helleraf2be262007-07-12 11:03:13 +0000168 widename = PyUnicode_AS_UNICODE(po);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000169 } else {
170 /* Drop the argument parsing error as narrow
171 strings are also valid. */
172 PyErr_Clear();
173 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000174 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000175 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000176#endif
Thomas Helleraf2be262007-07-12 11:03:13 +0000177 {
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000178 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio",
Guido van Rossuma9e20242007-03-08 00:43:48 +0000179 kwlist,
180 Py_FileSystemDefaultEncoding,
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000181 &name, &mode, &closefd))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000182 goto error;
Guido van Rossumb0428152007-04-08 17:44:42 +0000183 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000184 }
185
186 self->readable = self->writable = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000187 self->seekable = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000188 s = mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000189 while (*s) {
190 switch (*s++) {
191 case 'r':
192 if (rwa) {
193 bad_mode:
194 PyErr_SetString(PyExc_ValueError,
195 "Must have exactly one of read/write/append mode");
196 goto error;
197 }
198 rwa = 1;
199 self->readable = 1;
200 break;
201 case 'w':
202 if (rwa)
203 goto bad_mode;
204 rwa = 1;
205 self->writable = 1;
206 flags |= O_CREAT | O_TRUNC;
207 break;
208 case 'a':
209 if (rwa)
210 goto bad_mode;
211 rwa = 1;
212 self->writable = 1;
213 flags |= O_CREAT;
214 append = 1;
215 break;
216 case '+':
217 if (plus)
218 goto bad_mode;
219 self->readable = self->writable = 1;
220 plus = 1;
221 break;
222 default:
223 PyErr_Format(PyExc_ValueError,
224 "invalid mode: %.200s", mode);
225 goto error;
226 }
227 }
228
229 if (!rwa)
230 goto bad_mode;
231
232 if (self->readable && self->writable)
233 flags |= O_RDWR;
234 else if (self->readable)
235 flags |= O_RDONLY;
236 else
237 flags |= O_WRONLY;
238
239#ifdef O_BINARY
240 flags |= O_BINARY;
241#endif
242
Walter Dörwald0e411482007-06-06 16:55:38 +0000243#ifdef O_APPEND
244 if (append)
245 flags |= O_APPEND;
246#endif
247
Guido van Rossumb0428152007-04-08 17:44:42 +0000248 if (fd >= 0) {
249 self->fd = fd;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000250 self->closefd = closefd;
Guido van Rossumb0428152007-04-08 17:44:42 +0000251 }
252 else {
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000253 self->closefd = 1;
254 if (!closefd) {
255 PyErr_SetString(PyExc_ValueError,
256 "Cannot use closefd=True with file name");
257 goto error;
258 }
259
Guido van Rossumb0428152007-04-08 17:44:42 +0000260 Py_BEGIN_ALLOW_THREADS
261 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000262#ifdef MS_WINDOWS
263 if (widename != NULL)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000264 self->fd = _wopen(widename, flags, 0666);
Thomas Helleraf2be262007-07-12 11:03:13 +0000265 else
266#endif
Neal Norwitz88b44da2007-08-12 17:23:54 +0000267 self->fd = open(name, flags, 0666);
Guido van Rossumb0428152007-04-08 17:44:42 +0000268 Py_END_ALLOW_THREADS
269 if (self->fd < 0 || dircheck(self) < 0) {
270 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
271 goto error;
272 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000273 }
274
275 goto done;
276
277 error:
278 ret = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000279
Guido van Rossuma9e20242007-03-08 00:43:48 +0000280 done:
281 PyMem_Free(name);
282 return ret;
283}
284
285static void
286fileio_dealloc(PyFileIOObject *self)
287{
288 if (self->weakreflist != NULL)
289 PyObject_ClearWeakRefs((PyObject *) self);
290
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000291 if (self->fd >= 0 && self->closefd) {
Neal Norwitz88b44da2007-08-12 17:23:54 +0000292 errno = internal_close(self);
293 if (errno < 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000294#ifdef HAVE_STRERROR
Guido van Rossum53807da2007-04-10 19:01:47 +0000295 PySys_WriteStderr("close failed: [Errno %d] %s\n",
296 errno, strerror(errno));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000297#else
298 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
299#endif
Neal Norwitz88b44da2007-08-12 17:23:54 +0000300 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000301 }
302
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000303 Py_Type(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000304}
305
306static PyObject *
307err_closed(void)
308{
309 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
310 return NULL;
311}
312
313static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000314err_mode(char *action)
315{
316 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
317 return NULL;
318}
319
320static PyObject *
Guido van Rossuma9e20242007-03-08 00:43:48 +0000321fileio_fileno(PyFileIOObject *self)
322{
323 if (self->fd < 0)
324 return err_closed();
325 return PyInt_FromLong((long) self->fd);
326}
327
328static PyObject *
329fileio_readable(PyFileIOObject *self)
330{
331 if (self->fd < 0)
332 return err_closed();
Neal Norwitz88b44da2007-08-12 17:23:54 +0000333 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000334}
335
336static PyObject *
337fileio_writable(PyFileIOObject *self)
338{
339 if (self->fd < 0)
340 return err_closed();
Neal Norwitz88b44da2007-08-12 17:23:54 +0000341 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000342}
343
344static PyObject *
345fileio_seekable(PyFileIOObject *self)
346{
347 if (self->fd < 0)
348 return err_closed();
349 if (self->seekable < 0) {
350 int ret;
351 Py_BEGIN_ALLOW_THREADS
352 ret = lseek(self->fd, 0, SEEK_CUR);
353 Py_END_ALLOW_THREADS
354 if (ret < 0)
355 self->seekable = 0;
356 else
357 self->seekable = 1;
358 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000359 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000360}
361
362static PyObject *
363fileio_readinto(PyFileIOObject *self, PyObject *args)
364{
365 char *ptr;
366 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000367
Guido van Rossuma9e20242007-03-08 00:43:48 +0000368 if (self->fd < 0)
369 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000370 if (!self->readable)
371 return err_mode("reading");
372
Guido van Rossuma9e20242007-03-08 00:43:48 +0000373 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
374 return NULL;
375
376 Py_BEGIN_ALLOW_THREADS
377 errno = 0;
378 n = read(self->fd, ptr, n);
379 Py_END_ALLOW_THREADS
380 if (n < 0) {
381 if (errno == EAGAIN)
382 Py_RETURN_NONE;
383 PyErr_SetFromErrno(PyExc_IOError);
384 return NULL;
385 }
386
Neal Norwitz88b44da2007-08-12 17:23:54 +0000387 return PyInt_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000388}
389
Guido van Rossum7165cb12007-07-10 06:54:34 +0000390#define DEFAULT_BUFFER_SIZE (8*1024)
391
392static PyObject *
393fileio_readall(PyFileIOObject *self)
394{
395 PyObject *result;
396 Py_ssize_t total = 0;
397 int n;
398
399 result = PyBytes_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
400 if (result == NULL)
401 return NULL;
402
403 while (1) {
404 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
405 if (PyBytes_GET_SIZE(result) < newsize) {
406 if (PyBytes_Resize(result, newsize) < 0) {
407 if (total == 0) {
408 Py_DECREF(result);
409 return NULL;
410 }
411 PyErr_Clear();
412 break;
413 }
414 }
415 Py_BEGIN_ALLOW_THREADS
416 errno = 0;
417 n = read(self->fd,
418 PyBytes_AS_STRING(result) + total,
419 newsize - total);
420 Py_END_ALLOW_THREADS
421 if (n == 0)
422 break;
423 if (n < 0) {
424 if (total > 0)
425 break;
426 if (errno == EAGAIN) {
427 Py_DECREF(result);
428 Py_RETURN_NONE;
429 }
430 Py_DECREF(result);
431 PyErr_SetFromErrno(PyExc_IOError);
432 return NULL;
433 }
434 total += n;
435 }
436
437 if (PyBytes_GET_SIZE(result) > total) {
438 if (PyBytes_Resize(result, total) < 0) {
439 /* This should never happen, but just in case */
440 Py_DECREF(result);
441 return NULL;
442 }
443 }
444 return result;
445}
446
Guido van Rossuma9e20242007-03-08 00:43:48 +0000447static PyObject *
448fileio_read(PyFileIOObject *self, PyObject *args)
449{
450 char *ptr;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000451 Py_ssize_t n;
452 Py_ssize_t size = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000453 PyObject *bytes;
454
455 if (self->fd < 0)
456 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000457 if (!self->readable)
458 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000459
Neal Norwitz3c8ba932007-08-08 04:36:17 +0000460 if (!PyArg_ParseTuple(args, "|n", &size))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000461 return NULL;
462
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000463 if (size < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000464 return fileio_readall(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000465 }
466
Guido van Rossuma9e20242007-03-08 00:43:48 +0000467 bytes = PyBytes_FromStringAndSize(NULL, size);
468 if (bytes == NULL)
469 return NULL;
470 ptr = PyBytes_AsString(bytes);
471
472 Py_BEGIN_ALLOW_THREADS
473 errno = 0;
474 n = read(self->fd, ptr, size);
475 Py_END_ALLOW_THREADS
476
477 if (n < 0) {
478 if (errno == EAGAIN)
479 Py_RETURN_NONE;
480 PyErr_SetFromErrno(PyExc_IOError);
481 return NULL;
482 }
483
484 if (n != size) {
485 if (PyBytes_Resize(bytes, n) < 0) {
486 Py_DECREF(bytes);
Guido van Rossum53807da2007-04-10 19:01:47 +0000487 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000488 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000489 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000490
491 return (PyObject *) bytes;
492}
493
494static PyObject *
495fileio_write(PyFileIOObject *self, PyObject *args)
496{
497 Py_ssize_t n;
498 char *ptr;
499
500 if (self->fd < 0)
501 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000502 if (!self->writable)
503 return err_mode("writing");
504
Guido van Rossuma9e20242007-03-08 00:43:48 +0000505 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
506 return NULL;
507
508 Py_BEGIN_ALLOW_THREADS
509 errno = 0;
510 n = write(self->fd, ptr, n);
511 Py_END_ALLOW_THREADS
512
513 if (n < 0) {
514 if (errno == EAGAIN)
515 Py_RETURN_NONE;
516 PyErr_SetFromErrno(PyExc_IOError);
517 return NULL;
518 }
519
Neal Norwitz88b44da2007-08-12 17:23:54 +0000520 return PyInt_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000521}
522
Guido van Rossum53807da2007-04-10 19:01:47 +0000523/* XXX Windows support below is likely incomplete */
524
525#if defined(MS_WIN64) || defined(MS_WINDOWS)
526typedef PY_LONG_LONG Py_off_t;
527#else
528typedef off_t Py_off_t;
529#endif
530
531/* Cribbed from posix_lseek() */
532static PyObject *
533portable_lseek(int fd, PyObject *posobj, int whence)
534{
535 Py_off_t pos, res;
536
537#ifdef SEEK_SET
538 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
539 switch (whence) {
540#if SEEK_SET != 0
541 case 0: whence = SEEK_SET; break;
542#endif
543#if SEEK_CUR != 1
544 case 1: whence = SEEK_CUR; break;
545#endif
546#if SEEL_END != 2
547 case 2: whence = SEEK_END; break;
548#endif
549 }
550#endif /* SEEK_SET */
551
552 if (posobj == NULL)
553 pos = 0;
554 else {
555#if !defined(HAVE_LARGEFILE_SUPPORT)
556 pos = PyInt_AsLong(posobj);
557#else
558 pos = PyLong_Check(posobj) ?
559 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
560#endif
561 if (PyErr_Occurred())
562 return NULL;
563 }
564
565 Py_BEGIN_ALLOW_THREADS
566#if defined(MS_WIN64) || defined(MS_WINDOWS)
567 res = _lseeki64(fd, pos, whence);
568#else
569 res = lseek(fd, pos, whence);
570#endif
571 Py_END_ALLOW_THREADS
572 if (res < 0)
573 return PyErr_SetFromErrno(PyExc_IOError);
574
575#if !defined(HAVE_LARGEFILE_SUPPORT)
576 return PyInt_FromLong(res);
577#else
578 return PyLong_FromLongLong(res);
579#endif
580}
581
Guido van Rossuma9e20242007-03-08 00:43:48 +0000582static PyObject *
583fileio_seek(PyFileIOObject *self, PyObject *args)
584{
Guido van Rossum53807da2007-04-10 19:01:47 +0000585 PyObject *posobj;
586 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000587
588 if (self->fd < 0)
589 return err_closed();
590
Guido van Rossum53807da2007-04-10 19:01:47 +0000591 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000592 return NULL;
593
Guido van Rossum53807da2007-04-10 19:01:47 +0000594 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000595}
596
597static PyObject *
598fileio_tell(PyFileIOObject *self, PyObject *args)
599{
Guido van Rossuma9e20242007-03-08 00:43:48 +0000600 if (self->fd < 0)
601 return err_closed();
602
Guido van Rossum53807da2007-04-10 19:01:47 +0000603 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000604}
605
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000606#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000607static PyObject *
608fileio_truncate(PyFileIOObject *self, PyObject *args)
609{
Guido van Rossum53807da2007-04-10 19:01:47 +0000610 PyObject *posobj = NULL;
611 Py_off_t pos;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000612 int ret;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000613 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000614
Guido van Rossum53807da2007-04-10 19:01:47 +0000615 fd = self->fd;
616 if (fd < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000617 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000618 if (!self->writable)
619 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000620
Guido van Rossum53807da2007-04-10 19:01:47 +0000621 if (!PyArg_ParseTuple(args, "|O", &posobj))
622 return NULL;
623
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000624 if (posobj == Py_None || posobj == NULL) {
625 posobj = portable_lseek(fd, NULL, 1);
626 if (posobj == NULL)
627 return NULL;
628 }
629 else {
630 Py_INCREF(posobj);
631 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000632
633#if !defined(HAVE_LARGEFILE_SUPPORT)
634 pos = PyInt_AsLong(posobj);
635#else
636 pos = PyLong_Check(posobj) ?
637 PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj);
638#endif
Guido van Rossum87429772007-04-10 21:06:59 +0000639 if (PyErr_Occurred()) {
640 Py_DECREF(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000641 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000642 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000643
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000644#ifdef MS_WINDOWS
645 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
646 so don't even try using it. */
647 {
648 HANDLE hFile;
Guido van Rossum57233cb2007-10-26 17:19:33 +0000649 PyObject *pos2, *oldposobj;
650
651 /* store the current position */
652 oldposobj = portable_lseek(self->fd, NULL, 1);
653 if (oldposobj == NULL) {
654 Py_DECREF(posobj);
655 return NULL;
656 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000657
658 /* Have to move current pos to desired endpoint on Windows. */
659 errno = 0;
660 pos2 = portable_lseek(fd, posobj, SEEK_SET);
Guido van Rossum57233cb2007-10-26 17:19:33 +0000661 if (pos2 == NULL) {
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000662 Py_DECREF(posobj);
Guido van Rossum57233cb2007-10-26 17:19:33 +0000663 Py_DECREF(oldposobj);
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000664 return NULL;
665 }
666 Py_DECREF(pos2);
667
668 /* Truncate. Note that this may grow the file! */
669 Py_BEGIN_ALLOW_THREADS
670 errno = 0;
671 hFile = (HANDLE)_get_osfhandle(fd);
672 ret = hFile == (HANDLE)-1;
673 if (ret == 0) {
674 ret = SetEndOfFile(hFile) == 0;
675 if (ret)
676 errno = EACCES;
677 }
678 Py_END_ALLOW_THREADS
Guido van Rossum57233cb2007-10-26 17:19:33 +0000679
680 if (ret == 0) {
681 /* Move to the previous position in the file */
682 pos2 = portable_lseek(fd, oldposobj, SEEK_SET);
683 if (pos2 == NULL) {
684 Py_DECREF(posobj);
685 Py_DECREF(oldposobj);
686 return NULL;
687 }
688 }
689 Py_DECREF(pos2);
690 Py_DECREF(oldposobj);
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000691 }
692#else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000693 Py_BEGIN_ALLOW_THREADS
694 errno = 0;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000695 ret = ftruncate(fd, pos);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000696 Py_END_ALLOW_THREADS
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000697#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000698
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000699 if (ret != 0) {
Guido van Rossum87429772007-04-10 21:06:59 +0000700 Py_DECREF(posobj);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000701 PyErr_SetFromErrno(PyExc_IOError);
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000702 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000703 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000704
Guido van Rossum87429772007-04-10 21:06:59 +0000705 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000706}
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000707#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000708
709static char *
710mode_string(PyFileIOObject *self)
711{
712 if (self->readable) {
713 if (self->writable)
714 return "r+";
715 else
716 return "r";
717 }
718 else
719 return "w";
720}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000721
722static PyObject *
723fileio_repr(PyFileIOObject *self)
724{
Guido van Rossum53807da2007-04-10 19:01:47 +0000725 if (self->fd < 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000726 return PyUnicode_FromFormat("_fileio._FileIO(-1)");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000727
Walter Dörwald1ab83302007-05-18 17:15:44 +0000728 return PyUnicode_FromFormat("_fileio._FileIO(%d, '%s')",
Guido van Rossum53807da2007-04-10 19:01:47 +0000729 self->fd, mode_string(self));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000730}
731
732static PyObject *
733fileio_isatty(PyFileIOObject *self)
734{
735 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000736
Guido van Rossuma9e20242007-03-08 00:43:48 +0000737 if (self->fd < 0)
738 return err_closed();
739 Py_BEGIN_ALLOW_THREADS
740 res = isatty(self->fd);
741 Py_END_ALLOW_THREADS
742 return PyBool_FromLong(res);
743}
744
Guido van Rossuma9e20242007-03-08 00:43:48 +0000745
746PyDoc_STRVAR(fileio_doc,
747"file(name: str[, mode: str]) -> file IO object\n"
748"\n"
749"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
750"writing or appending. The file will be created if it doesn't exist\n"
751"when opened for writing or appending; it will be truncated when\n"
752"opened for writing. Add a '+' to the mode to allow simultaneous\n"
753"reading and writing.");
754
755PyDoc_STRVAR(read_doc,
756"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
757"\n"
758"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000759"In non-blocking mode, returns None if no data is available.\n"
760"On end-of-file, returns ''.");
761
762PyDoc_STRVAR(readall_doc,
763"readall() -> bytes. read all data from the file, returned as bytes.\n"
764"\n"
765"In non-blocking mode, returns as much as is immediately available,\n"
766"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000767
768PyDoc_STRVAR(write_doc,
769"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
770"\n"
771"Only makes one system call, so not all of the data may be written.\n"
772"The number of bytes actually written is returned.");
773
774PyDoc_STRVAR(fileno_doc,
775"fileno() -> int. \"file descriptor\".\n"
776"\n"
777"This is needed for lower-level file interfaces, such the fcntl module.");
778
779PyDoc_STRVAR(seek_doc,
780"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
781"\n"
782"Argument offset is a byte count. Optional argument whence defaults to\n"
783"0 (offset from start of file, offset should be >= 0); other values are 1\n"
784"(move relative to current position, positive or negative), and 2 (move\n"
785"relative to end of file, usually negative, although many platforms allow\n"
786"seeking beyond the end of a file)."
787"\n"
788"Note that not all file objects are seekable.");
789
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000790#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000791PyDoc_STRVAR(truncate_doc,
792"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
793"\n"
794"Size defaults to the current file position, as returned by tell().");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000795#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000796
797PyDoc_STRVAR(tell_doc,
798"tell() -> int. Current file position");
799
800PyDoc_STRVAR(readinto_doc,
801"readinto() -> Undocumented. Don't use this; it may go away.");
802
803PyDoc_STRVAR(close_doc,
804"close() -> None. Close the file.\n"
805"\n"
806"A closed file cannot be used for further I/O operations. close() may be\n"
807"called more than once without error. Changes the fileno to -1.");
808
809PyDoc_STRVAR(isatty_doc,
810"isatty() -> bool. True if the file is connected to a tty device.");
811
Guido van Rossuma9e20242007-03-08 00:43:48 +0000812PyDoc_STRVAR(seekable_doc,
813"seekable() -> bool. True if file supports random-access.");
814
815PyDoc_STRVAR(readable_doc,
816"readable() -> bool. True if file was opened in a read mode.");
817
818PyDoc_STRVAR(writable_doc,
819"writable() -> bool. True if file was opened in a write mode.");
820
821static PyMethodDef fileio_methods[] = {
822 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
Guido van Rossum7165cb12007-07-10 06:54:34 +0000823 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000824 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
825 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
826 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
827 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000828#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000829 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000830#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000831 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
832 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
833 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
834 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
835 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
836 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000837 {NULL, NULL} /* sentinel */
838};
839
Guido van Rossum53807da2007-04-10 19:01:47 +0000840/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
841
Guido van Rossumb0428152007-04-08 17:44:42 +0000842static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000843get_closed(PyFileIOObject *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +0000844{
Guido van Rossum53807da2007-04-10 19:01:47 +0000845 return PyBool_FromLong((long)(self->fd < 0));
846}
847
848static PyObject *
849get_mode(PyFileIOObject *self, void *closure)
850{
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000851 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +0000852}
853
854static PyGetSetDef fileio_getsetlist[] = {
855 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Guido van Rossum53807da2007-04-10 19:01:47 +0000856 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Guido van Rossumb0428152007-04-08 17:44:42 +0000857 {0},
858};
859
Guido van Rossuma9e20242007-03-08 00:43:48 +0000860PyTypeObject PyFileIO_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000861 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000862 "FileIO",
863 sizeof(PyFileIOObject),
864 0,
865 (destructor)fileio_dealloc, /* tp_dealloc */
866 0, /* tp_print */
867 0, /* tp_getattr */
868 0, /* tp_setattr */
869 0, /* tp_compare */
870 (reprfunc)fileio_repr, /* tp_repr */
871 0, /* tp_as_number */
872 0, /* tp_as_sequence */
873 0, /* tp_as_mapping */
874 0, /* tp_hash */
875 0, /* tp_call */
876 0, /* tp_str */
877 PyObject_GenericGetAttr, /* tp_getattro */
878 0, /* tp_setattro */
879 0, /* tp_as_buffer */
880 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
881 fileio_doc, /* tp_doc */
882 0, /* tp_traverse */
883 0, /* tp_clear */
884 0, /* tp_richcompare */
885 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
886 0, /* tp_iter */
887 0, /* tp_iternext */
888 fileio_methods, /* tp_methods */
889 0, /* tp_members */
Guido van Rossumb0428152007-04-08 17:44:42 +0000890 fileio_getsetlist, /* tp_getset */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000891 0, /* tp_base */
892 0, /* tp_dict */
893 0, /* tp_descr_get */
894 0, /* tp_descr_set */
895 0, /* tp_dictoffset */
896 fileio_init, /* tp_init */
897 PyType_GenericAlloc, /* tp_alloc */
898 fileio_new, /* tp_new */
899 PyObject_Del, /* tp_free */
900};
901
902static PyMethodDef module_methods[] = {
903 {NULL, NULL}
904};
905
906PyMODINIT_FUNC
907init_fileio(void)
908{
909 PyObject *m; /* a module object */
910
911 m = Py_InitModule3("_fileio", module_methods,
912 "Fast implementation of io.FileIO.");
913 if (m == NULL)
914 return;
915 if (PyType_Ready(&PyFileIO_Type) < 0)
916 return;
917 Py_INCREF(&PyFileIO_Type);
918 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
919}