liolib.c 22 KB

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