/Modules/_fileio.c

http://unladen-swallow.googlecode.com/ · C · 935 lines · 779 code · 121 blank · 35 comment · 144 complexity · 51125bf68e0c7d6e9395081a92aa23be MD5 · raw file

  1. /* Author: Daniel Stutzbach */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <stddef.h> /* For offsetof */
  8. /*
  9. * Known likely problems:
  10. *
  11. * - Files larger then 2**32-1
  12. * - Files with unicode filenames
  13. * - Passing numbers greater than 2**32-1 when an integer is expected
  14. * - Making it work on Windows and other oddball platforms
  15. *
  16. * To Do:
  17. *
  18. * - autoconfify header file inclusion
  19. */
  20. #ifdef MS_WINDOWS
  21. /* can simulate truncate with Win32 API functions; see file_truncate */
  22. #define HAVE_FTRUNCATE
  23. #define WIN32_LEAN_AND_MEAN
  24. #include <windows.h>
  25. #endif
  26. typedef struct {
  27. PyObject_HEAD
  28. int fd;
  29. unsigned int readable : 1;
  30. unsigned int writable : 1;
  31. signed int seekable : 2; /* -1 means unknown */
  32. signed int closefd : 1;
  33. PyObject *weakreflist;
  34. } PyFileIOObject;
  35. PyTypeObject PyFileIO_Type;
  36. #define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
  37. static PyObject *
  38. portable_lseek(int fd, PyObject *posobj, int whence);
  39. /* Returns 0 on success, errno (which is < 0) on failure. */
  40. static int
  41. internal_close(PyFileIOObject *self)
  42. {
  43. int save_errno = 0;
  44. if (self->fd >= 0) {
  45. int fd = self->fd;
  46. self->fd = -1;
  47. Py_BEGIN_ALLOW_THREADS
  48. if (close(fd) < 0)
  49. save_errno = errno;
  50. Py_END_ALLOW_THREADS
  51. }
  52. return save_errno;
  53. }
  54. static PyObject *
  55. fileio_close(PyFileIOObject *self)
  56. {
  57. if (!self->closefd) {
  58. self->fd = -1;
  59. Py_RETURN_NONE;
  60. }
  61. errno = internal_close(self);
  62. if (errno < 0) {
  63. PyErr_SetFromErrno(PyExc_IOError);
  64. return NULL;
  65. }
  66. Py_RETURN_NONE;
  67. }
  68. static PyObject *
  69. fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews)
  70. {
  71. PyFileIOObject *self;
  72. assert(type != NULL && type->tp_alloc != NULL);
  73. self = (PyFileIOObject *) type->tp_alloc(type, 0);
  74. if (self != NULL) {
  75. self->fd = -1;
  76. self->readable = 0;
  77. self->writable = 0;
  78. self->seekable = -1;
  79. self->closefd = 1;
  80. self->weakreflist = NULL;
  81. }
  82. return (PyObject *) self;
  83. }
  84. /* On Unix, open will succeed for directories.
  85. In Python, there should be no file objects referring to
  86. directories, so we need a check. */
  87. static int
  88. dircheck(PyFileIOObject* self, char *name)
  89. {
  90. #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
  91. struct stat buf;
  92. if (self->fd < 0)
  93. return 0;
  94. if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
  95. char *msg = strerror(EISDIR);
  96. PyObject *exc;
  97. internal_close(self);
  98. exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
  99. EISDIR, msg, name);
  100. PyErr_SetObject(PyExc_IOError, exc);
  101. Py_XDECREF(exc);
  102. return -1;
  103. }
  104. #endif
  105. return 0;
  106. }
  107. static int
  108. check_fd(int fd)
  109. {
  110. #if defined(HAVE_FSTAT)
  111. struct stat buf;
  112. if (fstat(fd, &buf) < 0 && errno == EBADF) {
  113. PyObject *exc;
  114. char *msg = strerror(EBADF);
  115. exc = PyObject_CallFunction(PyExc_OSError, "(is)",
  116. EBADF, msg);
  117. PyErr_SetObject(PyExc_OSError, exc);
  118. Py_XDECREF(exc);
  119. return -1;
  120. }
  121. #endif
  122. return 0;
  123. }
  124. static int
  125. fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
  126. {
  127. PyFileIOObject *self = (PyFileIOObject *) oself;
  128. static char *kwlist[] = {"file", "mode", "closefd", NULL};
  129. char *name = NULL;
  130. char *mode = "r";
  131. char *s;
  132. #ifdef MS_WINDOWS
  133. Py_UNICODE *widename = NULL;
  134. #endif
  135. int ret = 0;
  136. int rwa = 0, plus = 0, append = 0;
  137. int flags = 0;
  138. int fd = -1;
  139. int closefd = 1;
  140. assert(PyFileIO_Check(oself));
  141. if (self->fd >= 0) {
  142. /* Have to close the existing file first. */
  143. if (internal_close(self) < 0)
  144. return -1;
  145. }
  146. if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio",
  147. kwlist, &fd, &mode, &closefd)) {
  148. if (fd < 0) {
  149. PyErr_SetString(PyExc_ValueError,
  150. "Negative filedescriptor");
  151. return -1;
  152. }
  153. if (check_fd(fd))
  154. return -1;
  155. }
  156. else {
  157. PyErr_Clear();
  158. #ifdef Py_WIN_WIDE_FILENAMES
  159. if (GetVersion() < 0x80000000) {
  160. /* On NT, so wide API available */
  161. PyObject *po;
  162. if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio",
  163. kwlist, &po, &mode, &closefd)
  164. ) {
  165. widename = PyUnicode_AS_UNICODE(po);
  166. } else {
  167. /* Drop the argument parsing error as narrow
  168. strings are also valid. */
  169. PyErr_Clear();
  170. }
  171. }
  172. if (widename == NULL)
  173. #endif
  174. {
  175. if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio",
  176. kwlist,
  177. Py_FileSystemDefaultEncoding,
  178. &name, &mode, &closefd))
  179. return -1;
  180. }
  181. }
  182. s = mode;
  183. while (*s) {
  184. switch (*s++) {
  185. case 'r':
  186. if (rwa) {
  187. bad_mode:
  188. PyErr_SetString(PyExc_ValueError,
  189. "Must have exactly one of read/write/append mode");
  190. goto error;
  191. }
  192. rwa = 1;
  193. self->readable = 1;
  194. break;
  195. case 'w':
  196. if (rwa)
  197. goto bad_mode;
  198. rwa = 1;
  199. self->writable = 1;
  200. flags |= O_CREAT | O_TRUNC;
  201. break;
  202. case 'a':
  203. if (rwa)
  204. goto bad_mode;
  205. rwa = 1;
  206. self->writable = 1;
  207. flags |= O_CREAT;
  208. append = 1;
  209. break;
  210. case 'b':
  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. if (!rwa)
  225. goto bad_mode;
  226. if (self->readable && self->writable)
  227. flags |= O_RDWR;
  228. else if (self->readable)
  229. flags |= O_RDONLY;
  230. else
  231. flags |= O_WRONLY;
  232. #ifdef O_BINARY
  233. flags |= O_BINARY;
  234. #endif
  235. #ifdef O_APPEND
  236. if (append)
  237. flags |= O_APPEND;
  238. #endif
  239. if (fd >= 0) {
  240. self->fd = fd;
  241. self->closefd = closefd;
  242. }
  243. else {
  244. self->closefd = 1;
  245. if (!closefd) {
  246. PyErr_SetString(PyExc_ValueError,
  247. "Cannot use closefd=False with file name");
  248. goto error;
  249. }
  250. Py_BEGIN_ALLOW_THREADS
  251. errno = 0;
  252. #ifdef MS_WINDOWS
  253. if (widename != NULL)
  254. self->fd = _wopen(widename, flags, 0666);
  255. else
  256. #endif
  257. self->fd = open(name, flags, 0666);
  258. Py_END_ALLOW_THREADS
  259. if (self->fd < 0) {
  260. #ifdef MS_WINDOWS
  261. if (widename != NULL)
  262. PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
  263. else
  264. #endif
  265. PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
  266. goto error;
  267. }
  268. if(dircheck(self, name) < 0)
  269. goto error;
  270. }
  271. if (append) {
  272. /* For consistent behaviour, we explicitly seek to the
  273. end of file (otherwise, it might be done only on the
  274. first write()). */
  275. PyObject *pos = portable_lseek(self->fd, NULL, 2);
  276. if (pos == NULL)
  277. goto error;
  278. Py_DECREF(pos);
  279. }
  280. goto done;
  281. error:
  282. ret = -1;
  283. done:
  284. PyMem_Free(name);
  285. return ret;
  286. }
  287. static void
  288. fileio_dealloc(PyFileIOObject *self)
  289. {
  290. if (self->weakreflist != NULL)
  291. PyObject_ClearWeakRefs((PyObject *) self);
  292. if (self->fd >= 0 && self->closefd) {
  293. errno = internal_close(self);
  294. if (errno < 0) {
  295. PySys_WriteStderr("close failed: [Errno %d] %s\n",
  296. errno, strerror(errno));
  297. }
  298. }
  299. Py_TYPE(self)->tp_free((PyObject *)self);
  300. }
  301. static PyObject *
  302. err_closed(void)
  303. {
  304. PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
  305. return NULL;
  306. }
  307. static PyObject *
  308. err_mode(char *action)
  309. {
  310. PyErr_Format(PyExc_ValueError, "File not open for %s", action);
  311. return NULL;
  312. }
  313. static PyObject *
  314. fileio_fileno(PyFileIOObject *self)
  315. {
  316. if (self->fd < 0)
  317. return err_closed();
  318. return PyInt_FromLong((long) self->fd);
  319. }
  320. static PyObject *
  321. fileio_readable(PyFileIOObject *self)
  322. {
  323. if (self->fd < 0)
  324. return err_closed();
  325. return PyBool_FromLong((long) self->readable);
  326. }
  327. static PyObject *
  328. fileio_writable(PyFileIOObject *self)
  329. {
  330. if (self->fd < 0)
  331. return err_closed();
  332. return PyBool_FromLong((long) self->writable);
  333. }
  334. static PyObject *
  335. fileio_seekable(PyFileIOObject *self)
  336. {
  337. if (self->fd < 0)
  338. return err_closed();
  339. if (self->seekable < 0) {
  340. int ret;
  341. Py_BEGIN_ALLOW_THREADS
  342. ret = lseek(self->fd, 0, SEEK_CUR);
  343. Py_END_ALLOW_THREADS
  344. if (ret < 0)
  345. self->seekable = 0;
  346. else
  347. self->seekable = 1;
  348. }
  349. return PyBool_FromLong((long) self->seekable);
  350. }
  351. static PyObject *
  352. fileio_readinto(PyFileIOObject *self, PyObject *args)
  353. {
  354. Py_buffer pbuf;
  355. Py_ssize_t n;
  356. if (self->fd < 0)
  357. return err_closed();
  358. if (!self->readable)
  359. return err_mode("reading");
  360. if (!PyArg_ParseTuple(args, "w*", &pbuf))
  361. return NULL;
  362. Py_BEGIN_ALLOW_THREADS
  363. errno = 0;
  364. n = read(self->fd, pbuf.buf, pbuf.len);
  365. Py_END_ALLOW_THREADS
  366. PyBuffer_Release(&pbuf);
  367. if (n < 0) {
  368. if (errno == EAGAIN)
  369. Py_RETURN_NONE;
  370. PyErr_SetFromErrno(PyExc_IOError);
  371. return NULL;
  372. }
  373. return PyLong_FromSsize_t(n);
  374. }
  375. #define DEFAULT_BUFFER_SIZE (8*1024)
  376. static PyObject *
  377. fileio_readall(PyFileIOObject *self)
  378. {
  379. PyObject *result;
  380. Py_ssize_t total = 0;
  381. int n;
  382. result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
  383. if (result == NULL)
  384. return NULL;
  385. while (1) {
  386. Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
  387. if (PyString_GET_SIZE(result) < newsize) {
  388. if (_PyString_Resize(&result, newsize) < 0) {
  389. if (total == 0) {
  390. Py_DECREF(result);
  391. return NULL;
  392. }
  393. PyErr_Clear();
  394. break;
  395. }
  396. }
  397. Py_BEGIN_ALLOW_THREADS
  398. errno = 0;
  399. n = read(self->fd,
  400. PyString_AS_STRING(result) + total,
  401. newsize - total);
  402. Py_END_ALLOW_THREADS
  403. if (n == 0)
  404. break;
  405. if (n < 0) {
  406. if (total > 0)
  407. break;
  408. if (errno == EAGAIN) {
  409. Py_DECREF(result);
  410. Py_RETURN_NONE;
  411. }
  412. Py_DECREF(result);
  413. PyErr_SetFromErrno(PyExc_IOError);
  414. return NULL;
  415. }
  416. total += n;
  417. }
  418. if (PyString_GET_SIZE(result) > total) {
  419. if (_PyString_Resize(&result, total) < 0) {
  420. /* This should never happen, but just in case */
  421. Py_DECREF(result);
  422. return NULL;
  423. }
  424. }
  425. return result;
  426. }
  427. static PyObject *
  428. fileio_read(PyFileIOObject *self, PyObject *args)
  429. {
  430. char *ptr;
  431. Py_ssize_t n;
  432. Py_ssize_t size = -1;
  433. PyObject *bytes;
  434. if (self->fd < 0)
  435. return err_closed();
  436. if (!self->readable)
  437. return err_mode("reading");
  438. if (!PyArg_ParseTuple(args, "|n", &size))
  439. return NULL;
  440. if (size < 0) {
  441. return fileio_readall(self);
  442. }
  443. bytes = PyString_FromStringAndSize(NULL, size);
  444. if (bytes == NULL)
  445. return NULL;
  446. ptr = PyString_AS_STRING(bytes);
  447. Py_BEGIN_ALLOW_THREADS
  448. errno = 0;
  449. n = read(self->fd, ptr, size);
  450. Py_END_ALLOW_THREADS
  451. if (n < 0) {
  452. if (errno == EAGAIN)
  453. Py_RETURN_NONE;
  454. PyErr_SetFromErrno(PyExc_IOError);
  455. return NULL;
  456. }
  457. if (n != size) {
  458. if (_PyString_Resize(&bytes, n) < 0) {
  459. Py_DECREF(bytes);
  460. return NULL;
  461. }
  462. }
  463. return (PyObject *) bytes;
  464. }
  465. static PyObject *
  466. fileio_write(PyFileIOObject *self, PyObject *args)
  467. {
  468. Py_buffer pbuf;
  469. Py_ssize_t n;
  470. if (self->fd < 0)
  471. return err_closed();
  472. if (!self->writable)
  473. return err_mode("writing");
  474. if (!PyArg_ParseTuple(args, "s*", &pbuf))
  475. return NULL;
  476. Py_BEGIN_ALLOW_THREADS
  477. errno = 0;
  478. n = write(self->fd, pbuf.buf, pbuf.len);
  479. Py_END_ALLOW_THREADS
  480. PyBuffer_Release(&pbuf);
  481. if (n < 0) {
  482. if (errno == EAGAIN)
  483. Py_RETURN_NONE;
  484. PyErr_SetFromErrno(PyExc_IOError);
  485. return NULL;
  486. }
  487. return PyLong_FromSsize_t(n);
  488. }
  489. /* XXX Windows support below is likely incomplete */
  490. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  491. typedef PY_LONG_LONG Py_off_t;
  492. #else
  493. typedef off_t Py_off_t;
  494. #endif
  495. /* Cribbed from posix_lseek() */
  496. static PyObject *
  497. portable_lseek(int fd, PyObject *posobj, int whence)
  498. {
  499. Py_off_t pos, res;
  500. #ifdef SEEK_SET
  501. /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
  502. switch (whence) {
  503. #if SEEK_SET != 0
  504. case 0: whence = SEEK_SET; break;
  505. #endif
  506. #if SEEK_CUR != 1
  507. case 1: whence = SEEK_CUR; break;
  508. #endif
  509. #if SEEL_END != 2
  510. case 2: whence = SEEK_END; break;
  511. #endif
  512. }
  513. #endif /* SEEK_SET */
  514. if (posobj == NULL)
  515. pos = 0;
  516. else {
  517. if(PyFloat_Check(posobj)) {
  518. PyErr_SetString(PyExc_TypeError, "an integer is required");
  519. return NULL;
  520. }
  521. #if defined(HAVE_LARGEFILE_SUPPORT)
  522. pos = PyLong_AsLongLong(posobj);
  523. #else
  524. pos = PyLong_AsLong(posobj);
  525. #endif
  526. if (PyErr_Occurred())
  527. return NULL;
  528. }
  529. Py_BEGIN_ALLOW_THREADS
  530. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  531. res = _lseeki64(fd, pos, whence);
  532. #else
  533. res = lseek(fd, pos, whence);
  534. #endif
  535. Py_END_ALLOW_THREADS
  536. if (res < 0)
  537. return PyErr_SetFromErrno(PyExc_IOError);
  538. #if defined(HAVE_LARGEFILE_SUPPORT)
  539. return PyLong_FromLongLong(res);
  540. #else
  541. return PyLong_FromLong(res);
  542. #endif
  543. }
  544. static PyObject *
  545. fileio_seek(PyFileIOObject *self, PyObject *args)
  546. {
  547. PyObject *posobj;
  548. int whence = 0;
  549. if (self->fd < 0)
  550. return err_closed();
  551. if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
  552. return NULL;
  553. return portable_lseek(self->fd, posobj, whence);
  554. }
  555. static PyObject *
  556. fileio_tell(PyFileIOObject *self, PyObject *args)
  557. {
  558. if (self->fd < 0)
  559. return err_closed();
  560. return portable_lseek(self->fd, NULL, 1);
  561. }
  562. #ifdef HAVE_FTRUNCATE
  563. static PyObject *
  564. fileio_truncate(PyFileIOObject *self, PyObject *args)
  565. {
  566. PyObject *posobj = NULL;
  567. Py_off_t pos;
  568. int ret;
  569. int fd;
  570. fd = self->fd;
  571. if (fd < 0)
  572. return err_closed();
  573. if (!self->writable)
  574. return err_mode("writing");
  575. if (!PyArg_ParseTuple(args, "|O", &posobj))
  576. return NULL;
  577. if (posobj == Py_None || posobj == NULL) {
  578. /* Get the current position. */
  579. posobj = portable_lseek(fd, NULL, 1);
  580. if (posobj == NULL)
  581. return NULL;
  582. }
  583. else {
  584. /* Move to the position to be truncated. */
  585. posobj = portable_lseek(fd, posobj, 0);
  586. }
  587. #if defined(HAVE_LARGEFILE_SUPPORT)
  588. pos = PyLong_AsLongLong(posobj);
  589. #else
  590. pos = PyLong_AsLong(posobj);
  591. #endif
  592. if (PyErr_Occurred())
  593. return NULL;
  594. #ifdef MS_WINDOWS
  595. /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
  596. so don't even try using it. */
  597. {
  598. HANDLE hFile;
  599. /* Truncate. Note that this may grow the file! */
  600. Py_BEGIN_ALLOW_THREADS
  601. errno = 0;
  602. hFile = (HANDLE)_get_osfhandle(fd);
  603. ret = hFile == (HANDLE)-1;
  604. if (ret == 0) {
  605. ret = SetEndOfFile(hFile) == 0;
  606. if (ret)
  607. errno = EACCES;
  608. }
  609. Py_END_ALLOW_THREADS
  610. }
  611. #else
  612. Py_BEGIN_ALLOW_THREADS
  613. errno = 0;
  614. ret = ftruncate(fd, pos);
  615. Py_END_ALLOW_THREADS
  616. #endif /* !MS_WINDOWS */
  617. if (ret != 0) {
  618. PyErr_SetFromErrno(PyExc_IOError);
  619. return NULL;
  620. }
  621. return posobj;
  622. }
  623. #endif
  624. static char *
  625. mode_string(PyFileIOObject *self)
  626. {
  627. if (self->readable) {
  628. if (self->writable)
  629. return "rb+";
  630. else
  631. return "rb";
  632. }
  633. else
  634. return "wb";
  635. }
  636. static PyObject *
  637. fileio_repr(PyFileIOObject *self)
  638. {
  639. if (self->fd < 0)
  640. return PyString_FromFormat("_fileio._FileIO(-1)");
  641. return PyString_FromFormat("_fileio._FileIO(%d, '%s')",
  642. self->fd, mode_string(self));
  643. }
  644. static PyObject *
  645. fileio_isatty(PyFileIOObject *self)
  646. {
  647. long res;
  648. if (self->fd < 0)
  649. return err_closed();
  650. Py_BEGIN_ALLOW_THREADS
  651. res = isatty(self->fd);
  652. Py_END_ALLOW_THREADS
  653. return PyBool_FromLong(res);
  654. }
  655. PyDoc_STRVAR(fileio_doc,
  656. "file(name: str[, mode: str]) -> file IO object\n"
  657. "\n"
  658. "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
  659. "writing or appending. The file will be created if it doesn't exist\n"
  660. "when opened for writing or appending; it will be truncated when\n"
  661. "opened for writing. Add a '+' to the mode to allow simultaneous\n"
  662. "reading and writing.");
  663. PyDoc_STRVAR(read_doc,
  664. "read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
  665. "\n"
  666. "Only makes one system call, so less data may be returned than requested\n"
  667. "In non-blocking mode, returns None if no data is available.\n"
  668. "On end-of-file, returns ''.");
  669. PyDoc_STRVAR(readall_doc,
  670. "readall() -> bytes. read all data from the file, returned as bytes.\n"
  671. "\n"
  672. "In non-blocking mode, returns as much as is immediately available,\n"
  673. "or None if no data is available. On end-of-file, returns ''.");
  674. PyDoc_STRVAR(write_doc,
  675. "write(b: bytes) -> int. Write bytes b to file, return number written.\n"
  676. "\n"
  677. "Only makes one system call, so not all of the data may be written.\n"
  678. "The number of bytes actually written is returned.");
  679. PyDoc_STRVAR(fileno_doc,
  680. "fileno() -> int. \"file descriptor\".\n"
  681. "\n"
  682. "This is needed for lower-level file interfaces, such the fcntl module.");
  683. PyDoc_STRVAR(seek_doc,
  684. "seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
  685. "\n"
  686. "Argument offset is a byte count. Optional argument whence defaults to\n"
  687. "0 (offset from start of file, offset should be >= 0); other values are 1\n"
  688. "(move relative to current position, positive or negative), and 2 (move\n"
  689. "relative to end of file, usually negative, although many platforms allow\n"
  690. "seeking beyond the end of a file)."
  691. "\n"
  692. "Note that not all file objects are seekable.");
  693. #ifdef HAVE_FTRUNCATE
  694. PyDoc_STRVAR(truncate_doc,
  695. "truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
  696. "\n"
  697. "Size defaults to the current file position, as returned by tell()."
  698. "The current file position is changed to the value of size.");
  699. #endif
  700. PyDoc_STRVAR(tell_doc,
  701. "tell() -> int. Current file position");
  702. PyDoc_STRVAR(readinto_doc,
  703. "readinto() -> Undocumented. Don't use this; it may go away.");
  704. PyDoc_STRVAR(close_doc,
  705. "close() -> None. Close the file.\n"
  706. "\n"
  707. "A closed file cannot be used for further I/O operations. close() may be\n"
  708. "called more than once without error. Changes the fileno to -1.");
  709. PyDoc_STRVAR(isatty_doc,
  710. "isatty() -> bool. True if the file is connected to a tty device.");
  711. PyDoc_STRVAR(seekable_doc,
  712. "seekable() -> bool. True if file supports random-access.");
  713. PyDoc_STRVAR(readable_doc,
  714. "readable() -> bool. True if file was opened in a read mode.");
  715. PyDoc_STRVAR(writable_doc,
  716. "writable() -> bool. True if file was opened in a write mode.");
  717. static PyMethodDef fileio_methods[] = {
  718. {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
  719. {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
  720. {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
  721. {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
  722. {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
  723. {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
  724. #ifdef HAVE_FTRUNCATE
  725. {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
  726. #endif
  727. {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
  728. {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
  729. {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
  730. {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
  731. {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
  732. {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
  733. {NULL, NULL} /* sentinel */
  734. };
  735. /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
  736. static PyObject *
  737. get_closed(PyFileIOObject *self, void *closure)
  738. {
  739. return PyBool_FromLong((long)(self->fd < 0));
  740. }
  741. static PyObject *
  742. get_closefd(PyFileIOObject *self, void *closure)
  743. {
  744. return PyBool_FromLong((long)(self->closefd));
  745. }
  746. static PyObject *
  747. get_mode(PyFileIOObject *self, void *closure)
  748. {
  749. return PyString_FromString(mode_string(self));
  750. }
  751. static PyGetSetDef fileio_getsetlist[] = {
  752. {"closed", (getter)get_closed, NULL, "True if the file is closed"},
  753. {"closefd", (getter)get_closefd, NULL,
  754. "True if the file descriptor will be closed"},
  755. {"mode", (getter)get_mode, NULL, "String giving the file mode"},
  756. {0},
  757. };
  758. PyTypeObject PyFileIO_Type = {
  759. PyVarObject_HEAD_INIT(NULL, 0)
  760. "_FileIO",
  761. sizeof(PyFileIOObject),
  762. 0,
  763. (destructor)fileio_dealloc, /* tp_dealloc */
  764. 0, /* tp_print */
  765. 0, /* tp_getattr */
  766. 0, /* tp_setattr */
  767. 0, /* tp_compare */
  768. (reprfunc)fileio_repr, /* tp_repr */
  769. 0, /* tp_as_number */
  770. 0, /* tp_as_sequence */
  771. 0, /* tp_as_mapping */
  772. 0, /* tp_hash */
  773. 0, /* tp_call */
  774. 0, /* tp_str */
  775. PyObject_GenericGetAttr, /* tp_getattro */
  776. 0, /* tp_setattro */
  777. 0, /* tp_as_buffer */
  778. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  779. fileio_doc, /* tp_doc */
  780. 0, /* tp_traverse */
  781. 0, /* tp_clear */
  782. 0, /* tp_richcompare */
  783. offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
  784. 0, /* tp_iter */
  785. 0, /* tp_iternext */
  786. fileio_methods, /* tp_methods */
  787. 0, /* tp_members */
  788. fileio_getsetlist, /* tp_getset */
  789. 0, /* tp_base */
  790. 0, /* tp_dict */
  791. 0, /* tp_descr_get */
  792. 0, /* tp_descr_set */
  793. 0, /* tp_dictoffset */
  794. fileio_init, /* tp_init */
  795. PyType_GenericAlloc, /* tp_alloc */
  796. fileio_new, /* tp_new */
  797. PyObject_Del, /* tp_free */
  798. };
  799. static PyMethodDef module_methods[] = {
  800. {NULL, NULL}
  801. };
  802. PyMODINIT_FUNC
  803. init_fileio(void)
  804. {
  805. PyObject *m; /* a module object */
  806. m = Py_InitModule3("_fileio", module_methods,
  807. "Fast implementation of io.FileIO.");
  808. if (m == NULL)
  809. return;
  810. if (PyType_Ready(&PyFileIO_Type) < 0)
  811. return;
  812. Py_INCREF(&PyFileIO_Type);
  813. PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
  814. }