liolib.c 19 KB

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