home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Objects / fileobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  27.3 KB  |  1,285 lines

  1.  
  2. /* File object implementation */
  3.  
  4. #include "Python.h"
  5. #include "structmember.h"
  6.  
  7. #ifndef DONT_HAVE_SYS_TYPES_H
  8. #include <sys/types.h>
  9. #endif /* DONT_HAVE_SYS_TYPES_H */
  10.  
  11. /* We expect that fstat exists on most systems.
  12.    It's confirmed on Unix, Mac and Windows.
  13.    If you don't have it, add #define DONT_HAVE_FSTAT to your config.h. */
  14. #ifndef DONT_HAVE_FSTAT
  15. #define HAVE_FSTAT
  16.  
  17. #ifndef DONT_HAVE_SYS_TYPES_H
  18. #include <sys/types.h>
  19. #endif
  20.  
  21. #ifndef DONT_HAVE_SYS_STAT_H
  22. #include <sys/stat.h>
  23. #else
  24. #ifdef HAVE_STAT_H
  25. #include <stat.h>
  26. #endif
  27. #endif
  28.  
  29. #endif /* DONT_HAVE_FSTAT */
  30.  
  31. #ifdef HAVE_UNISTD_H
  32. #include <unistd.h>
  33. #endif
  34.  
  35. #ifdef MS_WIN32
  36. #define fileno _fileno
  37. /* can (almost fully) duplicate with _chsize, see file_truncate */
  38. #define HAVE_FTRUNCATE
  39. #endif
  40.  
  41. #ifdef macintosh
  42. #ifdef USE_GUSI
  43. #define HAVE_FTRUNCATE
  44. #endif
  45. #endif
  46.  
  47. #ifdef __MWERKS__
  48. /* Mwerks fopen() doesn't always set errno */
  49. #define NO_FOPEN_ERRNO
  50. #endif
  51.  
  52. #define BUF(v) PyString_AS_STRING((PyStringObject *)v)
  53.  
  54. #ifndef DONT_HAVE_ERRNO_H
  55. #include <errno.h>
  56. #endif
  57.  
  58. /* define the appropriate 64-bit capable tell() function */
  59. #if defined(MS_WIN64)
  60. #define TELL64 _telli64
  61. #elif defined(__NetBSD__) || defined(__OpenBSD__)
  62. /* NOTE: this is only used on older
  63.    NetBSD prior to f*o() funcions */
  64. #define TELL64(fd) lseek((fd),0,SEEK_CUR)
  65. #endif
  66.  
  67.  
  68. typedef struct {
  69.     PyObject_HEAD
  70.     FILE *f_fp;
  71.     PyObject *f_name;
  72.     PyObject *f_mode;
  73.     int (*f_close)(FILE *);
  74.     int f_softspace; /* Flag used by 'print' command */
  75.     int f_binary; /* Flag which indicates whether the file is open
  76.              open in binary (1) or test (0) mode */
  77. } PyFileObject;
  78.  
  79. FILE *
  80. PyFile_AsFile(PyObject *f)
  81. {
  82.     if (f == NULL || !PyFile_Check(f))
  83.         return NULL;
  84.     else
  85.         return ((PyFileObject *)f)->f_fp;
  86. }
  87.  
  88. PyObject *
  89. PyFile_Name(PyObject *f)
  90. {
  91.     if (f == NULL || !PyFile_Check(f))
  92.         return NULL;
  93.     else
  94.         return ((PyFileObject *)f)->f_name;
  95. }
  96.  
  97. PyObject *
  98. PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
  99. {
  100.     PyFileObject *f = PyObject_NEW(PyFileObject, &PyFile_Type);
  101.     if (f == NULL)
  102.         return NULL;
  103.     f->f_fp = NULL;
  104.     f->f_name = PyString_FromString(name);
  105.     f->f_mode = PyString_FromString(mode);
  106.     f->f_close = close;
  107.     f->f_softspace = 0;
  108.     if (strchr(mode,'b') != NULL)
  109.         f->f_binary = 1;
  110.     else
  111.         f->f_binary = 0;
  112.     if (f->f_name == NULL || f->f_mode == NULL) {
  113.         Py_DECREF(f);
  114.         return NULL;
  115.     }
  116.     f->f_fp = fp;
  117.     return (PyObject *) f;
  118. }
  119.  
  120. PyObject *
  121. PyFile_FromString(char *name, char *mode)
  122. {
  123.     extern int fclose(FILE *);
  124.     PyFileObject *f;
  125.     f = (PyFileObject *) PyFile_FromFile((FILE *)NULL, name, mode, fclose);
  126.     if (f == NULL)
  127.         return NULL;
  128. #ifdef HAVE_FOPENRF
  129.     if (*mode == '*') {
  130.         FILE *fopenRF();
  131.         f->f_fp = fopenRF(name, mode+1);
  132.     }
  133.     else
  134. #endif
  135.     {
  136.         Py_BEGIN_ALLOW_THREADS
  137.         f->f_fp = fopen(name, mode);
  138.         Py_END_ALLOW_THREADS
  139.     }
  140.     if (f->f_fp == NULL) {
  141. #ifdef NO_FOPEN_ERRNO
  142.         /* Metroworks only, not testable, so unchanged */
  143.         if ( errno == 0 ) {
  144.             PyErr_SetString(PyExc_IOError, "Cannot open file");
  145.             Py_DECREF(f);
  146.             return NULL;
  147.         }
  148. #endif
  149.         PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
  150.         Py_DECREF(f);
  151.         return NULL;
  152.     }
  153.     return (PyObject *)f;
  154. }
  155.  
  156. void
  157. PyFile_SetBufSize(PyObject *f, int bufsize)
  158. {
  159.     if (bufsize >= 0) {
  160. #ifdef HAVE_SETVBUF
  161.         int type;
  162.         switch (bufsize) {
  163.         case 0:
  164.             type = _IONBF;
  165.             break;
  166.         case 1:
  167.             type = _IOLBF;
  168.             bufsize = BUFSIZ;
  169.             break;
  170.         default:
  171.             type = _IOFBF;
  172.         }
  173.         setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
  174.             type, bufsize);
  175. #else /* !HAVE_SETVBUF */
  176.         if (bufsize <= 1)
  177.             setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
  178. #endif /* !HAVE_SETVBUF */
  179.     }
  180. }
  181.  
  182. static PyObject *
  183. err_closed(void)
  184. {
  185.     PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
  186.     return NULL;
  187. }
  188.  
  189. /* Methods */
  190.  
  191. static void
  192. file_dealloc(PyFileObject *f)
  193. {
  194.     if (f->f_fp != NULL && f->f_close != NULL) {
  195.         Py_BEGIN_ALLOW_THREADS
  196.         (*f->f_close)(f->f_fp);
  197.         Py_END_ALLOW_THREADS
  198.     }
  199.     if (f->f_name != NULL) {
  200.         Py_DECREF(f->f_name);
  201.     }
  202.     if (f->f_mode != NULL) {
  203.         Py_DECREF(f->f_mode);
  204.     }
  205.     PyObject_DEL(f);
  206. }
  207.  
  208. static PyObject *
  209. file_repr(PyFileObject *f)
  210. {
  211.     char buf[300];
  212.     sprintf(buf, "<%s file '%.256s', mode '%.10s' at %p>",
  213.         f->f_fp == NULL ? "closed" : "open",
  214.         PyString_AsString(f->f_name),
  215.         PyString_AsString(f->f_mode),
  216.         f);
  217.     return PyString_FromString(buf);
  218. }
  219.  
  220. static PyObject *
  221. file_close(PyFileObject *f, PyObject *args)
  222. {
  223.     int sts = 0;
  224.     if (!PyArg_NoArgs(args))
  225.         return NULL;
  226.     if (f->f_fp != NULL) {
  227.         if (f->f_close != NULL) {
  228.             Py_BEGIN_ALLOW_THREADS
  229.             errno = 0;
  230.             sts = (*f->f_close)(f->f_fp);
  231.             Py_END_ALLOW_THREADS
  232.         }
  233.         f->f_fp = NULL;
  234.     }
  235.     if (sts == EOF)
  236.         return PyErr_SetFromErrno(PyExc_IOError);
  237.     if (sts != 0)
  238.         return PyInt_FromLong((long)sts);
  239.     Py_INCREF(Py_None);
  240.     return Py_None;
  241. }
  242.  
  243.  
  244. /* a portable fseek() function
  245.    return 0 on success, non-zero on failure (with errno set) */
  246. int
  247. #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8 
  248. _portable_fseek(FILE *fp, fpos_t offset, int whence)
  249. #else
  250. _portable_fseek(FILE *fp, off_t offset, int whence)
  251. #endif
  252. {
  253. #if defined(HAVE_FSEEKO)
  254.     return fseeko(fp, offset, whence);
  255. #elif defined(HAVE_FSEEK64)
  256.     return fseek64(fp, offset, whence);
  257. #elif defined(__BEOS__)
  258.     return _fseek(fp, offset, whence);
  259. #elif defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_FPOS_T >= 8 
  260.     /* lacking a 64-bit capable fseek() (as Win64 does) use a 64-bit capable
  261.         fsetpos() and tell() to implement fseek()*/
  262.     fpos_t pos;
  263.     switch (whence) {
  264.         case SEEK_CUR:
  265.             if (fgetpos(fp, &pos) != 0)
  266.                 return -1;
  267.             offset += pos;
  268.             break;
  269.         case SEEK_END:
  270.             /* do a "no-op" seek first to sync the buffering so that
  271.                the low-level tell() can be used correctly */
  272.             if (fseek(fp, 0, SEEK_END) != 0)
  273.                 return -1;
  274.             if ((pos = TELL64(fileno(fp))) == -1L)
  275.                 return -1;
  276.             offset += pos;
  277.             break;
  278.         /* case SEEK_SET: break; */
  279.     }
  280.     return fsetpos(fp, &offset);
  281. #else
  282.     return fseek(fp, offset, whence);
  283. #endif
  284. }
  285.  
  286.  
  287. /* a portable ftell() function
  288.    Return -1 on failure with errno set appropriately, current file
  289.    position on success */
  290. #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8 
  291. fpos_t
  292. #else
  293. off_t
  294. #endif
  295. _portable_ftell(FILE* fp)
  296. {
  297. #if defined(HAVE_FTELLO) && defined(HAVE_LARGEFILE_SUPPORT)
  298.     return ftello(fp);
  299. #elif defined(HAVE_FTELL64) && defined(HAVE_LARGEFILE_SUPPORT)
  300.     return ftell64(fp);
  301. #elif SIZEOF_FPOS_T >= 8 && defined(HAVE_LARGEFILE_SUPPORT)
  302.     fpos_t pos;
  303.     if (fgetpos(fp, &pos) != 0)
  304.         return -1;
  305.     return pos;
  306. #else
  307.     return ftell(fp);
  308. #endif
  309. }
  310.  
  311.  
  312. static PyObject *
  313. file_seek(PyFileObject *f, PyObject *args)
  314. {
  315.     int whence;
  316.     int ret;
  317. #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8 
  318.     fpos_t offset, pos;
  319. #else
  320.     off_t offset;
  321. #endif /* !MS_WIN64 */
  322.     PyObject *offobj;
  323.     
  324.     if (f->f_fp == NULL)
  325.         return err_closed();
  326.     whence = 0;
  327.     if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
  328.         return NULL;
  329. #if !defined(HAVE_LARGEFILE_SUPPORT)
  330.     offset = PyInt_AsLong(offobj);
  331. #else
  332.     offset = PyLong_Check(offobj) ?
  333.         PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
  334. #endif
  335.     if (PyErr_Occurred())
  336.         return NULL;
  337.     
  338.     Py_BEGIN_ALLOW_THREADS
  339.     errno = 0;
  340.     ret = _portable_fseek(f->f_fp, offset, whence);
  341.     Py_END_ALLOW_THREADS
  342.  
  343.     if (ret != 0) {
  344.         PyErr_SetFromErrno(PyExc_IOError);
  345.         clearerr(f->f_fp);
  346.         return NULL;
  347.     }
  348.     Py_INCREF(Py_None);
  349.     return Py_None;
  350. }
  351.  
  352.  
  353. #ifdef HAVE_FTRUNCATE
  354. static PyObject *
  355. file_truncate(PyFileObject *f, PyObject *args)
  356. {
  357.     int ret;
  358. #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8 
  359.     fpos_t newsize;
  360. #else
  361.     off_t newsize;
  362. #endif
  363.     PyObject *newsizeobj;
  364.     
  365.     if (f->f_fp == NULL)
  366.         return err_closed();
  367.     newsizeobj = NULL;
  368.     if (!PyArg_ParseTuple(args, "|O:truncate", &newsizeobj))
  369.         return NULL;
  370.     if (newsizeobj != NULL) {
  371. #if !defined(HAVE_LARGEFILE_SUPPORT)
  372.         newsize = PyInt_AsLong(newsizeobj);
  373. #else
  374.         newsize = PyLong_Check(newsizeobj) ?
  375.                 PyLong_AsLongLong(newsizeobj) :
  376.                 PyInt_AsLong(newsizeobj);
  377. #endif
  378.         if (PyErr_Occurred())
  379.             return NULL;
  380.     } else {
  381.         /* Default to current position*/
  382.         Py_BEGIN_ALLOW_THREADS
  383.         errno = 0;
  384.         newsize = _portable_ftell(f->f_fp);
  385.         Py_END_ALLOW_THREADS
  386.         if (newsize == -1) {
  387.                 PyErr_SetFromErrno(PyExc_IOError);
  388.             clearerr(f->f_fp);
  389.             return NULL;
  390.         }
  391.     }
  392.     Py_BEGIN_ALLOW_THREADS
  393.     errno = 0;
  394.     ret = fflush(f->f_fp);
  395.     Py_END_ALLOW_THREADS
  396.     if (ret != 0) goto onioerror;
  397.  
  398. #ifdef MS_WIN32
  399.     /* can use _chsize; if, however, the newsize overflows 32-bits then
  400.        _chsize is *not* adequate; in this case, an OverflowError is raised */
  401.     if (newsize > LONG_MAX) {
  402.         PyErr_SetString(PyExc_OverflowError,
  403.             "the new size is too long for _chsize (it is limited to 32-bit values)");
  404.         return NULL;
  405.     } else {
  406.         Py_BEGIN_ALLOW_THREADS
  407.         errno = 0;
  408.         ret = _chsize(fileno(f->f_fp), newsize);
  409.         Py_END_ALLOW_THREADS
  410.         if (ret != 0) goto onioerror;
  411.     }
  412. #else
  413.     Py_BEGIN_ALLOW_THREADS
  414.     errno = 0;
  415.     ret = ftruncate(fileno(f->f_fp), newsize);
  416.     Py_END_ALLOW_THREADS
  417.     if (ret != 0) goto onioerror;
  418. #endif /* !MS_WIN32 */
  419.     
  420.     Py_INCREF(Py_None);
  421.     return Py_None;
  422.  
  423. onioerror:
  424.     PyErr_SetFromErrno(PyExc_IOError);
  425.     clearerr(f->f_fp);
  426.     return NULL;
  427. }
  428. #endif /* HAVE_FTRUNCATE */
  429.  
  430. static PyObject *
  431. file_tell(PyFileObject *f, PyObject *args)
  432. {
  433. #if defined(HAVE_LARGEFILE_SUPPORT) && SIZEOF_OFF_T < 8 && SIZEOF_FPOS_T >= 8 
  434.     fpos_t pos;
  435. #else
  436.     off_t pos;
  437. #endif
  438.  
  439.     if (f->f_fp == NULL)
  440.         return err_closed();
  441.     if (!PyArg_NoArgs(args))
  442.         return NULL;
  443.     Py_BEGIN_ALLOW_THREADS
  444.     errno = 0;
  445.     pos = _portable_ftell(f->f_fp);
  446.     Py_END_ALLOW_THREADS
  447.     if (pos == -1) {
  448.         PyErr_SetFromErrno(PyExc_IOError);
  449.         clearerr(f->f_fp);
  450.         return NULL;
  451.     }
  452. #if !defined(HAVE_LARGEFILE_SUPPORT)
  453.     return PyInt_FromLong(pos);
  454. #else
  455.     return PyLong_FromLongLong(pos);
  456. #endif
  457. }
  458.  
  459. static PyObject *
  460. file_fileno(PyFileObject *f, PyObject *args)
  461. {
  462.     if (f->f_fp == NULL)
  463.         return err_closed();
  464.     if (!PyArg_NoArgs(args))
  465.         return NULL;
  466.     return PyInt_FromLong((long) fileno(f->f_fp));
  467. }
  468.  
  469. static PyObject *
  470. file_flush(PyFileObject *f, PyObject *args)
  471. {
  472.     int res;
  473.     
  474.     if (f->f_fp == NULL)
  475.         return err_closed();
  476.     if (!PyArg_NoArgs(args))
  477.         return NULL;
  478.     Py_BEGIN_ALLOW_THREADS
  479.     errno = 0;
  480.     res = fflush(f->f_fp);
  481.     Py_END_ALLOW_THREADS
  482.     if (res != 0) {
  483.         PyErr_SetFromErrno(PyExc_IOError);
  484.         clearerr(f->f_fp);
  485.         return NULL;
  486.     }
  487.     Py_INCREF(Py_None);
  488.     return Py_None;
  489. }
  490.  
  491. static PyObject *
  492. file_isatty(PyFileObject *f, PyObject *args)
  493. {
  494.     long res;
  495.     if (f->f_fp == NULL)
  496.         return err_closed();
  497.     if (!PyArg_NoArgs(args))
  498.         return NULL;
  499.     Py_BEGIN_ALLOW_THREADS
  500.     res = isatty((int)fileno(f->f_fp));
  501.     Py_END_ALLOW_THREADS
  502.     return PyInt_FromLong(res);
  503. }
  504.  
  505.  
  506. #if BUFSIZ < 8192
  507. #define SMALLCHUNK 8192
  508. #else
  509. #define SMALLCHUNK BUFSIZ
  510. #endif
  511.  
  512. #if SIZEOF_INT < 4
  513. #define BIGCHUNK  (512 * 32)
  514. #else
  515. #define BIGCHUNK  (512 * 1024)
  516. #endif
  517.  
  518. static size_t
  519. new_buffersize(PyFileObject *f, size_t currentsize)
  520. {
  521. #ifdef HAVE_FSTAT
  522.     long pos, end;
  523.     struct stat st;
  524.     if (fstat(fileno(f->f_fp), &st) == 0) {
  525.         end = st.st_size;
  526.         /* The following is not a bug: we really need to call lseek()
  527.            *and* ftell().  The reason is that some stdio libraries
  528.            mistakenly flush their buffer when ftell() is called and
  529.            the lseek() call it makes fails, thereby throwing away
  530.            data that cannot be recovered in any way.  To avoid this,
  531.            we first test lseek(), and only call ftell() if lseek()
  532.            works.  We can't use the lseek() value either, because we
  533.            need to take the amount of buffered data into account.
  534.            (Yet another reason why stdio stinks. :-) */
  535.         pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
  536.         if (pos >= 0)
  537.             pos = ftell(f->f_fp);
  538.         if (pos < 0)
  539.             clearerr(f->f_fp);
  540.         if (end > pos && pos >= 0)
  541.             return currentsize + end - pos + 1;
  542.         /* Add 1 so if the file were to grow we'd notice. */
  543.     }
  544. #endif
  545.     if (currentsize > SMALLCHUNK) {
  546.         /* Keep doubling until we reach BIGCHUNK;
  547.            then keep adding BIGCHUNK. */
  548.         if (currentsize <= BIGCHUNK)
  549.             return currentsize + currentsize;
  550.         else
  551.             return currentsize + BIGCHUNK;
  552.     }
  553.     return currentsize + SMALLCHUNK;
  554. }
  555.  
  556. static PyObject *
  557. file_read(PyFileObject *f, PyObject *args)
  558. {
  559.     long bytesrequested = -1;
  560.     size_t bytesread, buffersize, chunksize;
  561.     PyObject *v;
  562.     
  563.     if (f->f_fp == NULL)
  564.         return err_closed();
  565.     if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
  566.         return NULL;
  567.     if (bytesrequested < 0)
  568.         buffersize = new_buffersize(f, (size_t)0);
  569.     else
  570.         buffersize = bytesrequested;
  571.     if (buffersize > INT_MAX) {
  572.         PyErr_SetString(PyExc_OverflowError,
  573.             "requested number of bytes is more than a Python string can hold");
  574.         return NULL;
  575.     }
  576.     v = PyString_FromStringAndSize((char *)NULL, buffersize);
  577.     if (v == NULL)
  578.         return NULL;
  579.     bytesread = 0;
  580.     for (;;) {
  581.         Py_BEGIN_ALLOW_THREADS
  582.         errno = 0;
  583.         chunksize = fread(BUF(v) + bytesread, 1,
  584.                   buffersize - bytesread, f->f_fp);
  585.         Py_END_ALLOW_THREADS
  586.         if (chunksize == 0) {
  587.             if (!ferror(f->f_fp))
  588.                 break;
  589.             PyErr_SetFromErrno(PyExc_IOError);
  590.             clearerr(f->f_fp);
  591.             Py_DECREF(v);
  592.             return NULL;
  593.         }
  594.         bytesread += chunksize;
  595.         if (bytesread < buffersize)
  596.             break;
  597.         if (bytesrequested < 0) {
  598.             buffersize = new_buffersize(f, buffersize);
  599.             if (_PyString_Resize(&v, buffersize) < 0)
  600.                 return NULL;
  601.         }
  602.     }
  603.     if (bytesread != buffersize)
  604.         _PyString_Resize(&v, bytesread);
  605.     return v;
  606. }
  607.  
  608. static PyObject *
  609. file_readinto(PyFileObject *f, PyObject *args)
  610. {
  611.     char *ptr;
  612.     size_t ntodo, ndone, nnow;
  613.     
  614.     if (f->f_fp == NULL)
  615.         return err_closed();
  616.     if (!PyArg_Parse(args, "w#", &ptr, &ntodo))
  617.         return NULL;
  618.     ndone = 0;
  619.     while (ntodo > 0) {
  620.         Py_BEGIN_ALLOW_THREADS
  621.         errno = 0;
  622.         nnow = fread(ptr+ndone, 1, ntodo, f->f_fp);
  623.         Py_END_ALLOW_THREADS
  624.         if (nnow == 0) {
  625.             if (!ferror(f->f_fp))
  626.                 break;
  627.             PyErr_SetFromErrno(PyExc_IOError);
  628.             clearerr(f->f_fp);
  629.             return NULL;
  630.         }
  631.         ndone += nnow;
  632.         ntodo -= nnow;
  633.     }
  634.     return PyInt_FromLong((long)ndone);
  635. }
  636.  
  637.  
  638. /* Internal routine to get a line.
  639.    Size argument interpretation:
  640.    > 0: max length;
  641.    = 0: read arbitrary line;
  642.    < 0: strip trailing '\n', raise EOFError if EOF reached immediately
  643. */
  644.  
  645. static PyObject *
  646. get_line(PyFileObject *f, int n)
  647. {
  648.     register FILE *fp;
  649.     register int c;
  650.     register char *buf, *end;
  651.     size_t n1, n2;
  652.     PyObject *v;
  653.  
  654.     fp = f->f_fp;
  655.     n2 = n > 0 ? n : 100;
  656.     v = PyString_FromStringAndSize((char *)NULL, n2);
  657.     if (v == NULL)
  658.         return NULL;
  659.     buf = BUF(v);
  660.     end = buf + n2;
  661.  
  662.     Py_BEGIN_ALLOW_THREADS
  663.     for (;;) {
  664.         if ((c = getc(fp)) == EOF) {
  665.             clearerr(fp);
  666.             Py_BLOCK_THREADS
  667.             if (PyErr_CheckSignals()) {
  668.                 Py_DECREF(v);
  669.                 return NULL;
  670.             }
  671.             if (n < 0 && buf == BUF(v)) {
  672.                 Py_DECREF(v);
  673.                 PyErr_SetString(PyExc_EOFError,
  674.                        "EOF when reading a line");
  675.                 return NULL;
  676.             }
  677.             Py_UNBLOCK_THREADS
  678.             break;
  679.         }
  680.         if ((*buf++ = c) == '\n') {
  681.             if (n < 0)
  682.                 buf--;
  683.             break;
  684.         }
  685.         if (buf == end) {
  686.             if (n > 0)
  687.                 break;
  688.             n1 = n2;
  689.             n2 += 1000;
  690.             if (n2 > INT_MAX) {
  691.                 PyErr_SetString(PyExc_OverflowError,
  692.                     "line is longer than a Python string can hold");
  693.                 return NULL;
  694.             }
  695.             Py_BLOCK_THREADS
  696.             if (_PyString_Resize(&v, n2) < 0)
  697.                 return NULL;
  698.             Py_UNBLOCK_THREADS
  699.             buf = BUF(v) + n1;
  700.             end = BUF(v) + n2;
  701.         }
  702.     }
  703.     Py_END_ALLOW_THREADS
  704.  
  705.     n1 = buf - BUF(v);
  706.     if (n1 != n2)
  707.         _PyString_Resize(&v, n1);
  708.     return v;
  709. }
  710.  
  711. /* External C interface */
  712.  
  713. PyObject *
  714. PyFile_GetLine(PyObject *f, int n)
  715. {
  716.     if (f == NULL) {
  717.         PyErr_BadInternalCall();
  718.         return NULL;
  719.     }
  720.     if (!PyFile_Check(f)) {
  721.         PyObject *reader;
  722.         PyObject *args;
  723.         PyObject *result;
  724.         reader = PyObject_GetAttrString(f, "readline");
  725.         if (reader == NULL)
  726.             return NULL;
  727.         if (n <= 0)
  728.             args = Py_BuildValue("()");
  729.         else
  730.             args = Py_BuildValue("(i)", n);
  731.         if (args == NULL) {
  732.             Py_DECREF(reader);
  733.             return NULL;
  734.         }
  735.         result = PyEval_CallObject(reader, args);
  736.         Py_DECREF(reader);
  737.         Py_DECREF(args);
  738.         if (result != NULL && !PyString_Check(result)) {
  739.             Py_DECREF(result);
  740.             result = NULL;
  741.             PyErr_SetString(PyExc_TypeError,
  742.                    "object.readline() returned non-string");
  743.         }
  744.         if (n < 0 && result != NULL) {
  745.             char *s = PyString_AsString(result);
  746.             int len = PyString_Size(result);
  747.             if (len == 0) {
  748.                 Py_DECREF(result);
  749.                 result = NULL;
  750.                 PyErr_SetString(PyExc_EOFError,
  751.                        "EOF when reading a line");
  752.             }
  753.             else if (s[len-1] == '\n') {
  754.                 if (result->ob_refcnt == 1)
  755.                     _PyString_Resize(&result, len-1);
  756.                 else {
  757.                     PyObject *v;
  758.                     v = PyString_FromStringAndSize(s,
  759.                                        len-1);
  760.                     Py_DECREF(result);
  761.                     result = v;
  762.                 }
  763.             }
  764.         }
  765.         return result;
  766.     }
  767.     if (((PyFileObject*)f)->f_fp == NULL)
  768.         return err_closed();
  769.     return get_line((PyFileObject *)f, n);
  770. }
  771.  
  772. /* Python method */
  773.  
  774. static PyObject *
  775. file_readline(PyFileObject *f, PyObject *args)
  776. {
  777.     int n = -1;
  778.  
  779.     if (f->f_fp == NULL)
  780.         return err_closed();
  781.     if (!PyArg_ParseTuple(args, "|i:readline", &n))
  782.         return NULL;
  783.     if (n == 0)
  784.         return PyString_FromString("");
  785.     if (n < 0)
  786.         n = 0;
  787.     return get_line(f, n);
  788. }
  789.  
  790. static PyObject *
  791. file_readlines(PyFileObject *f, PyObject *args)
  792. {
  793.     long sizehint = 0;
  794.     PyObject *list;
  795.     PyObject *line;
  796.     char small_buffer[SMALLCHUNK];
  797.     char *buffer = small_buffer;
  798.     size_t buffersize = SMALLCHUNK;
  799.     PyObject *big_buffer = NULL;
  800.     size_t nfilled = 0;
  801.     size_t nread;
  802.     size_t totalread = 0;
  803.     char *p, *q, *end;
  804.     int err;
  805.  
  806.     if (f->f_fp == NULL)
  807.         return err_closed();
  808.     if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
  809.         return NULL;
  810.     if ((list = PyList_New(0)) == NULL)
  811.         return NULL;
  812.     for (;;) {
  813.         Py_BEGIN_ALLOW_THREADS
  814.         errno = 0;
  815.         nread = fread(buffer+nfilled, 1, buffersize-nfilled, f->f_fp);
  816.         Py_END_ALLOW_THREADS
  817.         if (nread == 0) {
  818.             sizehint = 0;
  819.             if (!ferror(f->f_fp))
  820.                 break;
  821.             PyErr_SetFromErrno(PyExc_IOError);
  822.             clearerr(f->f_fp);
  823.           error:
  824.             Py_DECREF(list);
  825.             list = NULL;
  826.             goto cleanup;
  827.         }
  828.         totalread += nread;
  829.         p = memchr(buffer+nfilled, '\n', nread);
  830.         if (p == NULL) {
  831.             /* Need a larger buffer to fit this line */
  832.             nfilled += nread;
  833.             buffersize *= 2;
  834.             if (buffersize > INT_MAX) {
  835.                 PyErr_SetString(PyExc_OverflowError,
  836.                     "line is too long for a Python string");
  837.                 goto error;
  838.             }
  839.             if (big_buffer == NULL) {
  840.                 /* Create the big buffer */
  841.                 big_buffer = PyString_FromStringAndSize(
  842.                     NULL, buffersize);
  843.                 if (big_buffer == NULL)
  844.                     goto error;
  845.                 buffer = PyString_AS_STRING(big_buffer);
  846.                 memcpy(buffer, small_buffer, nfilled);
  847.             }
  848.             else {
  849.                 /* Grow the big buffer */
  850.                 _PyString_Resize(&big_buffer, buffersize);
  851.                 buffer = PyString_AS_STRING(big_buffer);
  852.             }
  853.             continue;
  854.         }
  855.         end = buffer+nfilled+nread;
  856.         q = buffer;
  857.         do {
  858.             /* Process complete lines */
  859.             p++;
  860.             line = PyString_FromStringAndSize(q, p-q);
  861.             if (line == NULL)
  862.                 goto error;
  863.             err = PyList_Append(list, line);
  864.             Py_DECREF(line);
  865.             if (err != 0)
  866.                 goto error;
  867.             q = p;
  868.             p = memchr(q, '\n', end-q);
  869.         } while (p != NULL);
  870.         /* Move the remaining incomplete line to the start */
  871.         nfilled = end-q;
  872.         memmove(buffer, q, nfilled);
  873.         if (sizehint > 0)
  874.             if (totalread >= (size_t)sizehint)
  875.                 break;
  876.     }
  877.     if (nfilled != 0) {
  878.         /* Partial last line */
  879.         line = PyString_FromStringAndSize(buffer, nfilled);
  880.         if (line == NULL)
  881.             goto error;
  882.         if (sizehint > 0) {
  883.             /* Need to complete the last line */
  884.             PyObject *rest = get_line(f, 0);
  885.             if (rest == NULL) {
  886.                 Py_DECREF(line);
  887.                 goto error;
  888.             }
  889.             PyString_Concat(&line, rest);
  890.             Py_DECREF(rest);
  891.             if (line == NULL)
  892.                 goto error;
  893.         }
  894.         err = PyList_Append(list, line);
  895.         Py_DECREF(line);
  896.         if (err != 0)
  897.             goto error;
  898.     }
  899.   cleanup:
  900.     if (big_buffer) {
  901.         Py_DECREF(big_buffer);
  902.     }
  903.     return list;
  904. }
  905.  
  906. static PyObject *
  907. file_write(PyFileObject *f, PyObject *args)
  908. {
  909.     char *s;
  910.     int n, n2;
  911.     if (f->f_fp == NULL)
  912.         return err_closed();
  913.     if (!PyArg_Parse(args, f->f_binary ? "s#" : "t#", &s, &n))
  914.         return NULL;
  915.     f->f_softspace = 0;
  916.     Py_BEGIN_ALLOW_THREADS
  917.     errno = 0;
  918.     n2 = fwrite(s, 1, n, f->f_fp);
  919.     Py_END_ALLOW_THREADS
  920.     if (n2 != n) {
  921.         PyErr_SetFromErrno(PyExc_IOError);
  922.         clearerr(f->f_fp);
  923.         return NULL;
  924.     }
  925.     Py_INCREF(Py_None);
  926.     return Py_None;
  927. }
  928.  
  929. static PyObject *
  930. file_writelines(PyFileObject *f, PyObject *args)
  931. {
  932. #define CHUNKSIZE 1000
  933.     PyObject *list, *line;
  934.     PyObject *result;
  935.     int i, j, index, len, nwritten, islist;
  936.  
  937.     if (f->f_fp == NULL)
  938.         return err_closed();
  939.     if (args == NULL || !PySequence_Check(args)) {
  940.         PyErr_SetString(PyExc_TypeError,
  941.                "writelines() requires sequence of strings");
  942.         return NULL;
  943.     }
  944.     islist = PyList_Check(args);
  945.  
  946.     /* Strategy: slurp CHUNKSIZE lines into a private list,
  947.        checking that they are all strings, then write that list
  948.        without holding the interpreter lock, then come back for more. */
  949.     index = 0;
  950.     if (islist)
  951.         list = NULL;
  952.     else {
  953.         list = PyList_New(CHUNKSIZE);
  954.         if (list == NULL)
  955.             return NULL;
  956.     }
  957.     result = NULL;
  958.  
  959.     for (;;) {
  960.         if (islist) {
  961.             Py_XDECREF(list);
  962.             list = PyList_GetSlice(args, index, index+CHUNKSIZE);
  963.             if (list == NULL)
  964.                 return NULL;
  965.             j = PyList_GET_SIZE(list);
  966.         }
  967.         else {
  968.             for (j = 0; j < CHUNKSIZE; j++) {
  969.                 line = PySequence_GetItem(args, index+j);
  970.                 if (line == NULL) {
  971.                     if (PyErr_ExceptionMatches(
  972.                         PyExc_IndexError)) {
  973.                         PyErr_Clear();
  974.                         break;
  975.                     }
  976.                     /* Some other error occurred.
  977.                        XXX We may lose some output. */
  978.                     goto error;
  979.                 }
  980.                 PyList_SetItem(list, j, line);
  981.             }
  982.         }
  983.         if (j == 0)
  984.             break;
  985.  
  986.         /* Check that all entries are indeed strings. If not,
  987.            apply the same rules as for file.write() and
  988.            convert the results to strings. This is slow, but
  989.            seems to be the only way since all conversion APIs
  990.            could potentially execute Python code. */
  991.         for (i = 0; i < j; i++) {
  992.             PyObject *v = PyList_GET_ITEM(list, i);
  993.             if (!PyString_Check(v)) {
  994.                     const char *buffer;
  995.                     int len;
  996.                 if (((f->f_binary && 
  997.                       PyObject_AsReadBuffer(v,
  998.                           (const void**)&buffer,
  999.                                 &len)) ||
  1000.                      PyObject_AsCharBuffer(v,
  1001.                                &buffer,
  1002.                                &len))) {
  1003.                     PyErr_SetString(PyExc_TypeError,
  1004.                 "writelines() requires sequences of strings");
  1005.                     goto error;
  1006.                 }
  1007.                 line = PyString_FromStringAndSize(buffer,
  1008.                                   len);
  1009.                 if (line == NULL)
  1010.                     goto error;
  1011.                 Py_DECREF(v);
  1012.                 PyList_SET_ITEM(list, i, line);
  1013.             }
  1014.         }
  1015.  
  1016.         /* Since we are releasing the global lock, the
  1017.            following code may *not* execute Python code. */
  1018.         Py_BEGIN_ALLOW_THREADS
  1019.         f->f_softspace = 0;
  1020.         errno = 0;
  1021.         for (i = 0; i < j; i++) {
  1022.                 line = PyList_GET_ITEM(list, i);
  1023.             len = PyString_GET_SIZE(line);
  1024.             nwritten = fwrite(PyString_AS_STRING(line),
  1025.                       1, len, f->f_fp);
  1026.             if (nwritten != len) {
  1027.                 Py_BLOCK_THREADS
  1028.                 PyErr_SetFromErrno(PyExc_IOError);
  1029.                 clearerr(f->f_fp);
  1030.                 goto error;
  1031.             }
  1032.         }
  1033.         Py_END_ALLOW_THREADS
  1034.  
  1035.         if (j < CHUNKSIZE)
  1036.             break;
  1037.         index += CHUNKSIZE;
  1038.     }
  1039.  
  1040.     Py_INCREF(Py_None);
  1041.     result = Py_None;
  1042.   error:
  1043.     Py_XDECREF(list);
  1044.     return result;
  1045. }
  1046.  
  1047. static PyMethodDef file_methods[] = {
  1048.     {"readline",    (PyCFunction)file_readline, 1},
  1049.     {"read",    (PyCFunction)file_read, 1},
  1050.     {"write",    (PyCFunction)file_write, 0},
  1051.     {"fileno",    (PyCFunction)file_fileno, 0},
  1052.     {"seek",    (PyCFunction)file_seek, 1},
  1053. #ifdef HAVE_FTRUNCATE
  1054.     {"truncate",    (PyCFunction)file_truncate, 1},
  1055. #endif
  1056.     {"tell",    (PyCFunction)file_tell, 0},
  1057.     {"readinto",    (PyCFunction)file_readinto, 0},
  1058.     {"readlines",    (PyCFunction)file_readlines, 1},
  1059.     {"writelines",    (PyCFunction)file_writelines, 0},
  1060.     {"flush",    (PyCFunction)file_flush, 0},
  1061.     {"close",    (PyCFunction)file_close, 0},
  1062.     {"isatty",    (PyCFunction)file_isatty, 0},
  1063.     {NULL,        NULL}        /* sentinel */
  1064. };
  1065.  
  1066. #define OFF(x) offsetof(PyFileObject, x)
  1067.  
  1068. static struct memberlist file_memberlist[] = {
  1069.     {"softspace",    T_INT,        OFF(f_softspace)},
  1070.     {"mode",    T_OBJECT,    OFF(f_mode),    RO},
  1071.     {"name",    T_OBJECT,    OFF(f_name),    RO},
  1072.     /* getattr(f, "closed") is implemented without this table */
  1073.     {"closed",    T_INT,        0,        RO},
  1074.     {NULL}    /* Sentinel */
  1075. };
  1076.  
  1077. static PyObject *
  1078. file_getattr(PyFileObject *f, char *name)
  1079. {
  1080.     PyObject *res;
  1081.  
  1082.     res = Py_FindMethod(file_methods, (PyObject *)f, name);
  1083.     if (res != NULL)
  1084.         return res;
  1085.     PyErr_Clear();
  1086.     if (strcmp(name, "closed") == 0)
  1087.         return PyInt_FromLong((long)(f->f_fp == 0));
  1088.     return PyMember_Get((char *)f, file_memberlist, name);
  1089. }
  1090.  
  1091. static int
  1092. file_setattr(PyFileObject *f, char *name, PyObject *v)
  1093. {
  1094.     if (v == NULL) {
  1095.         PyErr_SetString(PyExc_AttributeError,
  1096.                 "can't delete file attributes");
  1097.         return -1;
  1098.     }
  1099.     return PyMember_Set((char *)f, file_memberlist, name, v);
  1100. }
  1101.  
  1102. PyTypeObject PyFile_Type = {
  1103.     PyObject_HEAD_INIT(&PyType_Type)
  1104.     0,
  1105.     "file",
  1106.     sizeof(PyFileObject),
  1107.     0,
  1108.     (destructor)file_dealloc, /*tp_dealloc*/
  1109.     0,        /*tp_print*/
  1110.     (getattrfunc)file_getattr, /*tp_getattr*/
  1111.     (setattrfunc)file_setattr, /*tp_setattr*/
  1112.     0,        /*tp_compare*/
  1113.     (reprfunc)file_repr, /*tp_repr*/
  1114. };
  1115.  
  1116. /* Interface for the 'soft space' between print items. */
  1117.  
  1118. int
  1119. PyFile_SoftSpace(PyObject *f, int newflag)
  1120. {
  1121.     int oldflag = 0;
  1122.     if (f == NULL) {
  1123.         /* Do nothing */
  1124.     }
  1125.     else if (PyFile_Check(f)) {
  1126.         oldflag = ((PyFileObject *)f)->f_softspace;
  1127.         ((PyFileObject *)f)->f_softspace = newflag;
  1128.     }
  1129.     else {
  1130.         PyObject *v;
  1131.         v = PyObject_GetAttrString(f, "softspace");
  1132.         if (v == NULL)
  1133.             PyErr_Clear();
  1134.         else {
  1135.             if (PyInt_Check(v))
  1136.                 oldflag = PyInt_AsLong(v);
  1137.             Py_DECREF(v);
  1138.         }
  1139.         v = PyInt_FromLong((long)newflag);
  1140.         if (v == NULL)
  1141.             PyErr_Clear();
  1142.         else {
  1143.             if (PyObject_SetAttrString(f, "softspace", v) != 0)
  1144.                 PyErr_Clear();
  1145.             Py_DECREF(v);
  1146.         }
  1147.     }
  1148.     return oldflag;
  1149. }
  1150.  
  1151. /* Interfaces to write objects/strings to file-like objects */
  1152.  
  1153. int
  1154. PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
  1155. {
  1156.     PyObject *writer, *value, *args, *result;
  1157.     if (f == NULL) {
  1158.         PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
  1159.         return -1;
  1160.     }
  1161.     else if (PyFile_Check(f)) {
  1162.         FILE *fp = PyFile_AsFile(f);
  1163.         if (fp == NULL) {
  1164.             err_closed();
  1165.             return -1;
  1166.         }
  1167.         return PyObject_Print(v, fp, flags);
  1168.     }
  1169.     writer = PyObject_GetAttrString(f, "write");
  1170.     if (writer == NULL)
  1171.         return -1;
  1172.     if (flags & Py_PRINT_RAW)
  1173.         value = PyObject_Str(v);
  1174.     else
  1175.         value = PyObject_Repr(v);
  1176.     if (value == NULL) {
  1177.         Py_DECREF(writer);
  1178.         return -1;
  1179.     }
  1180.     args = Py_BuildValue("(O)", value);
  1181.     if (args == NULL) {
  1182.         Py_DECREF(value);
  1183.         Py_DECREF(writer);
  1184.         return -1;
  1185.     }
  1186.     result = PyEval_CallObject(writer, args);
  1187.     Py_DECREF(args);
  1188.     Py_DECREF(value);
  1189.     Py_DECREF(writer);
  1190.     if (result == NULL)
  1191.         return -1;
  1192.     Py_DECREF(result);
  1193.     return 0;
  1194. }
  1195.  
  1196. int
  1197. PyFile_WriteString(char *s, PyObject *f)
  1198. {
  1199.     if (f == NULL) {
  1200.         /* Should be caused by a pre-existing error */
  1201.         if (!PyErr_Occurred())
  1202.             PyErr_SetString(PyExc_SystemError,
  1203.                     "null file for PyFile_WriteString");
  1204.         return -1;
  1205.     }
  1206.     else if (PyFile_Check(f)) {
  1207.         FILE *fp = PyFile_AsFile(f);
  1208.         if (fp == NULL) {
  1209.             err_closed();
  1210.             return -1;
  1211.         }
  1212.         fputs(s, fp);
  1213.         return 0;
  1214.     }
  1215.     else if (!PyErr_Occurred()) {
  1216.         PyObject *v = PyString_FromString(s);
  1217.         int err;
  1218.         if (v == NULL)
  1219.             return -1;
  1220.         err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
  1221.         Py_DECREF(v);
  1222.         return err;
  1223.     }
  1224.     else
  1225.         return -1;
  1226. }
  1227.  
  1228. /* Try to get a file-descriptor from a Python object.  If the object
  1229.    is an integer or long integer, its value is returned.  If not, the
  1230.    object's fileno() method is called if it exists; the method must return
  1231.    an integer or long integer, which is returned as the file descriptor value.
  1232.    -1 is returned on failure.
  1233. */
  1234.  
  1235. int PyObject_AsFileDescriptor(PyObject *o)
  1236. {
  1237.     int fd;
  1238.     PyObject *meth;
  1239.  
  1240.     if (PyInt_Check(o)) {
  1241.         fd = PyInt_AsLong(o);
  1242.     }
  1243.     else if (PyLong_Check(o)) {
  1244.         fd = PyLong_AsLong(o);
  1245.     }
  1246.     else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
  1247.     {
  1248.         PyObject *fno = PyEval_CallObject(meth, NULL);
  1249.         Py_DECREF(meth);
  1250.         if (fno == NULL)
  1251.             return -1;
  1252.         
  1253.         if (PyInt_Check(fno)) {
  1254.             fd = PyInt_AsLong(fno);
  1255.             Py_DECREF(fno);
  1256.         }
  1257.         else if (PyLong_Check(fno)) {
  1258.             fd = PyLong_AsLong(fno);
  1259.             Py_DECREF(fno);
  1260.         }
  1261.         else {
  1262.             PyErr_SetString(PyExc_TypeError,
  1263.                     "fileno() returned a non-integer");
  1264.             Py_DECREF(fno);
  1265.             return -1;
  1266.         }
  1267.     }
  1268.     else {
  1269.         PyErr_SetString(PyExc_TypeError,
  1270.                 "argument must be an int, or have a fileno() method.");
  1271.         return -1;
  1272.     }
  1273.  
  1274.     if (fd < 0) {
  1275.         PyErr_Format(PyExc_ValueError,
  1276.                  "file descriptor cannot be a negative integer (%i)",
  1277.                  fd);
  1278.         return -1;
  1279.     }
  1280.     return fd;
  1281. }
  1282.  
  1283.  
  1284.  
  1285.