liolib.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. /*
  2. ** $Id: liolib.c,v 2.143 2015/03/06 19:09:08 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. /*
  312. ** Read a number: first reads a valid prefix of a numeral into a buffer.
  313. ** Then it calls 'lua_stringtonumber' to check whether the format is
  314. ** correct and to convert it to a Lua number
  315. */
  316. static int read_number (lua_State *L, FILE *f) {
  317. RN rn;
  318. int count = 0;
  319. int hex = 0;
  320. char decp[2];
  321. rn.f = f; rn.n = 0;
  322. decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
  323. decp[1] = '\0';
  324. l_lockfile(rn.f);
  325. do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
  326. test2(&rn, "-+"); /* optional signal */
  327. if (test2(&rn, "0")) {
  328. if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
  329. else count = 1; /* count initial '0' as a valid digit */
  330. }
  331. count += readdigits(&rn, hex); /* integral part */
  332. if (test2(&rn, decp)) /* decimal point? */
  333. count += readdigits(&rn, hex); /* fractional part */
  334. if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
  335. test2(&rn, "-+"); /* exponent signal */
  336. readdigits(&rn, 0); /* exponent digits */
  337. }
  338. ungetc(rn.c, rn.f); /* unread look-ahead char */
  339. l_unlockfile(rn.f);
  340. rn.buff[rn.n] = '\0'; /* finish string */
  341. if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
  342. return 1; /* ok */
  343. else { /* invalid format */
  344. lua_pushnil(L); /* "result" to be removed */
  345. return 0; /* read fails */
  346. }
  347. }
  348. static int test_eof (lua_State *L, FILE *f) {
  349. int c = getc(f);
  350. ungetc(c, f); /* no-op when c == EOF */
  351. lua_pushliteral(L, "");
  352. return (c != EOF);
  353. }
  354. static int read_line (lua_State *L, FILE *f, int chop) {
  355. luaL_Buffer b;
  356. int c = '\0';
  357. luaL_buffinit(L, &b);
  358. while (c != EOF && c != '\n') { /* repeat until end of line */
  359. char *buff = luaL_prepbuffer(&b); /* pre-allocate buffer */
  360. int i = 0;
  361. l_lockfile(f); /* no memory errors can happen inside the lock */
  362. while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
  363. buff[i++] = c;
  364. l_unlockfile(f);
  365. luaL_addsize(&b, i);
  366. }
  367. if (!chop && c == '\n') /* want a newline and have one? */
  368. luaL_addchar(&b, c); /* add ending newline to result */
  369. luaL_pushresult(&b); /* close buffer */
  370. /* return ok if read something (either a newline or something else) */
  371. return (c == '\n' || lua_rawlen(L, -1) > 0);
  372. }
  373. static void read_all (lua_State *L, FILE *f) {
  374. size_t nr;
  375. luaL_Buffer b;
  376. luaL_buffinit(L, &b);
  377. do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
  378. char *p = luaL_prepbuffsize(&b, LUAL_BUFFERSIZE);
  379. nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
  380. luaL_addsize(&b, nr);
  381. } while (nr == LUAL_BUFFERSIZE);
  382. luaL_pushresult(&b); /* close buffer */
  383. }
  384. static int read_chars (lua_State *L, FILE *f, size_t n) {
  385. size_t nr; /* number of chars actually read */
  386. char *p;
  387. luaL_Buffer b;
  388. luaL_buffinit(L, &b);
  389. p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
  390. nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
  391. luaL_addsize(&b, nr);
  392. luaL_pushresult(&b); /* close buffer */
  393. return (nr > 0); /* true iff read something */
  394. }
  395. static int g_read (lua_State *L, FILE *f, int first) {
  396. int nargs = lua_gettop(L) - 1;
  397. int success;
  398. int n;
  399. clearerr(f);
  400. if (nargs == 0) { /* no arguments? */
  401. success = read_line(L, f, 1);
  402. n = first+1; /* to return 1 result */
  403. }
  404. else { /* ensure stack space for all results and for auxlib's buffer */
  405. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  406. success = 1;
  407. for (n = first; nargs-- && success; n++) {
  408. if (lua_type(L, n) == LUA_TNUMBER) {
  409. size_t l = (size_t)luaL_checkinteger(L, n);
  410. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  411. }
  412. else {
  413. const char *p = luaL_checkstring(L, n);
  414. if (*p == '*') p++; /* skip optional '*' (for compatibility) */
  415. switch (*p) {
  416. case 'n': /* number */
  417. success = read_number(L, f);
  418. break;
  419. case 'l': /* line */
  420. success = read_line(L, f, 1);
  421. break;
  422. case 'L': /* line with end-of-line */
  423. success = read_line(L, f, 0);
  424. break;
  425. case 'a': /* file */
  426. read_all(L, f); /* read entire file */
  427. success = 1; /* always success */
  428. break;
  429. default:
  430. return luaL_argerror(L, n, "invalid format");
  431. }
  432. }
  433. }
  434. }
  435. if (ferror(f))
  436. return luaL_fileresult(L, 0, NULL);
  437. if (!success) {
  438. lua_pop(L, 1); /* remove last result */
  439. lua_pushnil(L); /* push nil instead */
  440. }
  441. return n - first;
  442. }
  443. static int io_read (lua_State *L) {
  444. return g_read(L, getiofile(L, IO_INPUT), 1);
  445. }
  446. static int f_read (lua_State *L) {
  447. return g_read(L, tofile(L), 2);
  448. }
  449. static int io_readline (lua_State *L) {
  450. LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
  451. int i;
  452. int n = (int)lua_tointeger(L, lua_upvalueindex(2));
  453. if (isclosed(p)) /* file is already closed? */
  454. return luaL_error(L, "file is already closed");
  455. lua_settop(L , 1);
  456. luaL_checkstack(L, n, "too many arguments");
  457. for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
  458. lua_pushvalue(L, lua_upvalueindex(3 + i));
  459. n = g_read(L, p->f, 2); /* 'n' is number of results */
  460. lua_assert(n > 0); /* should return at least a nil */
  461. if (lua_toboolean(L, -n)) /* read at least one value? */
  462. return n; /* return them */
  463. else { /* first result is nil: EOF or error */
  464. if (n > 1) { /* is there error information? */
  465. /* 2nd result is error message */
  466. return luaL_error(L, "%s", lua_tostring(L, -n + 1));
  467. }
  468. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  469. lua_settop(L, 0);
  470. lua_pushvalue(L, lua_upvalueindex(1));
  471. aux_close(L); /* close it */
  472. }
  473. return 0;
  474. }
  475. }
  476. /* }====================================================== */
  477. static int g_write (lua_State *L, FILE *f, int arg) {
  478. int nargs = lua_gettop(L) - arg;
  479. int status = 1;
  480. for (; nargs--; arg++) {
  481. if (lua_type(L, arg) == LUA_TNUMBER) {
  482. /* optimization: could be done exactly as for strings */
  483. int len = lua_isinteger(L, arg)
  484. ? fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg))
  485. : fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg));
  486. status = status && (len > 0);
  487. }
  488. else {
  489. size_t l;
  490. const char *s = luaL_checklstring(L, arg, &l);
  491. status = status && (fwrite(s, sizeof(char), l, f) == l);
  492. }
  493. }
  494. if (status) return 1; /* file handle already on stack top */
  495. else return luaL_fileresult(L, status, NULL);
  496. }
  497. static int io_write (lua_State *L) {
  498. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  499. }
  500. static int f_write (lua_State *L) {
  501. FILE *f = tofile(L);
  502. lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
  503. return g_write(L, f, 2);
  504. }
  505. static int f_seek (lua_State *L) {
  506. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  507. static const char *const modenames[] = {"set", "cur", "end", NULL};
  508. FILE *f = tofile(L);
  509. int op = luaL_checkoption(L, 2, "cur", modenames);
  510. lua_Integer p3 = luaL_optinteger(L, 3, 0);
  511. l_seeknum offset = (l_seeknum)p3;
  512. luaL_argcheck(L, (lua_Integer)offset == p3, 3,
  513. "not an integer in proper range");
  514. op = l_fseek(f, offset, mode[op]);
  515. if (op)
  516. return luaL_fileresult(L, 0, NULL); /* error */
  517. else {
  518. lua_pushinteger(L, (lua_Integer)l_ftell(f));
  519. return 1;
  520. }
  521. }
  522. static int f_setvbuf (lua_State *L) {
  523. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  524. static const char *const modenames[] = {"no", "full", "line", NULL};
  525. FILE *f = tofile(L);
  526. int op = luaL_checkoption(L, 2, NULL, modenames);
  527. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  528. int res = setvbuf(f, NULL, mode[op], (size_t)sz);
  529. return luaL_fileresult(L, res == 0, NULL);
  530. }
  531. static int io_flush (lua_State *L) {
  532. return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  533. }
  534. static int f_flush (lua_State *L) {
  535. return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
  536. }
  537. /*
  538. ** functions for 'io' library
  539. */
  540. static const luaL_Reg iolib[] = {
  541. {"close", io_close},
  542. {"flush", io_flush},
  543. {"input", io_input},
  544. {"lines", io_lines},
  545. {"open", io_open},
  546. {"output", io_output},
  547. {"popen", io_popen},
  548. {"read", io_read},
  549. {"tmpfile", io_tmpfile},
  550. {"type", io_type},
  551. {"write", io_write},
  552. {NULL, NULL}
  553. };
  554. /*
  555. ** methods for file handles
  556. */
  557. static const luaL_Reg flib[] = {
  558. {"close", io_close},
  559. {"flush", f_flush},
  560. {"lines", f_lines},
  561. {"read", f_read},
  562. {"seek", f_seek},
  563. {"setvbuf", f_setvbuf},
  564. {"write", f_write},
  565. {"__gc", f_gc},
  566. {"__tostring", f_tostring},
  567. {NULL, NULL}
  568. };
  569. static void createmeta (lua_State *L) {
  570. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  571. lua_pushvalue(L, -1); /* push metatable */
  572. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  573. luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
  574. lua_pop(L, 1); /* pop new metatable */
  575. }
  576. /*
  577. ** function to (not) close the standard files stdin, stdout, and stderr
  578. */
  579. static int io_noclose (lua_State *L) {
  580. LStream *p = tolstream(L);
  581. p->closef = &io_noclose; /* keep file opened */
  582. lua_pushnil(L);
  583. lua_pushliteral(L, "cannot close standard file");
  584. return 2;
  585. }
  586. static void createstdfile (lua_State *L, FILE *f, const char *k,
  587. const char *fname) {
  588. LStream *p = newprefile(L);
  589. p->f = f;
  590. p->closef = &io_noclose;
  591. if (k != NULL) {
  592. lua_pushvalue(L, -1);
  593. lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
  594. }
  595. lua_setfield(L, -2, fname); /* add file to module */
  596. }
  597. LUAMOD_API int luaopen_io (lua_State *L) {
  598. luaL_newlib(L, iolib); /* new module */
  599. createmeta(L);
  600. /* create (and set) default files */
  601. createstdfile(L, stdin, IO_INPUT, "stdin");
  602. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  603. createstdfile(L, stderr, NULL, "stderr");
  604. return 1;
  605. }