liolib.c 20 KB

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