liolib.c 21 KB

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