blob: a685b134a3b9bb66ce3412f3007e453249c5c9f8 [file] [log] [blame]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +00005#ifdef HAVE_SYS_TYPES_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +00006#include <sys/types.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +00007#endif
8#ifdef HAVE_SYS_STAT_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +00009#include <sys/stat.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000010#endif
11#ifdef HAVE_FCNTL_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +000012#include <fcntl.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000013#endif
Christian Heimes7f39c9f2008-01-25 12:18:43 +000014#include <stddef.h> /* For offsetof */
Antoine Pitrou19690592009-06-12 20:14:08 +000015#include "_iomodule.h"
Christian Heimes7f39c9f2008-01-25 12:18:43 +000016
17/*
18 * Known likely problems:
19 *
20 * - Files larger then 2**32-1
21 * - Files with unicode filenames
22 * - Passing numbers greater than 2**32-1 when an integer is expected
23 * - Making it work on Windows and other oddball platforms
24 *
25 * To Do:
26 *
27 * - autoconfify header file inclusion
28 */
29
30#ifdef MS_WINDOWS
31/* can simulate truncate with Win32 API functions; see file_truncate */
32#define HAVE_FTRUNCATE
33#define WIN32_LEAN_AND_MEAN
34#include <windows.h>
35#endif
36
Antoine Pitrou19690592009-06-12 20:14:08 +000037#if BUFSIZ < (8*1024)
38#define SMALLCHUNK (8*1024)
39#elif (BUFSIZ >= (2 << 25))
40#error "unreasonable BUFSIZ > 64MB defined"
41#else
42#define SMALLCHUNK BUFSIZ
43#endif
44
45#if SIZEOF_INT < 4
46#define BIGCHUNK (512 * 32)
47#else
48#define BIGCHUNK (512 * 1024)
49#endif
50
Christian Heimes7f39c9f2008-01-25 12:18:43 +000051typedef struct {
Antoine Pitroub26dc462010-05-05 16:27:30 +000052 PyObject_HEAD
53 int fd;
54 unsigned int readable : 1;
55 unsigned int writable : 1;
56 signed int seekable : 2; /* -1 means unknown */
57 unsigned int closefd : 1;
58 PyObject *weakreflist;
59 PyObject *dict;
Antoine Pitrou19690592009-06-12 20:14:08 +000060} fileio;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000061
62PyTypeObject PyFileIO_Type;
63
64#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
65
Antoine Pitrou19690592009-06-12 20:14:08 +000066int
67_PyFileIO_closed(PyObject *self)
68{
Antoine Pitroub26dc462010-05-05 16:27:30 +000069 return ((fileio *)self)->fd < 0;
Antoine Pitrou19690592009-06-12 20:14:08 +000070}
71
Antoine Pitroue741cc62009-01-21 00:45:36 +000072static PyObject *
73portable_lseek(int fd, PyObject *posobj, int whence);
74
Antoine Pitrou19690592009-06-12 20:14:08 +000075static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
76
77/* Returns 0 on success, -1 with exception set on failure. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +000078static int
Antoine Pitrou19690592009-06-12 20:14:08 +000079internal_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +000080{
Antoine Pitroub26dc462010-05-05 16:27:30 +000081 int err = 0;
82 int save_errno = 0;
83 if (self->fd >= 0) {
84 int fd = self->fd;
85 self->fd = -1;
86 /* fd is accessible and someone else may have closed it */
87 if (_PyVerify_fd(fd)) {
88 Py_BEGIN_ALLOW_THREADS
89 err = close(fd);
90 if (err < 0)
91 save_errno = errno;
92 Py_END_ALLOW_THREADS
93 } else {
94 save_errno = errno;
95 err = -1;
96 }
97 }
98 if (err < 0) {
99 errno = save_errno;
100 PyErr_SetFromErrno(PyExc_IOError);
101 return -1;
102 }
103 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000104}
105
106static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000107fileio_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000108{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000109 if (!self->closefd) {
110 self->fd = -1;
111 Py_RETURN_NONE;
112 }
113 errno = internal_close(self);
114 if (errno < 0)
115 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000116
Antoine Pitroub26dc462010-05-05 16:27:30 +0000117 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
118 "close", "O", self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000119}
120
121static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000122fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000123{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000124 fileio *self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000125
Antoine Pitroub26dc462010-05-05 16:27:30 +0000126 assert(type != NULL && type->tp_alloc != NULL);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000127
Antoine Pitroub26dc462010-05-05 16:27:30 +0000128 self = (fileio *) type->tp_alloc(type, 0);
129 if (self != NULL) {
130 self->fd = -1;
131 self->readable = 0;
132 self->writable = 0;
133 self->seekable = -1;
134 self->closefd = 1;
135 self->weakreflist = NULL;
136 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000137
Antoine Pitroub26dc462010-05-05 16:27:30 +0000138 return (PyObject *) self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000139}
140
141/* On Unix, open will succeed for directories.
142 In Python, there should be no file objects referring to
143 directories, so we need a check. */
144
145static int
Antoine Pitrou19690592009-06-12 20:14:08 +0000146dircheck(fileio* self, const char *name)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000147{
148#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000149 struct stat buf;
150 if (self->fd < 0)
151 return 0;
152 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
153 char *msg = strerror(EISDIR);
154 PyObject *exc;
155 if (internal_close(self))
156 return -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000157
Antoine Pitroub26dc462010-05-05 16:27:30 +0000158 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
159 EISDIR, msg, name);
160 PyErr_SetObject(PyExc_IOError, exc);
161 Py_XDECREF(exc);
162 return -1;
163 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000164#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000165 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000166}
167
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000168static int
169check_fd(int fd)
170{
171#if defined(HAVE_FSTAT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000172 struct stat buf;
173 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
174 PyObject *exc;
175 char *msg = strerror(EBADF);
176 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
177 EBADF, msg);
178 PyErr_SetObject(PyExc_OSError, exc);
179 Py_XDECREF(exc);
180 return -1;
181 }
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000182#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000183 return 0;
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000184}
185
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000186
187static int
188fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
189{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000190 fileio *self = (fileio *) oself;
191 static char *kwlist[] = {"file", "mode", "closefd", NULL};
192 const char *name = NULL;
193 PyObject *nameobj, *stringobj = NULL;
194 char *mode = "r";
195 char *s;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000196#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000197 Py_UNICODE *widename = NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000198#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000199 int ret = 0;
200 int rwa = 0, plus = 0, append = 0;
201 int flags = 0;
202 int fd = -1;
203 int closefd = 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000204
Antoine Pitroub26dc462010-05-05 16:27:30 +0000205 assert(PyFileIO_Check(oself));
206 if (self->fd >= 0) {
207 /* Have to close the existing file first. */
208 if (internal_close(self) < 0)
209 return -1;
210 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000211
Antoine Pitroub26dc462010-05-05 16:27:30 +0000212 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
213 kwlist, &nameobj, &mode, &closefd))
214 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000215
Antoine Pitroub26dc462010-05-05 16:27:30 +0000216 if (PyFloat_Check(nameobj)) {
217 PyErr_SetString(PyExc_TypeError,
218 "integer argument expected, got float");
219 return -1;
220 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000221
Antoine Pitroub26dc462010-05-05 16:27:30 +0000222 fd = PyLong_AsLong(nameobj);
223 if (fd < 0) {
224 if (!PyErr_Occurred()) {
225 PyErr_SetString(PyExc_ValueError,
226 "Negative filedescriptor");
227 return -1;
228 }
229 PyErr_Clear();
230 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000231
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000232#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000233 if (PyUnicode_Check(nameobj))
234 widename = PyUnicode_AS_UNICODE(nameobj);
235 if (widename == NULL)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000236#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000237 if (fd < 0)
238 {
239 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
240 Py_ssize_t namelen;
241 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
242 return -1;
243 }
244 else {
245 PyObject *u = PyUnicode_FromObject(nameobj);
Antoine Pitrou19690592009-06-12 20:14:08 +0000246
Antoine Pitroub26dc462010-05-05 16:27:30 +0000247 if (u == NULL)
248 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000249
Antoine Pitroub26dc462010-05-05 16:27:30 +0000250 stringobj = PyUnicode_AsEncodedString(
251 u, Py_FileSystemDefaultEncoding, NULL);
252 Py_DECREF(u);
253 if (stringobj == NULL)
254 return -1;
255 if (!PyBytes_Check(stringobj)) {
256 PyErr_SetString(PyExc_TypeError,
257 "encoder failed to return bytes");
258 goto error;
259 }
260 name = PyBytes_AS_STRING(stringobj);
261 }
262 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000263
Antoine Pitroub26dc462010-05-05 16:27:30 +0000264 s = mode;
265 while (*s) {
266 switch (*s++) {
267 case 'r':
268 if (rwa) {
269 bad_mode:
270 PyErr_SetString(PyExc_ValueError,
271 "Must have exactly one of read/write/append mode");
272 goto error;
273 }
274 rwa = 1;
275 self->readable = 1;
276 break;
277 case 'w':
278 if (rwa)
279 goto bad_mode;
280 rwa = 1;
281 self->writable = 1;
282 flags |= O_CREAT | O_TRUNC;
283 break;
284 case 'a':
285 if (rwa)
286 goto bad_mode;
287 rwa = 1;
288 self->writable = 1;
289 flags |= O_CREAT;
290 append = 1;
291 break;
292 case 'b':
293 break;
294 case '+':
295 if (plus)
296 goto bad_mode;
297 self->readable = self->writable = 1;
298 plus = 1;
299 break;
300 default:
301 PyErr_Format(PyExc_ValueError,
302 "invalid mode: %.200s", mode);
303 goto error;
304 }
305 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000306
Antoine Pitroub26dc462010-05-05 16:27:30 +0000307 if (!rwa)
308 goto bad_mode;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000309
Antoine Pitroub26dc462010-05-05 16:27:30 +0000310 if (self->readable && self->writable)
311 flags |= O_RDWR;
312 else if (self->readable)
313 flags |= O_RDONLY;
314 else
315 flags |= O_WRONLY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000316
317#ifdef O_BINARY
Antoine Pitroub26dc462010-05-05 16:27:30 +0000318 flags |= O_BINARY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000319#endif
320
321#ifdef O_APPEND
Antoine Pitroub26dc462010-05-05 16:27:30 +0000322 if (append)
323 flags |= O_APPEND;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000324#endif
325
Antoine Pitroub26dc462010-05-05 16:27:30 +0000326 if (fd >= 0) {
327 if (check_fd(fd))
328 goto error;
329 self->fd = fd;
330 self->closefd = closefd;
331 }
332 else {
333 self->closefd = 1;
334 if (!closefd) {
335 PyErr_SetString(PyExc_ValueError,
336 "Cannot use closefd=False with file name");
337 goto error;
338 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000339
Antoine Pitroub26dc462010-05-05 16:27:30 +0000340 Py_BEGIN_ALLOW_THREADS
341 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000342#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000343 if (widename != NULL)
344 self->fd = _wopen(widename, flags, 0666);
345 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000346#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000347 self->fd = open(name, flags, 0666);
348 Py_END_ALLOW_THREADS
349 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000350#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000351 if (widename != NULL)
352 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
353 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000354#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000355 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
356 goto error;
357 }
358 if(dircheck(self, name) < 0)
359 goto error;
360 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000361
Antoine Pitroub26dc462010-05-05 16:27:30 +0000362 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
363 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000364
Antoine Pitroub26dc462010-05-05 16:27:30 +0000365 if (append) {
366 /* For consistent behaviour, we explicitly seek to the
367 end of file (otherwise, it might be done only on the
368 first write()). */
369 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou594a0462010-10-31 13:05:48 +0000370 if (pos == NULL) {
371 if (closefd) {
372 close(self->fd);
373 self->fd = -1;
374 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000375 goto error;
Antoine Pitrou594a0462010-10-31 13:05:48 +0000376 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000377 Py_DECREF(pos);
378 }
Antoine Pitroue741cc62009-01-21 00:45:36 +0000379
Antoine Pitroub26dc462010-05-05 16:27:30 +0000380 goto done;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000381
382 error:
Antoine Pitroub26dc462010-05-05 16:27:30 +0000383 ret = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000384
385 done:
Antoine Pitroub26dc462010-05-05 16:27:30 +0000386 Py_CLEAR(stringobj);
387 return ret;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000388}
389
Antoine Pitrou19690592009-06-12 20:14:08 +0000390static int
391fileio_traverse(fileio *self, visitproc visit, void *arg)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000392{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000393 Py_VISIT(self->dict);
394 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000395}
396
397static int
398fileio_clear(fileio *self)
399{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000400 Py_CLEAR(self->dict);
401 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000402}
403
404static void
405fileio_dealloc(fileio *self)
406{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000407 if (_PyIOBase_finalize((PyObject *) self) < 0)
408 return;
409 _PyObject_GC_UNTRACK(self);
410 if (self->weakreflist != NULL)
411 PyObject_ClearWeakRefs((PyObject *) self);
412 Py_CLEAR(self->dict);
413 Py_TYPE(self)->tp_free((PyObject *)self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000414}
415
416static PyObject *
417err_closed(void)
418{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000419 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
420 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000421}
422
423static PyObject *
424err_mode(char *action)
425{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000426 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
427 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000428}
429
430static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000431fileio_fileno(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000432{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000433 if (self->fd < 0)
434 return err_closed();
435 return PyInt_FromLong((long) self->fd);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000436}
437
438static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000439fileio_readable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000440{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000441 if (self->fd < 0)
442 return err_closed();
443 return PyBool_FromLong((long) self->readable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000444}
445
446static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000447fileio_writable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000448{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000449 if (self->fd < 0)
450 return err_closed();
451 return PyBool_FromLong((long) self->writable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000452}
453
454static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000455fileio_seekable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000456{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000457 if (self->fd < 0)
458 return err_closed();
459 if (self->seekable < 0) {
460 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
461 if (pos == NULL) {
462 PyErr_Clear();
463 self->seekable = 0;
464 } else {
465 Py_DECREF(pos);
466 self->seekable = 1;
467 }
468 }
469 return PyBool_FromLong((long) self->seekable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000470}
471
472static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000473fileio_readinto(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000474{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000475 Py_buffer pbuf;
476 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000477
Antoine Pitroub26dc462010-05-05 16:27:30 +0000478 if (self->fd < 0)
479 return err_closed();
480 if (!self->readable)
481 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000482
Antoine Pitroub26dc462010-05-05 16:27:30 +0000483 if (!PyArg_ParseTuple(args, "w*", &pbuf))
484 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000485
Antoine Pitroub26dc462010-05-05 16:27:30 +0000486 if (_PyVerify_fd(self->fd)) {
487 Py_BEGIN_ALLOW_THREADS
488 errno = 0;
489 n = read(self->fd, pbuf.buf, pbuf.len);
490 Py_END_ALLOW_THREADS
491 } else
492 n = -1;
493 PyBuffer_Release(&pbuf);
494 if (n < 0) {
495 if (errno == EAGAIN)
496 Py_RETURN_NONE;
497 PyErr_SetFromErrno(PyExc_IOError);
498 return NULL;
499 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000500
Antoine Pitroub26dc462010-05-05 16:27:30 +0000501 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000502}
503
Antoine Pitrou19690592009-06-12 20:14:08 +0000504static size_t
505new_buffersize(fileio *self, size_t currentsize)
506{
507#ifdef HAVE_FSTAT
Antoine Pitroub26dc462010-05-05 16:27:30 +0000508 off_t pos, end;
509 struct stat st;
510 if (fstat(self->fd, &st) == 0) {
511 end = st.st_size;
512 pos = lseek(self->fd, 0L, SEEK_CUR);
513 /* Files claiming a size smaller than SMALLCHUNK may
514 actually be streaming pseudo-files. In this case, we
515 apply the more aggressive algorithm below.
516 */
517 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
518 /* Add 1 so if the file were to grow we'd notice. */
519 return currentsize + end - pos + 1;
520 }
521 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000522#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000523 if (currentsize > SMALLCHUNK) {
524 /* Keep doubling until we reach BIGCHUNK;
525 then keep adding BIGCHUNK. */
526 if (currentsize <= BIGCHUNK)
527 return currentsize + currentsize;
528 else
529 return currentsize + BIGCHUNK;
530 }
531 return currentsize + SMALLCHUNK;
Antoine Pitrou19690592009-06-12 20:14:08 +0000532}
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000533
534static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000535fileio_readall(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000536{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000537 PyObject *result;
538 Py_ssize_t total = 0;
539 int n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000540
Antoine Pitroub26dc462010-05-05 16:27:30 +0000541 if (!_PyVerify_fd(self->fd))
542 return PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou19690592009-06-12 20:14:08 +0000543
Antoine Pitroub26dc462010-05-05 16:27:30 +0000544 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
545 if (result == NULL)
546 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000547
Antoine Pitroub26dc462010-05-05 16:27:30 +0000548 while (1) {
549 size_t newsize = new_buffersize(self, total);
550 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
551 PyErr_SetString(PyExc_OverflowError,
552 "unbounded read returned more bytes "
553 "than a Python string can hold ");
554 Py_DECREF(result);
555 return NULL;
556 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000557
Antoine Pitroub26dc462010-05-05 16:27:30 +0000558 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
559 if (_PyBytes_Resize(&result, newsize) < 0) {
560 if (total == 0) {
561 Py_DECREF(result);
562 return NULL;
563 }
564 PyErr_Clear();
565 break;
566 }
567 }
568 Py_BEGIN_ALLOW_THREADS
569 errno = 0;
570 n = read(self->fd,
571 PyBytes_AS_STRING(result) + total,
572 newsize - total);
573 Py_END_ALLOW_THREADS
574 if (n == 0)
575 break;
576 if (n < 0) {
577 if (total > 0)
578 break;
579 if (errno == EAGAIN) {
580 Py_DECREF(result);
581 Py_RETURN_NONE;
582 }
583 Py_DECREF(result);
584 PyErr_SetFromErrno(PyExc_IOError);
585 return NULL;
586 }
587 total += n;
588 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000589
Antoine Pitroub26dc462010-05-05 16:27:30 +0000590 if (PyBytes_GET_SIZE(result) > total) {
591 if (_PyBytes_Resize(&result, total) < 0) {
592 /* This should never happen, but just in case */
593 Py_DECREF(result);
594 return NULL;
595 }
596 }
597 return result;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000598}
599
600static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000601fileio_read(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000602{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000603 char *ptr;
604 Py_ssize_t n;
605 Py_ssize_t size = -1;
606 PyObject *bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000607
Antoine Pitroub26dc462010-05-05 16:27:30 +0000608 if (self->fd < 0)
609 return err_closed();
610 if (!self->readable)
611 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000612
Antoine Pitroub26dc462010-05-05 16:27:30 +0000613 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
614 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000615
Antoine Pitroub26dc462010-05-05 16:27:30 +0000616 if (size < 0) {
617 return fileio_readall(self);
618 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000619
Antoine Pitroub26dc462010-05-05 16:27:30 +0000620 bytes = PyBytes_FromStringAndSize(NULL, size);
621 if (bytes == NULL)
622 return NULL;
623 ptr = PyBytes_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000624
Antoine Pitroub26dc462010-05-05 16:27:30 +0000625 if (_PyVerify_fd(self->fd)) {
626 Py_BEGIN_ALLOW_THREADS
627 errno = 0;
628 n = read(self->fd, ptr, size);
629 Py_END_ALLOW_THREADS
630 } else
631 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000632
Antoine Pitroub26dc462010-05-05 16:27:30 +0000633 if (n < 0) {
634 Py_DECREF(bytes);
635 if (errno == EAGAIN)
636 Py_RETURN_NONE;
637 PyErr_SetFromErrno(PyExc_IOError);
638 return NULL;
639 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000640
Antoine Pitroub26dc462010-05-05 16:27:30 +0000641 if (n != size) {
642 if (_PyBytes_Resize(&bytes, n) < 0) {
643 Py_DECREF(bytes);
644 return NULL;
645 }
646 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000647
Antoine Pitroub26dc462010-05-05 16:27:30 +0000648 return (PyObject *) bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000649}
650
651static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000652fileio_write(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000653{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000654 Py_buffer pbuf;
655 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000656
Antoine Pitroub26dc462010-05-05 16:27:30 +0000657 if (self->fd < 0)
658 return err_closed();
659 if (!self->writable)
660 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000661
Antoine Pitroub26dc462010-05-05 16:27:30 +0000662 if (!PyArg_ParseTuple(args, "s*", &pbuf))
663 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000664
Antoine Pitroub26dc462010-05-05 16:27:30 +0000665 if (_PyVerify_fd(self->fd)) {
666 Py_BEGIN_ALLOW_THREADS
667 errno = 0;
668 n = write(self->fd, pbuf.buf, pbuf.len);
669 Py_END_ALLOW_THREADS
670 } else
671 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000672
Antoine Pitroub26dc462010-05-05 16:27:30 +0000673 PyBuffer_Release(&pbuf);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000674
Antoine Pitroub26dc462010-05-05 16:27:30 +0000675 if (n < 0) {
676 if (errno == EAGAIN)
677 Py_RETURN_NONE;
678 PyErr_SetFromErrno(PyExc_IOError);
679 return NULL;
680 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000681
Antoine Pitroub26dc462010-05-05 16:27:30 +0000682 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000683}
684
685/* XXX Windows support below is likely incomplete */
686
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000687/* Cribbed from posix_lseek() */
688static PyObject *
689portable_lseek(int fd, PyObject *posobj, int whence)
690{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000691 Py_off_t pos, res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000692
693#ifdef SEEK_SET
Antoine Pitroub26dc462010-05-05 16:27:30 +0000694 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
695 switch (whence) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000696#if SEEK_SET != 0
Antoine Pitroub26dc462010-05-05 16:27:30 +0000697 case 0: whence = SEEK_SET; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000698#endif
699#if SEEK_CUR != 1
Antoine Pitroub26dc462010-05-05 16:27:30 +0000700 case 1: whence = SEEK_CUR; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000701#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000702#if SEEK_END != 2
Antoine Pitroub26dc462010-05-05 16:27:30 +0000703 case 2: whence = SEEK_END; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000704#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000705 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000706#endif /* SEEK_SET */
707
Antoine Pitroub26dc462010-05-05 16:27:30 +0000708 if (posobj == NULL)
709 pos = 0;
710 else {
711 if(PyFloat_Check(posobj)) {
712 PyErr_SetString(PyExc_TypeError, "an integer is required");
713 return NULL;
714 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000715#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000716 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000717#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000718 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000719#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000720 if (PyErr_Occurred())
721 return NULL;
722 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000723
Antoine Pitroub26dc462010-05-05 16:27:30 +0000724 if (_PyVerify_fd(fd)) {
725 Py_BEGIN_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000726#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000727 res = _lseeki64(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000728#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000729 res = lseek(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000730#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000731 Py_END_ALLOW_THREADS
732 } else
733 res = -1;
734 if (res < 0)
735 return PyErr_SetFromErrno(PyExc_IOError);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000736
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000737#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000738 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000739#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000740 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000741#endif
742}
743
744static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000745fileio_seek(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000746{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000747 PyObject *posobj;
748 int whence = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000749
Antoine Pitroub26dc462010-05-05 16:27:30 +0000750 if (self->fd < 0)
751 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000752
Antoine Pitroub26dc462010-05-05 16:27:30 +0000753 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
754 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000755
Antoine Pitroub26dc462010-05-05 16:27:30 +0000756 return portable_lseek(self->fd, posobj, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000757}
758
759static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000760fileio_tell(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000761{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000762 if (self->fd < 0)
763 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000764
Antoine Pitroub26dc462010-05-05 16:27:30 +0000765 return portable_lseek(self->fd, NULL, 1);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000766}
767
768#ifdef HAVE_FTRUNCATE
769static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000770fileio_truncate(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000771{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000772 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000773#ifndef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000774 Py_off_t pos;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000775#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000776 int ret;
777 int fd;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000778
Antoine Pitroub26dc462010-05-05 16:27:30 +0000779 fd = self->fd;
780 if (fd < 0)
781 return err_closed();
782 if (!self->writable)
783 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000784
Antoine Pitroub26dc462010-05-05 16:27:30 +0000785 if (!PyArg_ParseTuple(args, "|O", &posobj))
786 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000787
Antoine Pitroub26dc462010-05-05 16:27:30 +0000788 if (posobj == Py_None || posobj == NULL) {
789 /* Get the current position. */
790 posobj = portable_lseek(fd, NULL, 1);
791 if (posobj == NULL)
792 return NULL;
793 }
794 else {
795 Py_INCREF(posobj);
796 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000797
798#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000799 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
800 so don't even try using it. */
801 {
802 PyObject *oldposobj, *tempposobj;
803 HANDLE hFile;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000804
Antoine Pitroub26dc462010-05-05 16:27:30 +0000805 /* we save the file pointer position */
806 oldposobj = portable_lseek(fd, NULL, 1);
807 if (oldposobj == NULL) {
808 Py_DECREF(posobj);
809 return NULL;
810 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000811
Antoine Pitroub26dc462010-05-05 16:27:30 +0000812 /* we then move to the truncation position */
813 tempposobj = portable_lseek(fd, posobj, 0);
814 if (tempposobj == NULL) {
815 Py_DECREF(oldposobj);
816 Py_DECREF(posobj);
817 return NULL;
818 }
819 Py_DECREF(tempposobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000820
Antoine Pitroub26dc462010-05-05 16:27:30 +0000821 /* Truncate. Note that this may grow the file! */
822 Py_BEGIN_ALLOW_THREADS
823 errno = 0;
824 hFile = (HANDLE)_get_osfhandle(fd);
825 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
826 if (ret == 0) {
827 ret = SetEndOfFile(hFile) == 0;
828 if (ret)
829 errno = EACCES;
830 }
831 Py_END_ALLOW_THREADS
832
833 /* we restore the file pointer position in any case */
834 tempposobj = portable_lseek(fd, oldposobj, 0);
835 Py_DECREF(oldposobj);
836 if (tempposobj == NULL) {
837 Py_DECREF(posobj);
838 return NULL;
839 }
840 Py_DECREF(tempposobj);
841 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000842#else
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000843
844#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000845 pos = PyLong_AsLongLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000846#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000847 pos = PyLong_AsLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000848#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000849 if (PyErr_Occurred()){
850 Py_DECREF(posobj);
851 return NULL;
852 }
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000853
Antoine Pitroub26dc462010-05-05 16:27:30 +0000854 Py_BEGIN_ALLOW_THREADS
855 errno = 0;
856 ret = ftruncate(fd, pos);
857 Py_END_ALLOW_THREADS
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000858
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000859#endif /* !MS_WINDOWS */
860
Antoine Pitroub26dc462010-05-05 16:27:30 +0000861 if (ret != 0) {
862 Py_DECREF(posobj);
863 PyErr_SetFromErrno(PyExc_IOError);
864 return NULL;
865 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000866
Antoine Pitroub26dc462010-05-05 16:27:30 +0000867 return posobj;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000868}
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000869#endif /* HAVE_FTRUNCATE */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000870
871static char *
Antoine Pitrou19690592009-06-12 20:14:08 +0000872mode_string(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000873{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000874 if (self->readable) {
875 if (self->writable)
876 return "rb+";
877 else
878 return "rb";
879 }
880 else
881 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000882}
883
884static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000885fileio_repr(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000886{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000887 PyObject *nameobj, *res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000888
Antoine Pitroub26dc462010-05-05 16:27:30 +0000889 if (self->fd < 0)
890 return PyString_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou19690592009-06-12 20:14:08 +0000891
Antoine Pitroub26dc462010-05-05 16:27:30 +0000892 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
893 if (nameobj == NULL) {
894 if (PyErr_ExceptionMatches(PyExc_AttributeError))
895 PyErr_Clear();
896 else
897 return NULL;
898 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
899 self->fd, mode_string(self));
900 }
901 else {
902 PyObject *repr = PyObject_Repr(nameobj);
903 Py_DECREF(nameobj);
904 if (repr == NULL)
905 return NULL;
906 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
907 PyString_AS_STRING(repr),
908 mode_string(self));
909 Py_DECREF(repr);
910 }
911 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000912}
913
914static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000915fileio_isatty(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000916{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000917 long res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000918
Antoine Pitroub26dc462010-05-05 16:27:30 +0000919 if (self->fd < 0)
920 return err_closed();
921 Py_BEGIN_ALLOW_THREADS
922 res = isatty(self->fd);
923 Py_END_ALLOW_THREADS
924 return PyBool_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000925}
926
927
928PyDoc_STRVAR(fileio_doc,
929"file(name: str[, mode: str]) -> file IO object\n"
930"\n"
931"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitroub26dc462010-05-05 16:27:30 +0000932"writing or appending. The file will be created if it doesn't exist\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000933"when opened for writing or appending; it will be truncated when\n"
934"opened for writing. Add a '+' to the mode to allow simultaneous\n"
935"reading and writing.");
936
937PyDoc_STRVAR(read_doc,
938"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
939"\n"
940"Only makes one system call, so less data may be returned than requested\n"
941"In non-blocking mode, returns None if no data is available.\n"
942"On end-of-file, returns ''.");
943
944PyDoc_STRVAR(readall_doc,
945"readall() -> bytes. read all data from the file, returned as bytes.\n"
946"\n"
947"In non-blocking mode, returns as much as is immediately available,\n"
948"or None if no data is available. On end-of-file, returns ''.");
949
950PyDoc_STRVAR(write_doc,
951"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
952"\n"
953"Only makes one system call, so not all of the data may be written.\n"
954"The number of bytes actually written is returned.");
955
956PyDoc_STRVAR(fileno_doc,
957"fileno() -> int. \"file descriptor\".\n"
958"\n"
959"This is needed for lower-level file interfaces, such the fcntl module.");
960
961PyDoc_STRVAR(seek_doc,
962"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
963"\n"
964"Argument offset is a byte count. Optional argument whence defaults to\n"
965"0 (offset from start of file, offset should be >= 0); other values are 1\n"
966"(move relative to current position, positive or negative), and 2 (move\n"
967"relative to end of file, usually negative, although many platforms allow\n"
968"seeking beyond the end of a file)."
969"\n"
970"Note that not all file objects are seekable.");
971
972#ifdef HAVE_FTRUNCATE
973PyDoc_STRVAR(truncate_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +0000974"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000975"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000976"Size defaults to the current file position, as returned by tell()."
977"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000978#endif
979
980PyDoc_STRVAR(tell_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +0000981"tell() -> int. Current file position");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000982
983PyDoc_STRVAR(readinto_doc,
Antoine Pitrou19690592009-06-12 20:14:08 +0000984"readinto() -> Same as RawIOBase.readinto().");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000985
986PyDoc_STRVAR(close_doc,
987"close() -> None. Close the file.\n"
988"\n"
989"A closed file cannot be used for further I/O operations. close() may be\n"
990"called more than once without error. Changes the fileno to -1.");
991
992PyDoc_STRVAR(isatty_doc,
993"isatty() -> bool. True if the file is connected to a tty device.");
994
995PyDoc_STRVAR(seekable_doc,
996"seekable() -> bool. True if file supports random-access.");
997
998PyDoc_STRVAR(readable_doc,
999"readable() -> bool. True if file was opened in a read mode.");
1000
1001PyDoc_STRVAR(writable_doc,
1002"writable() -> bool. True if file was opened in a write mode.");
1003
1004static PyMethodDef fileio_methods[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001005 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1006 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1007 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1008 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1009 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1010 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001011#ifdef HAVE_FTRUNCATE
Antoine Pitroub26dc462010-05-05 16:27:30 +00001012 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001013#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +00001014 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1015 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1016 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1017 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1018 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1019 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1020 {NULL, NULL} /* sentinel */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001021};
1022
1023/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1024
1025static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001026get_closed(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001027{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001028 return PyBool_FromLong((long)(self->fd < 0));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001029}
1030
1031static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001032get_closefd(fileio *self, void *closure)
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001033{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001034 return PyBool_FromLong((long)(self->closefd));
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001035}
1036
1037static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001038get_mode(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001039{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001040 return PyUnicode_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001041}
1042
1043static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001044 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1045 {"closefd", (getter)get_closefd, NULL,
1046 "True if the file descriptor will be closed"},
1047 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1048 {NULL},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001049};
1050
1051PyTypeObject PyFileIO_Type = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001052 PyVarObject_HEAD_INIT(NULL, 0)
1053 "_io.FileIO",
1054 sizeof(fileio),
1055 0,
1056 (destructor)fileio_dealloc, /* tp_dealloc */
1057 0, /* tp_print */
1058 0, /* tp_getattr */
1059 0, /* tp_setattr */
1060 0, /* tp_reserved */
1061 (reprfunc)fileio_repr, /* tp_repr */
1062 0, /* tp_as_number */
1063 0, /* tp_as_sequence */
1064 0, /* tp_as_mapping */
1065 0, /* tp_hash */
1066 0, /* tp_call */
1067 0, /* tp_str */
1068 PyObject_GenericGetAttr, /* tp_getattro */
1069 0, /* tp_setattro */
1070 0, /* tp_as_buffer */
1071 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1072 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1073 fileio_doc, /* tp_doc */
1074 (traverseproc)fileio_traverse, /* tp_traverse */
1075 (inquiry)fileio_clear, /* tp_clear */
1076 0, /* tp_richcompare */
1077 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1078 0, /* tp_iter */
1079 0, /* tp_iternext */
1080 fileio_methods, /* tp_methods */
1081 0, /* tp_members */
1082 fileio_getsetlist, /* tp_getset */
1083 0, /* tp_base */
1084 0, /* tp_dict */
1085 0, /* tp_descr_get */
1086 0, /* tp_descr_set */
1087 offsetof(fileio, dict), /* tp_dictoffset */
1088 fileio_init, /* tp_init */
1089 PyType_GenericAlloc, /* tp_alloc */
1090 fileio_new, /* tp_new */
1091 PyObject_GC_Del, /* tp_free */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001092};