liolib.c 22 KB

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