liolib.c 19 KB

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