liolib.c 21 KB

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