blob: f520f0c701fc149ca1c0dc5f3f05c71eac35da27 [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)) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000107 char *msg = strerror(EISDIR);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000108 PyObject *exc;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000109 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000110
Guido van Rossuma9e20242007-03-08 00:43:48 +0000111 exc = PyObject_CallFunction(PyExc_IOError, "(is)",
112 EISDIR, msg);
113 PyErr_SetObject(PyExc_IOError, exc);
114 Py_XDECREF(exc);
115 return -1;
116 }
117#endif
118 return 0;
119}
120
121
122static int
123fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
124{
125 PyFileIOObject *self = (PyFileIOObject *) oself;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000126 static char *kwlist[] = {"file", "mode", "closefd", NULL};
Guido van Rossuma9e20242007-03-08 00:43:48 +0000127 char *name = NULL;
128 char *mode = "r";
Guido van Rossum53807da2007-04-10 19:01:47 +0000129 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000130#ifdef MS_WINDOWS
131 Py_UNICODE *widename = NULL;
132#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000133 int ret = 0;
134 int rwa = 0, plus = 0, append = 0;
135 int flags = 0;
Guido van Rossumb0428152007-04-08 17:44:42 +0000136 int fd = -1;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000137 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000138
139 assert(PyFileIO_Check(oself));
Neal Norwitz88b44da2007-08-12 17:23:54 +0000140 if (self->fd >= 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000141 /* Have to close the existing file first. */
Neal Norwitz88b44da2007-08-12 17:23:54 +0000142 if (internal_close(self) < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000143 return -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000144 }
145
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000146 if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio",
147 kwlist, &fd, &mode, &closefd)) {
Guido van Rossumb0428152007-04-08 17:44:42 +0000148 if (fd < 0) {
149 PyErr_SetString(PyExc_ValueError,
150 "Negative filedescriptor");
151 return -1;
152 }
153 }
154 else {
155 PyErr_Clear();
156
Guido van Rossuma9e20242007-03-08 00:43:48 +0000157#ifdef Py_WIN_WIDE_FILENAMES
Guido van Rossumb0428152007-04-08 17:44:42 +0000158 if (GetVersion() < 0x80000000) {
159 /* On NT, so wide API available */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000160 PyObject *po;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000161 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio",
162 kwlist, &po, &mode, &closefd)
163 ) {
Thomas Helleraf2be262007-07-12 11:03:13 +0000164 widename = PyUnicode_AS_UNICODE(po);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000165 } else {
166 /* Drop the argument parsing error as narrow
167 strings are also valid. */
168 PyErr_Clear();
169 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000170 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000171 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000172#endif
Thomas Helleraf2be262007-07-12 11:03:13 +0000173 {
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000174 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio",
Guido van Rossuma9e20242007-03-08 00:43:48 +0000175 kwlist,
176 Py_FileSystemDefaultEncoding,
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000177 &name, &mode, &closefd))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000178 goto error;
Guido van Rossumb0428152007-04-08 17:44:42 +0000179 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000180 }
181
182 self->readable = self->writable = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000183 self->seekable = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000184 s = mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000185 while (*s) {
186 switch (*s++) {
187 case 'r':
188 if (rwa) {
189 bad_mode:
190 PyErr_SetString(PyExc_ValueError,
191 "Must have exactly one of read/write/append mode");
192 goto error;
193 }
194 rwa = 1;
195 self->readable = 1;
196 break;
197 case 'w':
198 if (rwa)
199 goto bad_mode;
200 rwa = 1;
201 self->writable = 1;
202 flags |= O_CREAT | O_TRUNC;
203 break;
204 case 'a':
205 if (rwa)
206 goto bad_mode;
207 rwa = 1;
208 self->writable = 1;
209 flags |= O_CREAT;
210 append = 1;
211 break;
212 case '+':
213 if (plus)
214 goto bad_mode;
215 self->readable = self->writable = 1;
216 plus = 1;
217 break;
218 default:
219 PyErr_Format(PyExc_ValueError,
220 "invalid mode: %.200s", mode);
221 goto error;
222 }
223 }
224
225 if (!rwa)
226 goto bad_mode;
227
228 if (self->readable && self->writable)
229 flags |= O_RDWR;
230 else if (self->readable)
231 flags |= O_RDONLY;
232 else
233 flags |= O_WRONLY;
234
235#ifdef O_BINARY
236 flags |= O_BINARY;
237#endif
238
Walter Dörwald0e411482007-06-06 16:55:38 +0000239#ifdef O_APPEND
240 if (append)
241 flags |= O_APPEND;
242#endif
243
Guido van Rossumb0428152007-04-08 17:44:42 +0000244 if (fd >= 0) {
245 self->fd = fd;
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000246 self->closefd = closefd;
Guido van Rossumb0428152007-04-08 17:44:42 +0000247 }
248 else {
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000249 self->closefd = 1;
250 if (!closefd) {
251 PyErr_SetString(PyExc_ValueError,
252 "Cannot use closefd=True with file name");
253 goto error;
254 }
255
Guido van Rossumb0428152007-04-08 17:44:42 +0000256 Py_BEGIN_ALLOW_THREADS
257 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000258#ifdef MS_WINDOWS
259 if (widename != NULL)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000260 self->fd = _wopen(widename, flags, 0666);
Thomas Helleraf2be262007-07-12 11:03:13 +0000261 else
262#endif
Neal Norwitz88b44da2007-08-12 17:23:54 +0000263 self->fd = open(name, flags, 0666);
Guido van Rossumb0428152007-04-08 17:44:42 +0000264 Py_END_ALLOW_THREADS
265 if (self->fd < 0 || dircheck(self) < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000266#ifdef MS_WINDOWS
267 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
268#else
Guido van Rossumb0428152007-04-08 17:44:42 +0000269 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Christian Heimes0b489542007-10-31 19:20:48 +0000270#endif
Guido van Rossumb0428152007-04-08 17:44:42 +0000271 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:
Guido van Rossuma9e20242007-03-08 00:43:48 +0000281 return ret;
282}
283
284static void
285fileio_dealloc(PyFileIOObject *self)
286{
287 if (self->weakreflist != NULL)
288 PyObject_ClearWeakRefs((PyObject *) self);
289
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000290 if (self->fd >= 0 && self->closefd) {
Neal Norwitz88b44da2007-08-12 17:23:54 +0000291 errno = internal_close(self);
292 if (errno < 0) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000293 PySys_WriteStderr("close failed: [Errno %d] %s\n",
294 errno, strerror(errno));
Neal Norwitz88b44da2007-08-12 17:23:54 +0000295 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000296 }
297
Christian Heimes90aa7642007-12-19 02:45:37 +0000298 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000299}
300
301static PyObject *
302err_closed(void)
303{
304 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
305 return NULL;
306}
307
308static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000309err_mode(char *action)
310{
311 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
312 return NULL;
313}
314
315static PyObject *
Guido van Rossuma9e20242007-03-08 00:43:48 +0000316fileio_fileno(PyFileIOObject *self)
317{
318 if (self->fd < 0)
319 return err_closed();
Christian Heimes217cfd12007-12-02 14:31:20 +0000320 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000321}
322
323static PyObject *
324fileio_readable(PyFileIOObject *self)
325{
326 if (self->fd < 0)
327 return err_closed();
Neal Norwitz88b44da2007-08-12 17:23:54 +0000328 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000329}
330
331static PyObject *
332fileio_writable(PyFileIOObject *self)
333{
334 if (self->fd < 0)
335 return err_closed();
Neal Norwitz88b44da2007-08-12 17:23:54 +0000336 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000337}
338
339static PyObject *
340fileio_seekable(PyFileIOObject *self)
341{
342 if (self->fd < 0)
343 return err_closed();
344 if (self->seekable < 0) {
345 int ret;
346 Py_BEGIN_ALLOW_THREADS
347 ret = lseek(self->fd, 0, SEEK_CUR);
348 Py_END_ALLOW_THREADS
349 if (ret < 0)
350 self->seekable = 0;
351 else
352 self->seekable = 1;
353 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000354 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000355}
356
357static PyObject *
358fileio_readinto(PyFileIOObject *self, PyObject *args)
359{
360 char *ptr;
361 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000362
Guido van Rossuma9e20242007-03-08 00:43:48 +0000363 if (self->fd < 0)
364 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000365 if (!self->readable)
366 return err_mode("reading");
367
Guido van Rossuma9e20242007-03-08 00:43:48 +0000368 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
369 return NULL;
370
371 Py_BEGIN_ALLOW_THREADS
372 errno = 0;
373 n = read(self->fd, ptr, n);
374 Py_END_ALLOW_THREADS
375 if (n < 0) {
376 if (errno == EAGAIN)
377 Py_RETURN_NONE;
378 PyErr_SetFromErrno(PyExc_IOError);
379 return NULL;
380 }
381
Christian Heimes217cfd12007-12-02 14:31:20 +0000382 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000383}
384
Guido van Rossum7165cb12007-07-10 06:54:34 +0000385#define DEFAULT_BUFFER_SIZE (8*1024)
386
387static PyObject *
388fileio_readall(PyFileIOObject *self)
389{
390 PyObject *result;
391 Py_ssize_t total = 0;
392 int n;
393
Christian Heimes72b710a2008-05-26 13:28:38 +0000394 result = PyBytes_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
Guido van Rossum7165cb12007-07-10 06:54:34 +0000395 if (result == NULL)
396 return NULL;
397
398 while (1) {
399 Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
Christian Heimes72b710a2008-05-26 13:28:38 +0000400 if (PyBytes_GET_SIZE(result) < newsize) {
401 if (_PyBytes_Resize(&result, newsize) < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000402 if (total == 0) {
403 Py_DECREF(result);
404 return NULL;
405 }
406 PyErr_Clear();
407 break;
408 }
409 }
410 Py_BEGIN_ALLOW_THREADS
411 errno = 0;
412 n = read(self->fd,
Christian Heimes72b710a2008-05-26 13:28:38 +0000413 PyBytes_AS_STRING(result) + total,
Guido van Rossum7165cb12007-07-10 06:54:34 +0000414 newsize - total);
415 Py_END_ALLOW_THREADS
416 if (n == 0)
417 break;
418 if (n < 0) {
419 if (total > 0)
420 break;
421 if (errno == EAGAIN) {
422 Py_DECREF(result);
423 Py_RETURN_NONE;
424 }
425 Py_DECREF(result);
426 PyErr_SetFromErrno(PyExc_IOError);
427 return NULL;
428 }
429 total += n;
430 }
431
Christian Heimes72b710a2008-05-26 13:28:38 +0000432 if (PyBytes_GET_SIZE(result) > total) {
433 if (_PyBytes_Resize(&result, total) < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000434 /* This should never happen, but just in case */
435 Py_DECREF(result);
436 return NULL;
437 }
438 }
439 return result;
440}
441
Guido van Rossuma9e20242007-03-08 00:43:48 +0000442static PyObject *
443fileio_read(PyFileIOObject *self, PyObject *args)
444{
445 char *ptr;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000446 Py_ssize_t n;
447 Py_ssize_t size = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000448 PyObject *bytes;
449
450 if (self->fd < 0)
451 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000452 if (!self->readable)
453 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000454
Neal Norwitz3c8ba932007-08-08 04:36:17 +0000455 if (!PyArg_ParseTuple(args, "|n", &size))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000456 return NULL;
457
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000458 if (size < 0) {
Guido van Rossum7165cb12007-07-10 06:54:34 +0000459 return fileio_readall(self);
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000460 }
461
Christian Heimes72b710a2008-05-26 13:28:38 +0000462 bytes = PyBytes_FromStringAndSize(NULL, size);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000463 if (bytes == NULL)
464 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +0000465 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000466
467 Py_BEGIN_ALLOW_THREADS
468 errno = 0;
469 n = read(self->fd, ptr, size);
470 Py_END_ALLOW_THREADS
471
472 if (n < 0) {
473 if (errno == EAGAIN)
474 Py_RETURN_NONE;
475 PyErr_SetFromErrno(PyExc_IOError);
476 return NULL;
477 }
478
479 if (n != size) {
Christian Heimes72b710a2008-05-26 13:28:38 +0000480 if (_PyBytes_Resize(&bytes, n) < 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000481 Py_DECREF(bytes);
Guido van Rossum53807da2007-04-10 19:01:47 +0000482 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000483 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000484 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000485
486 return (PyObject *) bytes;
487}
488
489static PyObject *
490fileio_write(PyFileIOObject *self, PyObject *args)
491{
492 Py_ssize_t n;
493 char *ptr;
494
495 if (self->fd < 0)
496 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000497 if (!self->writable)
498 return err_mode("writing");
499
Guido van Rossuma9e20242007-03-08 00:43:48 +0000500 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
501 return NULL;
502
503 Py_BEGIN_ALLOW_THREADS
504 errno = 0;
505 n = write(self->fd, ptr, n);
506 Py_END_ALLOW_THREADS
507
508 if (n < 0) {
509 if (errno == EAGAIN)
510 Py_RETURN_NONE;
511 PyErr_SetFromErrno(PyExc_IOError);
512 return NULL;
513 }
514
Christian Heimes217cfd12007-12-02 14:31:20 +0000515 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000516}
517
Guido van Rossum53807da2007-04-10 19:01:47 +0000518/* XXX Windows support below is likely incomplete */
519
520#if defined(MS_WIN64) || defined(MS_WINDOWS)
521typedef PY_LONG_LONG Py_off_t;
522#else
523typedef off_t Py_off_t;
524#endif
525
526/* Cribbed from posix_lseek() */
527static PyObject *
528portable_lseek(int fd, PyObject *posobj, int whence)
529{
530 Py_off_t pos, res;
531
532#ifdef SEEK_SET
533 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
534 switch (whence) {
535#if SEEK_SET != 0
536 case 0: whence = SEEK_SET; break;
537#endif
538#if SEEK_CUR != 1
539 case 1: whence = SEEK_CUR; break;
540#endif
541#if SEEL_END != 2
542 case 2: whence = SEEK_END; break;
543#endif
544 }
545#endif /* SEEK_SET */
546
547 if (posobj == NULL)
548 pos = 0;
549 else {
Christian Heimes8e42a0a2007-11-08 18:04:45 +0000550 if(PyFloat_Check(posobj)) {
551 PyErr_SetString(PyExc_TypeError, "an integer is required");
552 return NULL;
553 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000554#if defined(HAVE_LARGEFILE_SUPPORT)
555 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000556#else
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000557 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000558#endif
559 if (PyErr_Occurred())
560 return NULL;
561 }
562
563 Py_BEGIN_ALLOW_THREADS
564#if defined(MS_WIN64) || defined(MS_WINDOWS)
565 res = _lseeki64(fd, pos, whence);
566#else
567 res = lseek(fd, pos, whence);
568#endif
569 Py_END_ALLOW_THREADS
570 if (res < 0)
571 return PyErr_SetFromErrno(PyExc_IOError);
572
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000573#if defined(HAVE_LARGEFILE_SUPPORT)
Guido van Rossum53807da2007-04-10 19:01:47 +0000574 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000575#else
576 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000577#endif
578}
579
Guido van Rossuma9e20242007-03-08 00:43:48 +0000580static PyObject *
581fileio_seek(PyFileIOObject *self, PyObject *args)
582{
Guido van Rossum53807da2007-04-10 19:01:47 +0000583 PyObject *posobj;
584 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000585
586 if (self->fd < 0)
587 return err_closed();
588
Guido van Rossum53807da2007-04-10 19:01:47 +0000589 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
Guido van Rossuma9e20242007-03-08 00:43:48 +0000590 return NULL;
591
Guido van Rossum53807da2007-04-10 19:01:47 +0000592 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000593}
594
595static PyObject *
596fileio_tell(PyFileIOObject *self, PyObject *args)
597{
Guido van Rossuma9e20242007-03-08 00:43:48 +0000598 if (self->fd < 0)
599 return err_closed();
600
Guido van Rossum53807da2007-04-10 19:01:47 +0000601 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000602}
603
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000604#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000605static PyObject *
606fileio_truncate(PyFileIOObject *self, PyObject *args)
607{
Guido van Rossum53807da2007-04-10 19:01:47 +0000608 PyObject *posobj = NULL;
609 Py_off_t pos;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000610 int ret;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000611 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000612
Guido van Rossum53807da2007-04-10 19:01:47 +0000613 fd = self->fd;
614 if (fd < 0)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000615 return err_closed();
Guido van Rossum53807da2007-04-10 19:01:47 +0000616 if (!self->writable)
617 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000618
Guido van Rossum53807da2007-04-10 19:01:47 +0000619 if (!PyArg_ParseTuple(args, "|O", &posobj))
620 return NULL;
621
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000622 if (posobj == Py_None || posobj == NULL) {
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000623 /* Get the current position. */
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000624 posobj = portable_lseek(fd, NULL, 1);
625 if (posobj == NULL)
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000626 return NULL;
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000627 }
628 else {
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000629 /* Move to the position to be truncated. */
630 posobj = portable_lseek(fd, posobj, 0);
Guido van Rossumdc0b1a12007-04-12 22:55:07 +0000631 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000632
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000633#if defined(HAVE_LARGEFILE_SUPPORT)
634 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000635#else
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000636 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000637#endif
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000638 if (PyErr_Occurred())
Guido van Rossum53807da2007-04-10 19:01:47 +0000639 return NULL;
640
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000641#ifdef MS_WINDOWS
642 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
643 so don't even try using it. */
644 {
645 HANDLE hFile;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000646
647 /* Truncate. Note that this may grow the file! */
648 Py_BEGIN_ALLOW_THREADS
649 errno = 0;
650 hFile = (HANDLE)_get_osfhandle(fd);
651 ret = hFile == (HANDLE)-1;
652 if (ret == 0) {
653 ret = SetEndOfFile(hFile) == 0;
654 if (ret)
655 errno = EACCES;
656 }
657 Py_END_ALLOW_THREADS
658 }
659#else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000660 Py_BEGIN_ALLOW_THREADS
661 errno = 0;
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000662 ret = ftruncate(fd, pos);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000663 Py_END_ALLOW_THREADS
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000664#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000665
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000666 if (ret != 0) {
Guido van Rossuma9e20242007-03-08 00:43:48 +0000667 PyErr_SetFromErrno(PyExc_IOError);
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000668 return NULL;
Guido van Rossum87429772007-04-10 21:06:59 +0000669 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000670
Guido van Rossum87429772007-04-10 21:06:59 +0000671 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000672}
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000673#endif
Guido van Rossum53807da2007-04-10 19:01:47 +0000674
675static char *
676mode_string(PyFileIOObject *self)
677{
678 if (self->readable) {
679 if (self->writable)
680 return "r+";
681 else
682 return "r";
683 }
684 else
685 return "w";
686}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000687
688static PyObject *
689fileio_repr(PyFileIOObject *self)
690{
Guido van Rossum53807da2007-04-10 19:01:47 +0000691 if (self->fd < 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000692 return PyUnicode_FromFormat("_fileio._FileIO(-1)");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000693
Walter Dörwald1ab83302007-05-18 17:15:44 +0000694 return PyUnicode_FromFormat("_fileio._FileIO(%d, '%s')",
Guido van Rossum53807da2007-04-10 19:01:47 +0000695 self->fd, mode_string(self));
Guido van Rossuma9e20242007-03-08 00:43:48 +0000696}
697
698static PyObject *
699fileio_isatty(PyFileIOObject *self)
700{
701 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000702
Guido van Rossuma9e20242007-03-08 00:43:48 +0000703 if (self->fd < 0)
704 return err_closed();
705 Py_BEGIN_ALLOW_THREADS
706 res = isatty(self->fd);
707 Py_END_ALLOW_THREADS
708 return PyBool_FromLong(res);
709}
710
Guido van Rossuma9e20242007-03-08 00:43:48 +0000711
712PyDoc_STRVAR(fileio_doc,
713"file(name: str[, mode: str]) -> file IO object\n"
714"\n"
715"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
716"writing or appending. The file will be created if it doesn't exist\n"
717"when opened for writing or appending; it will be truncated when\n"
718"opened for writing. Add a '+' to the mode to allow simultaneous\n"
719"reading and writing.");
720
721PyDoc_STRVAR(read_doc,
722"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
723"\n"
724"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000725"In non-blocking mode, returns None if no data is available.\n"
726"On end-of-file, returns ''.");
727
728PyDoc_STRVAR(readall_doc,
729"readall() -> bytes. read all data from the file, returned as bytes.\n"
730"\n"
731"In non-blocking mode, returns as much as is immediately available,\n"
732"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000733
734PyDoc_STRVAR(write_doc,
735"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
736"\n"
737"Only makes one system call, so not all of the data may be written.\n"
738"The number of bytes actually written is returned.");
739
740PyDoc_STRVAR(fileno_doc,
741"fileno() -> int. \"file descriptor\".\n"
742"\n"
743"This is needed for lower-level file interfaces, such the fcntl module.");
744
745PyDoc_STRVAR(seek_doc,
746"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
747"\n"
748"Argument offset is a byte count. Optional argument whence defaults to\n"
749"0 (offset from start of file, offset should be >= 0); other values are 1\n"
750"(move relative to current position, positive or negative), and 2 (move\n"
751"relative to end of file, usually negative, although many platforms allow\n"
752"seeking beyond the end of a file)."
753"\n"
754"Note that not all file objects are seekable.");
755
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000756#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000757PyDoc_STRVAR(truncate_doc,
758"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
759"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000760"Size defaults to the current file position, as returned by tell()."
761"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000762#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000763
764PyDoc_STRVAR(tell_doc,
765"tell() -> int. Current file position");
766
767PyDoc_STRVAR(readinto_doc,
768"readinto() -> Undocumented. Don't use this; it may go away.");
769
770PyDoc_STRVAR(close_doc,
771"close() -> None. Close the file.\n"
772"\n"
773"A closed file cannot be used for further I/O operations. close() may be\n"
774"called more than once without error. Changes the fileno to -1.");
775
776PyDoc_STRVAR(isatty_doc,
777"isatty() -> bool. True if the file is connected to a tty device.");
778
Guido van Rossuma9e20242007-03-08 00:43:48 +0000779PyDoc_STRVAR(seekable_doc,
780"seekable() -> bool. True if file supports random-access.");
781
782PyDoc_STRVAR(readable_doc,
783"readable() -> bool. True if file was opened in a read mode.");
784
785PyDoc_STRVAR(writable_doc,
786"writable() -> bool. True if file was opened in a write mode.");
787
788static PyMethodDef fileio_methods[] = {
789 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
Guido van Rossum7165cb12007-07-10 06:54:34 +0000790 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000791 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
792 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
793 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
794 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000795#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000796 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000797#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000798 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
799 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
800 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
801 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
802 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
803 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Guido van Rossuma9e20242007-03-08 00:43:48 +0000804 {NULL, NULL} /* sentinel */
805};
806
Guido van Rossum53807da2007-04-10 19:01:47 +0000807/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
808
Guido van Rossumb0428152007-04-08 17:44:42 +0000809static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000810get_closed(PyFileIOObject *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +0000811{
Guido van Rossum53807da2007-04-10 19:01:47 +0000812 return PyBool_FromLong((long)(self->fd < 0));
813}
814
815static PyObject *
816get_mode(PyFileIOObject *self, void *closure)
817{
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000818 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +0000819}
820
821static PyGetSetDef fileio_getsetlist[] = {
822 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Guido van Rossum53807da2007-04-10 19:01:47 +0000823 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Guido van Rossumb0428152007-04-08 17:44:42 +0000824 {0},
825};
826
Guido van Rossuma9e20242007-03-08 00:43:48 +0000827PyTypeObject PyFileIO_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000828 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Amaury Forgeot d'Arc1ff99102007-11-19 20:34:10 +0000829 "_FileIO",
Guido van Rossuma9e20242007-03-08 00:43:48 +0000830 sizeof(PyFileIOObject),
831 0,
832 (destructor)fileio_dealloc, /* tp_dealloc */
833 0, /* tp_print */
834 0, /* tp_getattr */
835 0, /* tp_setattr */
836 0, /* tp_compare */
837 (reprfunc)fileio_repr, /* tp_repr */
838 0, /* tp_as_number */
839 0, /* tp_as_sequence */
840 0, /* tp_as_mapping */
841 0, /* tp_hash */
842 0, /* tp_call */
843 0, /* tp_str */
844 PyObject_GenericGetAttr, /* tp_getattro */
845 0, /* tp_setattro */
846 0, /* tp_as_buffer */
847 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
848 fileio_doc, /* tp_doc */
849 0, /* tp_traverse */
850 0, /* tp_clear */
851 0, /* tp_richcompare */
852 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
853 0, /* tp_iter */
854 0, /* tp_iternext */
855 fileio_methods, /* tp_methods */
856 0, /* tp_members */
Guido van Rossumb0428152007-04-08 17:44:42 +0000857 fileio_getsetlist, /* tp_getset */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000858 0, /* tp_base */
859 0, /* tp_dict */
860 0, /* tp_descr_get */
861 0, /* tp_descr_set */
862 0, /* tp_dictoffset */
863 fileio_init, /* tp_init */
864 PyType_GenericAlloc, /* tp_alloc */
865 fileio_new, /* tp_new */
866 PyObject_Del, /* tp_free */
867};
868
869static PyMethodDef module_methods[] = {
870 {NULL, NULL}
871};
872
Martin v. Löwis1a214512008-06-11 05:26:20 +0000873static struct PyModuleDef fileiomodule = {
874 PyModuleDef_HEAD_INIT,
875 "_fileio",
876 "Fast implementation of io.FileIO.",
877 -1,
878 module_methods,
879 NULL,
880 NULL,
881 NULL,
882 NULL
883};
884
Guido van Rossuma9e20242007-03-08 00:43:48 +0000885PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000886PyInit__fileio(void)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000887{
888 PyObject *m; /* a module object */
889
Martin v. Löwis1a214512008-06-11 05:26:20 +0000890 m = PyModule_Create(&fileiomodule);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000891 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000892 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000893 if (PyType_Ready(&PyFileIO_Type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000894 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000895 Py_INCREF(&PyFileIO_Type);
896 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000897 return m;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000898}