liolib.c 19 KB

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