liolib.c 19 KB

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