lua

A copy of the Lua development repository
Log | Files | Refs | README

liolib.c (22069B)


      1 /*
      2 ** $Id: liolib.c $
      3 ** Standard I/O (and system) library
      4 ** See Copyright Notice in lua.h
      5 */
      6 
      7 #define liolib_c
      8 #define LUA_LIB
      9 
     10 #include "lprefix.h"
     11 
     12 
     13 #include <ctype.h>
     14 #include <errno.h>
     15 #include <locale.h>
     16 #include <stdio.h>
     17 #include <stdlib.h>
     18 #include <string.h>
     19 
     20 #include "lua.h"
     21 
     22 #include "lauxlib.h"
     23 #include "lualib.h"
     24 #include "llimits.h"
     25 
     26 
     27 /*
     28 ** Change this macro to accept other modes for 'fopen' besides
     29 ** the standard ones.
     30 */
     31 #if !defined(l_checkmode)
     32 
     33 /* accepted extensions to 'mode' in 'fopen' */
     34 #if !defined(L_MODEEXT)
     35 #define L_MODEEXT	"b"
     36 #endif
     37 
     38 /* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
     39 static int l_checkmode (const char *mode) {
     40   return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
     41          (*mode != '+' || ((void)(++mode), 1)) &&  /* skip if char is '+' */
     42          (strspn(mode, L_MODEEXT) == strlen(mode)));  /* check extensions */
     43 }
     44 
     45 #endif
     46 
     47 /*
     48 ** {======================================================
     49 ** l_popen spawns a new process connected to the current
     50 ** one through the file streams.
     51 ** =======================================================
     52 */
     53 
     54 #if !defined(l_popen)		/* { */
     55 
     56 #if defined(LUA_USE_POSIX)	/* { */
     57 
     58 #define l_popen(L,c,m)		(fflush(NULL), popen(c,m))
     59 #define l_pclose(L,file)	(pclose(file))
     60 
     61 #elif defined(LUA_USE_WINDOWS)	/* }{ */
     62 
     63 #define l_popen(L,c,m)		(_popen(c,m))
     64 #define l_pclose(L,file)	(_pclose(file))
     65 
     66 #if !defined(l_checkmodep)
     67 /* Windows accepts "[rw][bt]?" as valid modes */
     68 #define l_checkmodep(m)	((m[0] == 'r' || m[0] == 'w') && \
     69   (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
     70 #endif
     71 
     72 #else				/* }{ */
     73 
     74 /* ISO C definitions */
     75 #define l_popen(L,c,m)  \
     76 	  ((void)c, (void)m, \
     77 	  luaL_error(L, "'popen' not supported"), \
     78 	  (FILE*)0)
     79 #define l_pclose(L,file)		((void)L, (void)file, -1)
     80 
     81 #endif				/* } */
     82 
     83 #endif				/* } */
     84 
     85 
     86 #if !defined(l_checkmodep)
     87 /* By default, Lua accepts only "r" or "w" as valid modes */
     88 #define l_checkmodep(m)        ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
     89 #endif
     90 
     91 /* }====================================================== */
     92 
     93 
     94 #if !defined(l_getc)		/* { */
     95 
     96 #if defined(LUA_USE_POSIX)
     97 #define l_getc(f)		getc_unlocked(f)
     98 #define l_lockfile(f)		flockfile(f)
     99 #define l_unlockfile(f)		funlockfile(f)
    100 #else
    101 #define l_getc(f)		getc(f)
    102 #define l_lockfile(f)		((void)0)
    103 #define l_unlockfile(f)		((void)0)
    104 #endif
    105 
    106 #endif				/* } */
    107 
    108 
    109 /*
    110 ** {======================================================
    111 ** l_fseek: configuration for longer offsets
    112 ** =======================================================
    113 */
    114 
    115 #if !defined(l_fseek)		/* { */
    116 
    117 #if defined(LUA_USE_POSIX)	/* { */
    118 
    119 #include <sys/types.h>
    120 
    121 #define l_fseek(f,o,w)		fseeko(f,o,w)
    122 #define l_ftell(f)		ftello(f)
    123 #define l_seeknum		off_t
    124 
    125 #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
    126    && defined(_MSC_VER) && (_MSC_VER >= 1400)	/* }{ */
    127 
    128 /* Windows (but not DDK) and Visual C++ 2005 or higher */
    129 #define l_fseek(f,o,w)		_fseeki64(f,o,w)
    130 #define l_ftell(f)		_ftelli64(f)
    131 #define l_seeknum		__int64
    132 
    133 #else				/* }{ */
    134 
    135 /* ISO C definitions */
    136 #define l_fseek(f,o,w)		fseek(f,o,w)
    137 #define l_ftell(f)		ftell(f)
    138 #define l_seeknum		long
    139 
    140 #endif				/* } */
    141 
    142 #endif				/* } */
    143 
    144 /* }====================================================== */
    145 
    146 
    147 
    148 #define IO_PREFIX	"_IO_"
    149 #define IOPREF_LEN	(sizeof(IO_PREFIX)/sizeof(char) - 1)
    150 #define IO_INPUT	(IO_PREFIX "input")
    151 #define IO_OUTPUT	(IO_PREFIX "output")
    152 
    153 
    154 typedef luaL_Stream LStream;
    155 
    156 
    157 #define tolstream(L)	((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
    158 
    159 #define isclosed(p)	((p)->closef == NULL)
    160 
    161 
    162 static int io_type (lua_State *L) {
    163   LStream *p;
    164   luaL_checkany(L, 1);
    165   p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
    166   if (p == NULL)
    167     luaL_pushfail(L);  /* not a file */
    168   else if (isclosed(p))
    169     lua_pushliteral(L, "closed file");
    170   else
    171     lua_pushliteral(L, "file");
    172   return 1;
    173 }
    174 
    175 
    176 static int f_tostring (lua_State *L) {
    177   LStream *p = tolstream(L);
    178   if (isclosed(p))
    179     lua_pushliteral(L, "file (closed)");
    180   else
    181     lua_pushfstring(L, "file (%p)", p->f);
    182   return 1;
    183 }
    184 
    185 
    186 static FILE *tofile (lua_State *L) {
    187   LStream *p = tolstream(L);
    188   if (l_unlikely(isclosed(p)))
    189     luaL_error(L, "attempt to use a closed file");
    190   lua_assert(p->f);
    191   return p->f;
    192 }
    193 
    194 
    195 /*
    196 ** When creating file handles, always creates a 'closed' file handle
    197 ** before opening the actual file; so, if there is a memory error, the
    198 ** handle is in a consistent state.
    199 */
    200 static LStream *newprefile (lua_State *L) {
    201   LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);
    202   p->closef = NULL;  /* mark file handle as 'closed' */
    203   luaL_setmetatable(L, LUA_FILEHANDLE);
    204   return p;
    205 }
    206 
    207 
    208 /*
    209 ** Calls the 'close' function from a file handle. The 'volatile' avoids
    210 ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
    211 ** 32 bits).
    212 */
    213 static int aux_close (lua_State *L) {
    214   LStream *p = tolstream(L);
    215   volatile lua_CFunction cf = p->closef;
    216   p->closef = NULL;  /* mark stream as closed */
    217   return (*cf)(L);  /* close it */
    218 }
    219 
    220 
    221 static int f_close (lua_State *L) {
    222   tofile(L);  /* make sure argument is an open stream */
    223   return aux_close(L);
    224 }
    225 
    226 
    227 static int io_close (lua_State *L) {
    228   if (lua_isnone(L, 1))  /* no argument? */
    229     lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT);  /* use default output */
    230   return f_close(L);
    231 }
    232 
    233 
    234 static int f_gc (lua_State *L) {
    235   LStream *p = tolstream(L);
    236   if (!isclosed(p) && p->f != NULL)
    237     aux_close(L);  /* ignore closed and incompletely open files */
    238   return 0;
    239 }
    240 
    241 
    242 /*
    243 ** function to close regular files
    244 */
    245 static int io_fclose (lua_State *L) {
    246   LStream *p = tolstream(L);
    247   errno = 0;
    248   return luaL_fileresult(L, (fclose(p->f) == 0), NULL);
    249 }
    250 
    251 
    252 static LStream *newfile (lua_State *L) {
    253   LStream *p = newprefile(L);
    254   p->f = NULL;
    255   p->closef = &io_fclose;
    256   return p;
    257 }
    258 
    259 
    260 static void opencheck (lua_State *L, const char *fname, const char *mode) {
    261   LStream *p = newfile(L);
    262   p->f = fopen(fname, mode);
    263   if (l_unlikely(p->f == NULL))
    264     luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
    265 }
    266 
    267 
    268 static int io_open (lua_State *L) {
    269   const char *filename = luaL_checkstring(L, 1);
    270   const char *mode = luaL_optstring(L, 2, "r");
    271   LStream *p = newfile(L);
    272   const char *md = mode;  /* to traverse/check mode */
    273   luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
    274   errno = 0;
    275   p->f = fopen(filename, mode);
    276   return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
    277 }
    278 
    279 
    280 /*
    281 ** function to close 'popen' files
    282 */
    283 static int io_pclose (lua_State *L) {
    284   LStream *p = tolstream(L);
    285   errno = 0;
    286   return luaL_execresult(L, l_pclose(L, p->f));
    287 }
    288 
    289 
    290 static int io_popen (lua_State *L) {
    291   const char *filename = luaL_checkstring(L, 1);
    292   const char *mode = luaL_optstring(L, 2, "r");
    293   LStream *p = newprefile(L);
    294   luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
    295   errno = 0;
    296   p->f = l_popen(L, filename, mode);
    297   p->closef = &io_pclose;
    298   return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
    299 }
    300 
    301 
    302 static int io_tmpfile (lua_State *L) {
    303   LStream *p = newfile(L);
    304   errno = 0;
    305   p->f = tmpfile();
    306   return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
    307 }
    308 
    309 
    310 static FILE *getiofile (lua_State *L, const char *findex) {
    311   LStream *p;
    312   lua_getfield(L, LUA_REGISTRYINDEX, findex);
    313   p = (LStream *)lua_touserdata(L, -1);
    314   if (l_unlikely(isclosed(p)))
    315     luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
    316   return p->f;
    317 }
    318 
    319 
    320 static int g_iofile (lua_State *L, const char *f, const char *mode) {
    321   if (!lua_isnoneornil(L, 1)) {
    322     const char *filename = lua_tostring(L, 1);
    323     if (filename)
    324       opencheck(L, filename, mode);
    325     else {
    326       tofile(L);  /* check that it's a valid file handle */
    327       lua_pushvalue(L, 1);
    328     }
    329     lua_setfield(L, LUA_REGISTRYINDEX, f);
    330   }
    331   /* return current value */
    332   lua_getfield(L, LUA_REGISTRYINDEX, f);
    333   return 1;
    334 }
    335 
    336 
    337 static int io_input (lua_State *L) {
    338   return g_iofile(L, IO_INPUT, "r");
    339 }
    340 
    341 
    342 static int io_output (lua_State *L) {
    343   return g_iofile(L, IO_OUTPUT, "w");
    344 }
    345 
    346 
    347 static int io_readline (lua_State *L);
    348 
    349 
    350 /*
    351 ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
    352 ** in the limit for upvalues of a closure)
    353 */
    354 #define MAXARGLINE	250
    355 
    356 /*
    357 ** Auxiliary function to create the iteration function for 'lines'.
    358 ** The iteration function is a closure over 'io_readline', with
    359 ** the following upvalues:
    360 ** 1) The file being read (first value in the stack)
    361 ** 2) the number of arguments to read
    362 ** 3) a boolean, true iff file has to be closed when finished ('toclose')
    363 ** *) a variable number of format arguments (rest of the stack)
    364 */
    365 static void aux_lines (lua_State *L, int toclose) {
    366   int n = lua_gettop(L) - 1;  /* number of arguments to read */
    367   luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
    368   lua_pushvalue(L, 1);  /* file */
    369   lua_pushinteger(L, n);  /* number of arguments to read */
    370   lua_pushboolean(L, toclose);  /* close/not close file when finished */
    371   lua_rotate(L, 2, 3);  /* move the three values to their positions */
    372   lua_pushcclosure(L, io_readline, 3 + n);
    373 }
    374 
    375 
    376 static int f_lines (lua_State *L) {
    377   tofile(L);  /* check that it's a valid file handle */
    378   aux_lines(L, 0);
    379   return 1;
    380 }
    381 
    382 
    383 /*
    384 ** Return an iteration function for 'io.lines'. If file has to be
    385 ** closed, also returns the file itself as a second result (to be
    386 ** closed as the state at the exit of a generic for).
    387 */
    388 static int io_lines (lua_State *L) {
    389   int toclose;
    390   if (lua_isnone(L, 1)) lua_pushnil(L);  /* at least one argument */
    391   if (lua_isnil(L, 1)) {  /* no file name? */
    392     lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT);  /* get default input */
    393     lua_replace(L, 1);  /* put it at index 1 */
    394     tofile(L);  /* check that it's a valid file handle */
    395     toclose = 0;  /* do not close it after iteration */
    396   }
    397   else {  /* open a new file */
    398     const char *filename = luaL_checkstring(L, 1);
    399     opencheck(L, filename, "r");
    400     lua_replace(L, 1);  /* put file at index 1 */
    401     toclose = 1;  /* close it after iteration */
    402   }
    403   aux_lines(L, toclose);  /* push iteration function */
    404   if (toclose) {
    405     lua_pushnil(L);  /* state */
    406     lua_pushnil(L);  /* control */
    407     lua_pushvalue(L, 1);  /* file is the to-be-closed variable (4th result) */
    408     return 4;
    409   }
    410   else
    411     return 1;
    412 }
    413 
    414 
    415 /*
    416 ** {======================================================
    417 ** READ
    418 ** =======================================================
    419 */
    420 
    421 
    422 /* maximum length of a numeral */
    423 #if !defined (L_MAXLENNUM)
    424 #define L_MAXLENNUM     200
    425 #endif
    426 
    427 
    428 /* auxiliary structure used by 'read_number' */
    429 typedef struct {
    430   FILE *f;  /* file being read */
    431   int c;  /* current character (look ahead) */
    432   int n;  /* number of elements in buffer 'buff' */
    433   char buff[L_MAXLENNUM + 1];  /* +1 for ending '\0' */
    434 } RN;
    435 
    436 
    437 /*
    438 ** Add current char to buffer (if not out of space) and read next one
    439 */
    440 static int nextc (RN *rn) {
    441   if (l_unlikely(rn->n >= L_MAXLENNUM)) {  /* buffer overflow? */
    442     rn->buff[0] = '\0';  /* invalidate result */
    443     return 0;  /* fail */
    444   }
    445   else {
    446     rn->buff[rn->n++] = cast_char(rn->c);  /* save current char */
    447     rn->c = l_getc(rn->f);  /* read next one */
    448     return 1;
    449   }
    450 }
    451 
    452 
    453 /*
    454 ** Accept current char if it is in 'set' (of size 2)
    455 */
    456 static int test2 (RN *rn, const char *set) {
    457   if (rn->c == set[0] || rn->c == set[1])
    458     return nextc(rn);
    459   else return 0;
    460 }
    461 
    462 
    463 /*
    464 ** Read a sequence of (hex)digits
    465 */
    466 static int readdigits (RN *rn, int hex) {
    467   int count = 0;
    468   while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
    469     count++;
    470   return count;
    471 }
    472 
    473 
    474 /*
    475 ** Read a number: first reads a valid prefix of a numeral into a buffer.
    476 ** Then it calls 'lua_stringtonumber' to check whether the format is
    477 ** correct and to convert it to a Lua number.
    478 */
    479 static int read_number (lua_State *L, FILE *f) {
    480   RN rn;
    481   int count = 0;
    482   int hex = 0;
    483   char decp[2];
    484   rn.f = f; rn.n = 0;
    485   decp[0] = lua_getlocaledecpoint();  /* get decimal point from locale */
    486   decp[1] = '.';  /* always accept a dot */
    487   l_lockfile(rn.f);
    488   do { rn.c = l_getc(rn.f); } while (isspace(rn.c));  /* skip spaces */
    489   test2(&rn, "-+");  /* optional sign */
    490   if (test2(&rn, "00")) {
    491     if (test2(&rn, "xX")) hex = 1;  /* numeral is hexadecimal */
    492     else count = 1;  /* count initial '0' as a valid digit */
    493   }
    494   count += readdigits(&rn, hex);  /* integral part */
    495   if (test2(&rn, decp))  /* decimal point? */
    496     count += readdigits(&rn, hex);  /* fractional part */
    497   if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) {  /* exponent mark? */
    498     test2(&rn, "-+");  /* exponent sign */
    499     readdigits(&rn, 0);  /* exponent digits */
    500   }
    501   ungetc(rn.c, rn.f);  /* unread look-ahead char */
    502   l_unlockfile(rn.f);
    503   rn.buff[rn.n] = '\0';  /* finish string */
    504   if (l_likely(lua_stringtonumber(L, rn.buff)))
    505     return 1;  /* ok, it is a valid number */
    506   else {  /* invalid format */
    507    lua_pushnil(L);  /* "result" to be removed */
    508    return 0;  /* read fails */
    509   }
    510 }
    511 
    512 
    513 static int test_eof (lua_State *L, FILE *f) {
    514   int c = getc(f);
    515   ungetc(c, f);  /* no-op when c == EOF */
    516   lua_pushliteral(L, "");
    517   return (c != EOF);
    518 }
    519 
    520 
    521 static int read_line (lua_State *L, FILE *f, int chop) {
    522   luaL_Buffer b;
    523   int c;
    524   luaL_buffinit(L, &b);
    525   do {  /* may need to read several chunks to get whole line */
    526     char *buff = luaL_prepbuffer(&b);  /* preallocate buffer space */
    527     unsigned i = 0;
    528     l_lockfile(f);  /* no memory errors can happen inside the lock */
    529     while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
    530       buff[i++] = cast_char(c);  /* read up to end of line or buffer limit */
    531     l_unlockfile(f);
    532     luaL_addsize(&b, i);
    533   } while (c != EOF && c != '\n');  /* repeat until end of line */
    534   if (!chop && c == '\n')  /* want a newline and have one? */
    535     luaL_addchar(&b, '\n');  /* add ending newline to result */
    536   luaL_pushresult(&b);  /* close buffer */
    537   /* return ok if read something (either a newline or something else) */
    538   return (c == '\n' || lua_rawlen(L, -1) > 0);
    539 }
    540 
    541 
    542 static void read_all (lua_State *L, FILE *f) {
    543   size_t nr;
    544   luaL_Buffer b;
    545   luaL_buffinit(L, &b);
    546   do {  /* read file in chunks of LUAL_BUFFERSIZE bytes */
    547     char *p = luaL_prepbuffer(&b);
    548     nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
    549     luaL_addsize(&b, nr);
    550   } while (nr == LUAL_BUFFERSIZE);
    551   luaL_pushresult(&b);  /* close buffer */
    552 }
    553 
    554 
    555 static int read_chars (lua_State *L, FILE *f, size_t n) {
    556   size_t nr;  /* number of chars actually read */
    557   char *p;
    558   luaL_Buffer b;
    559   luaL_buffinit(L, &b);
    560   p = luaL_prepbuffsize(&b, n);  /* prepare buffer to read whole block */
    561   nr = fread(p, sizeof(char), n, f);  /* try to read 'n' chars */
    562   luaL_addsize(&b, nr);
    563   luaL_pushresult(&b);  /* close buffer */
    564   return (nr > 0);  /* true iff read something */
    565 }
    566 
    567 
    568 static int g_read (lua_State *L, FILE *f, int first) {
    569   int nargs = lua_gettop(L) - 1;
    570   int n, success;
    571   clearerr(f);
    572   errno = 0;
    573   if (nargs == 0) {  /* no arguments? */
    574     success = read_line(L, f, 1);
    575     n = first + 1;  /* to return 1 result */
    576   }
    577   else {
    578     /* ensure stack space for all results and for auxlib's buffer */
    579     luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
    580     success = 1;
    581     for (n = first; nargs-- && success; n++) {
    582       if (lua_type(L, n) == LUA_TNUMBER) {
    583         size_t l = (size_t)luaL_checkinteger(L, n);
    584         success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
    585       }
    586       else {
    587         const char *p = luaL_checkstring(L, n);
    588         if (*p == '*') p++;  /* skip optional '*' (for compatibility) */
    589         switch (*p) {
    590           case 'n':  /* number */
    591             success = read_number(L, f);
    592             break;
    593           case 'l':  /* line */
    594             success = read_line(L, f, 1);
    595             break;
    596           case 'L':  /* line with end-of-line */
    597             success = read_line(L, f, 0);
    598             break;
    599           case 'a':  /* file */
    600             read_all(L, f);  /* read entire file */
    601             success = 1; /* always success */
    602             break;
    603           default:
    604             return luaL_argerror(L, n, "invalid format");
    605         }
    606       }
    607     }
    608   }
    609   if (ferror(f))
    610     return luaL_fileresult(L, 0, NULL);
    611   if (!success) {
    612     lua_pop(L, 1);  /* remove last result */
    613     luaL_pushfail(L);  /* push nil instead */
    614   }
    615   return n - first;
    616 }
    617 
    618 
    619 static int io_read (lua_State *L) {
    620   return g_read(L, getiofile(L, IO_INPUT), 1);
    621 }
    622 
    623 
    624 static int f_read (lua_State *L) {
    625   return g_read(L, tofile(L), 2);
    626 }
    627 
    628 
    629 /*
    630 ** Iteration function for 'lines'.
    631 */
    632 static int io_readline (lua_State *L) {
    633   LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
    634   int i;
    635   int n = (int)lua_tointeger(L, lua_upvalueindex(2));
    636   if (isclosed(p))  /* file is already closed? */
    637     return luaL_error(L, "file is already closed");
    638   lua_settop(L , 1);
    639   luaL_checkstack(L, n, "too many arguments");
    640   for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */
    641     lua_pushvalue(L, lua_upvalueindex(3 + i));
    642   n = g_read(L, p->f, 2);  /* 'n' is number of results */
    643   lua_assert(n > 0);  /* should return at least a nil */
    644   if (lua_toboolean(L, -n))  /* read at least one value? */
    645     return n;  /* return them */
    646   else {  /* first result is false: EOF or error */
    647     if (n > 1) {  /* is there error information? */
    648       /* 2nd result is error message */
    649       return luaL_error(L, "%s", lua_tostring(L, -n + 1));
    650     }
    651     if (lua_toboolean(L, lua_upvalueindex(3))) {  /* generator created file? */
    652       lua_settop(L, 0);  /* clear stack */
    653       lua_pushvalue(L, lua_upvalueindex(1));  /* push file at index 1 */
    654       aux_close(L);  /* close it */
    655     }
    656     return 0;
    657   }
    658 }
    659 
    660 /* }====================================================== */
    661 
    662 
    663 static int g_write (lua_State *L, FILE *f, int arg) {
    664   int nargs = lua_gettop(L) - arg;
    665   int status = 1;
    666   errno = 0;
    667   for (; nargs--; arg++) {
    668     char buff[LUA_N2SBUFFSZ];
    669     const char *s;
    670     size_t len = lua_numbertocstring(L, arg, buff);  /* try as a number */
    671     if (len > 0) {  /* did conversion work (value was a number)? */
    672       s = buff;
    673       len--;
    674     }
    675     else  /* must be a string */
    676       s = luaL_checklstring(L, arg, &len);
    677     status = status && (fwrite(s, sizeof(char), len, f) == len);
    678   }
    679   if (l_likely(status))
    680     return 1;  /* file handle already on stack top */
    681   else
    682     return luaL_fileresult(L, status, NULL);
    683 }
    684 
    685 
    686 static int io_write (lua_State *L) {
    687   return g_write(L, getiofile(L, IO_OUTPUT), 1);
    688 }
    689 
    690 
    691 static int f_write (lua_State *L) {
    692   FILE *f = tofile(L);
    693   lua_pushvalue(L, 1);  /* push file at the stack top (to be returned) */
    694   return g_write(L, f, 2);
    695 }
    696 
    697 
    698 static int f_seek (lua_State *L) {
    699   static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
    700   static const char *const modenames[] = {"set", "cur", "end", NULL};
    701   FILE *f = tofile(L);
    702   int op = luaL_checkoption(L, 2, "cur", modenames);
    703   lua_Integer p3 = luaL_optinteger(L, 3, 0);
    704   l_seeknum offset = (l_seeknum)p3;
    705   luaL_argcheck(L, (lua_Integer)offset == p3, 3,
    706                   "not an integer in proper range");
    707   errno = 0;
    708   op = l_fseek(f, offset, mode[op]);
    709   if (l_unlikely(op))
    710     return luaL_fileresult(L, 0, NULL);  /* error */
    711   else {
    712     lua_pushinteger(L, (lua_Integer)l_ftell(f));
    713     return 1;
    714   }
    715 }
    716 
    717 
    718 static int f_setvbuf (lua_State *L) {
    719   static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
    720   static const char *const modenames[] = {"no", "full", "line", NULL};
    721   FILE *f = tofile(L);
    722   int op = luaL_checkoption(L, 2, NULL, modenames);
    723   lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
    724   int res;
    725   errno = 0;
    726   res = setvbuf(f, NULL, mode[op], (size_t)sz);
    727   return luaL_fileresult(L, res == 0, NULL);
    728 }
    729 
    730 
    731 
    732 static int io_flush (lua_State *L) {
    733   FILE *f = getiofile(L, IO_OUTPUT);
    734   errno = 0;
    735   return luaL_fileresult(L, fflush(f) == 0, NULL);
    736 }
    737 
    738 
    739 static int f_flush (lua_State *L) {
    740   FILE *f = tofile(L);
    741   errno = 0;
    742   return luaL_fileresult(L, fflush(f) == 0, NULL);
    743 }
    744 
    745 
    746 /*
    747 ** functions for 'io' library
    748 */
    749 static const luaL_Reg iolib[] = {
    750   {"close", io_close},
    751   {"flush", io_flush},
    752   {"input", io_input},
    753   {"lines", io_lines},
    754   {"open", io_open},
    755   {"output", io_output},
    756   {"popen", io_popen},
    757   {"read", io_read},
    758   {"tmpfile", io_tmpfile},
    759   {"type", io_type},
    760   {"write", io_write},
    761   {NULL, NULL}
    762 };
    763 
    764 
    765 /*
    766 ** methods for file handles
    767 */
    768 static const luaL_Reg meth[] = {
    769   {"read", f_read},
    770   {"write", f_write},
    771   {"lines", f_lines},
    772   {"flush", f_flush},
    773   {"seek", f_seek},
    774   {"close", f_close},
    775   {"setvbuf", f_setvbuf},
    776   {NULL, NULL}
    777 };
    778 
    779 
    780 /*
    781 ** metamethods for file handles
    782 */
    783 static const luaL_Reg metameth[] = {
    784   {"__index", NULL},  /* placeholder */
    785   {"__gc", f_gc},
    786   {"__close", f_gc},
    787   {"__tostring", f_tostring},
    788   {NULL, NULL}
    789 };
    790 
    791 
    792 static void createmeta (lua_State *L) {
    793   luaL_newmetatable(L, LUA_FILEHANDLE);  /* metatable for file handles */
    794   luaL_setfuncs(L, metameth, 0);  /* add metamethods to new metatable */
    795   luaL_newlibtable(L, meth);  /* create method table */
    796   luaL_setfuncs(L, meth, 0);  /* add file methods to method table */
    797   lua_setfield(L, -2, "__index");  /* metatable.__index = method table */
    798   lua_pop(L, 1);  /* pop metatable */
    799 }
    800 
    801 
    802 /*
    803 ** function to (not) close the standard files stdin, stdout, and stderr
    804 */
    805 static int io_noclose (lua_State *L) {
    806   LStream *p = tolstream(L);
    807   p->closef = &io_noclose;  /* keep file opened */
    808   luaL_pushfail(L);
    809   lua_pushliteral(L, "cannot close standard file");
    810   return 2;
    811 }
    812 
    813 
    814 static void createstdfile (lua_State *L, FILE *f, const char *k,
    815                            const char *fname) {
    816   LStream *p = newprefile(L);
    817   p->f = f;
    818   p->closef = &io_noclose;
    819   if (k != NULL) {
    820     lua_pushvalue(L, -1);
    821     lua_setfield(L, LUA_REGISTRYINDEX, k);  /* add file to registry */
    822   }
    823   lua_setfield(L, -2, fname);  /* add file to module */
    824 }
    825 
    826 
    827 LUAMOD_API int luaopen_io (lua_State *L) {
    828   luaL_newlib(L, iolib);  /* new module */
    829   createmeta(L);
    830   /* create (and set) default files */
    831   createstdfile(L, stdin, IO_INPUT, "stdin");
    832   createstdfile(L, stdout, IO_OUTPUT, "stdout");
    833   createstdfile(L, stderr, NULL, "stderr");
    834   return 1;
    835 }
    836