2
0

liolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. ** $Id: liolib.c,v 2.58 2005/02/18 12:40:02 roberto Exp roberto $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <errno.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #define liolib_c
  11. #define LUA_LIB
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. #define IO_INPUT 1
  16. #define IO_OUTPUT 2
  17. static const char *const fnames[] = {"input", "output"};
  18. static int pushresult (lua_State *L, int i, const char *filename) {
  19. if (i) {
  20. lua_pushboolean(L, 1);
  21. return 1;
  22. }
  23. else {
  24. lua_pushnil(L);
  25. if (filename)
  26. lua_pushfstring(L, "%s: %s", filename, strerror(errno));
  27. else
  28. lua_pushfstring(L, "%s", strerror(errno));
  29. lua_pushinteger(L, errno);
  30. return 3;
  31. }
  32. }
  33. static void fileerror (lua_State *L, int arg, const char *filename) {
  34. lua_pushfstring(L, "%s: %s", filename, strerror(errno));
  35. luaL_argerror(L, arg, lua_tostring(L, -1));
  36. }
  37. static FILE **topfile (lua_State *L) {
  38. FILE **f = (FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE);
  39. if (f == NULL) luaL_argerror(L, 1, "bad file");
  40. return f;
  41. }
  42. static int io_type (lua_State *L) {
  43. FILE **f = (FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE);
  44. if (f == NULL) lua_pushnil(L);
  45. else if (*f == NULL)
  46. lua_pushliteral(L, "closed file");
  47. else
  48. lua_pushliteral(L, "file");
  49. return 1;
  50. }
  51. static FILE *tofile (lua_State *L) {
  52. FILE **f = topfile(L);
  53. if (*f == NULL)
  54. luaL_error(L, "attempt to use a closed file");
  55. return *f;
  56. }
  57. /*
  58. ** When creating file handles, always creates a `closed' file handle
  59. ** before opening the actual file; so, if there is a memory error, the
  60. ** file is not left opened.
  61. */
  62. static FILE **newfile (lua_State *L) {
  63. FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
  64. *pf = NULL; /* file handle is currently `closed' */
  65. luaL_getmetatable(L, LUA_FILEHANDLE);
  66. lua_setmetatable(L, -2);
  67. return pf;
  68. }
  69. static int aux_close (lua_State *L) {
  70. FILE *f = tofile(L);
  71. if (f == stdin || f == stdout || f == stderr)
  72. return 0; /* file cannot be closed */
  73. else {
  74. int ok = (fclose(f) == 0);
  75. if (ok)
  76. *(FILE **)lua_touserdata(L, 1) = NULL; /* mark file as closed */
  77. return ok;
  78. }
  79. }
  80. static int io_close (lua_State *L) {
  81. if (lua_isnone(L, 1))
  82. lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
  83. return pushresult(L, aux_close(L), NULL);
  84. }
  85. static int io_gc (lua_State *L) {
  86. FILE **f = topfile(L);
  87. if (*f != NULL) /* ignore closed files */
  88. aux_close(L);
  89. return 0;
  90. }
  91. static int io_tostring (lua_State *L) {
  92. FILE *f = *topfile(L);
  93. if (f == NULL)
  94. lua_pushstring(L, "file (closed)");
  95. else
  96. lua_pushfstring(L, "file (%p)", f);
  97. return 1;
  98. }
  99. static int io_open (lua_State *L) {
  100. const char *filename = luaL_checkstring(L, 1);
  101. const char *mode = luaL_optstring(L, 2, "r");
  102. FILE **pf = newfile(L);
  103. *pf = fopen(filename, mode);
  104. return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
  105. }
  106. static int io_tmpfile (lua_State *L) {
  107. FILE **pf = newfile(L);
  108. *pf = tmpfile();
  109. return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
  110. }
  111. static FILE *getiofile (lua_State *L, int findex) {
  112. FILE *f;
  113. lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
  114. lua_assert(luaL_checkudata(L, -1, LUA_FILEHANDLE));
  115. f = *(FILE **)lua_touserdata(L, -1);
  116. if (f == NULL)
  117. luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
  118. return f;
  119. }
  120. static int g_iofile (lua_State *L, int f, const char *mode) {
  121. if (!lua_isnoneornil(L, 1)) {
  122. const char *filename = lua_tostring(L, 1);
  123. if (filename) {
  124. FILE **pf = newfile(L);
  125. *pf = fopen(filename, mode);
  126. if (*pf == NULL)
  127. fileerror(L, 1, filename);
  128. }
  129. else {
  130. tofile(L); /* check that it's a valid file handle */
  131. lua_pushvalue(L, 1);
  132. }
  133. lua_assert(luaL_checkudata(L, -1, LUA_FILEHANDLE));
  134. lua_rawseti(L, LUA_ENVIRONINDEX, f);
  135. }
  136. /* return current value */
  137. lua_rawgeti(L, LUA_ENVIRONINDEX, f);
  138. return 1;
  139. }
  140. static int io_input (lua_State *L) {
  141. return g_iofile(L, IO_INPUT, "r");
  142. }
  143. static int io_output (lua_State *L) {
  144. return g_iofile(L, IO_OUTPUT, "w");
  145. }
  146. static int io_readline (lua_State *L);
  147. static void aux_lines (lua_State *L, int idx, int toclose) {
  148. lua_pushvalue(L, idx);
  149. lua_pushboolean(L, toclose); /* close/not close file when finished */
  150. lua_pushcclosure(L, io_readline, 2);
  151. }
  152. static int f_lines (lua_State *L) {
  153. tofile(L); /* check that it's a valid file handle */
  154. aux_lines(L, 1, 0);
  155. return 1;
  156. }
  157. static int io_lines (lua_State *L) {
  158. if (lua_isnoneornil(L, 1)) { /* no arguments? */
  159. /* will iterate over default input */
  160. lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
  161. return f_lines(L);
  162. }
  163. else {
  164. const char *filename = luaL_checkstring(L, 1);
  165. FILE **pf = newfile(L);
  166. *pf = fopen(filename, "r");
  167. if (*pf == NULL)
  168. fileerror(L, 1, filename);
  169. aux_lines(L, lua_gettop(L), 1);
  170. return 1;
  171. }
  172. }
  173. /*
  174. ** {======================================================
  175. ** READ
  176. ** =======================================================
  177. */
  178. static int read_number (lua_State *L, FILE *f) {
  179. lua_Number d;
  180. if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
  181. lua_pushnumber(L, d);
  182. return 1;
  183. }
  184. else return 0; /* read fails */
  185. }
  186. static int test_eof (lua_State *L, FILE *f) {
  187. int c = getc(f);
  188. ungetc(c, f);
  189. lua_pushlstring(L, NULL, 0);
  190. return (c != EOF);
  191. }
  192. static int read_line (lua_State *L, FILE *f) {
  193. luaL_Buffer b;
  194. luaL_buffinit(L, &b);
  195. for (;;) {
  196. size_t l;
  197. char *p = luaL_prepbuffer(&b);
  198. if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
  199. luaL_pushresult(&b); /* close buffer */
  200. return (lua_strlen(L, -1) > 0); /* check whether read something */
  201. }
  202. l = strlen(p);
  203. if (p[l-1] != '\n')
  204. luaL_addsize(&b, l);
  205. else {
  206. luaL_addsize(&b, l - 1); /* do not include `eol' */
  207. luaL_pushresult(&b); /* close buffer */
  208. return 1; /* read at least an `eol' */
  209. }
  210. }
  211. }
  212. static int read_chars (lua_State *L, FILE *f, size_t n) {
  213. size_t rlen; /* how much to read */
  214. size_t nr; /* number of chars actually read */
  215. luaL_Buffer b;
  216. luaL_buffinit(L, &b);
  217. rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
  218. do {
  219. char *p = luaL_prepbuffer(&b);
  220. if (rlen > n) rlen = n; /* cannot read more than asked */
  221. nr = fread(p, sizeof(char), rlen, f);
  222. luaL_addsize(&b, nr);
  223. n -= nr; /* still have to read `n' chars */
  224. } while (n > 0 && nr == rlen); /* until end of count or eof */
  225. luaL_pushresult(&b); /* close buffer */
  226. return (n == 0 || lua_strlen(L, -1) > 0);
  227. }
  228. static int g_read (lua_State *L, FILE *f, int first) {
  229. int nargs = lua_gettop(L) - 1;
  230. int success;
  231. int n;
  232. clearerr(f);
  233. if (nargs == 0) { /* no arguments? */
  234. success = read_line(L, f);
  235. n = first+1; /* to return 1 result */
  236. }
  237. else { /* ensure stack space for all results and for auxlib's buffer */
  238. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  239. success = 1;
  240. for (n = first; nargs-- && success; n++) {
  241. if (lua_type(L, n) == LUA_TNUMBER) {
  242. size_t l = (size_t)lua_tointeger(L, n);
  243. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  244. }
  245. else {
  246. const char *p = lua_tostring(L, n);
  247. luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
  248. switch (p[1]) {
  249. case 'n': /* number */
  250. success = read_number(L, f);
  251. break;
  252. case 'l': /* line */
  253. success = read_line(L, f);
  254. break;
  255. case 'a': /* file */
  256. read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
  257. success = 1; /* always success */
  258. break;
  259. case 'w': /* word */
  260. return luaL_error(L, "obsolete option `*w' to `read'");
  261. default:
  262. return luaL_argerror(L, n, "invalid format");
  263. }
  264. }
  265. }
  266. }
  267. if (ferror(f))
  268. return pushresult(L, 0, NULL);
  269. if (!success) {
  270. lua_pop(L, 1); /* remove last result */
  271. lua_pushnil(L); /* push nil instead */
  272. }
  273. return n - first;
  274. }
  275. static int io_read (lua_State *L) {
  276. return g_read(L, getiofile(L, IO_INPUT), 1);
  277. }
  278. static int f_read (lua_State *L) {
  279. return g_read(L, tofile(L), 2);
  280. }
  281. static int io_readline (lua_State *L) {
  282. FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
  283. int sucess;
  284. if (f == NULL) /* file is already closed? */
  285. luaL_error(L, "file is already closed");
  286. sucess = read_line(L, f);
  287. if (ferror(f))
  288. luaL_error(L, "%s", strerror(errno));
  289. if (sucess) return 1;
  290. else { /* EOF */
  291. if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
  292. lua_settop(L, 0);
  293. lua_pushvalue(L, lua_upvalueindex(1));
  294. aux_close(L); /* close it */
  295. }
  296. return 0;
  297. }
  298. }
  299. /* }====================================================== */
  300. static int g_write (lua_State *L, FILE *f, int arg) {
  301. int nargs = lua_gettop(L) - 1;
  302. int status = 1;
  303. for (; nargs--; arg++) {
  304. if (lua_type(L, arg) == LUA_TNUMBER) {
  305. /* optimization: could be done exactly as for strings */
  306. status = status &&
  307. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  308. }
  309. else {
  310. size_t l;
  311. const char *s = luaL_checklstring(L, arg, &l);
  312. status = status && (fwrite(s, sizeof(char), l, f) == l);
  313. }
  314. }
  315. return pushresult(L, status, NULL);
  316. }
  317. static int io_write (lua_State *L) {
  318. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  319. }
  320. static int f_write (lua_State *L) {
  321. return g_write(L, tofile(L), 2);
  322. }
  323. static int f_seek (lua_State *L) {
  324. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  325. static const char *const modenames[] = {"set", "cur", "end", NULL};
  326. FILE *f = tofile(L);
  327. int op = luaL_findstring(luaL_optstring(L, 2, "cur"), modenames);
  328. lua_Integer offset = luaL_optinteger(L, 3, 0);
  329. luaL_argcheck(L, op != -1, 2, "invalid mode");
  330. op = fseek(f, offset, mode[op]);
  331. if (op)
  332. return pushresult(L, 0, NULL); /* error */
  333. else {
  334. lua_pushinteger(L, ftell(f));
  335. return 1;
  336. }
  337. }
  338. static int f_setvbuf (lua_State *L) {
  339. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  340. static const char *const modenames[] = {"no", "full", "line", NULL};
  341. FILE *f = tofile(L);
  342. int op = luaL_findstring(luaL_checkstring(L, 2), modenames);
  343. luaL_argcheck(L, op != -1, 2, "invalid mode");
  344. return pushresult(L, setvbuf(f, NULL, mode[op], 0) == 0, NULL);
  345. }
  346. static int io_flush (lua_State *L) {
  347. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  348. }
  349. static int f_flush (lua_State *L) {
  350. return pushresult(L, fflush(tofile(L)) == 0, NULL);
  351. }
  352. static const luaL_reg iolib[] = {
  353. {"input", io_input},
  354. {"output", io_output},
  355. {"lines", io_lines},
  356. {"close", io_close},
  357. {"flush", io_flush},
  358. {"open", io_open},
  359. {"read", io_read},
  360. {"tmpfile", io_tmpfile},
  361. {"type", io_type},
  362. {"write", io_write},
  363. {NULL, NULL}
  364. };
  365. static const luaL_reg flib[] = {
  366. {"flush", f_flush},
  367. {"read", f_read},
  368. {"lines", f_lines},
  369. {"seek", f_seek},
  370. {"setvbuf", f_setvbuf},
  371. {"write", f_write},
  372. {"close", io_close},
  373. {"__gc", io_gc},
  374. {"__tostring", io_tostring},
  375. {NULL, NULL}
  376. };
  377. static void createmeta (lua_State *L) {
  378. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  379. lua_pushvalue(L, -1); /* push metatable */
  380. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  381. luaL_openlib(L, NULL, flib, 0); /* file methods */
  382. }
  383. static void createupval (lua_State *L) {
  384. lua_newtable(L);
  385. /* create (and set) default files */
  386. *newfile(L) = stdin;
  387. lua_rawseti(L, -2, IO_INPUT);
  388. *newfile(L) = stdout;
  389. lua_rawseti(L, -2, IO_OUTPUT);
  390. }
  391. LUALIB_API int luaopen_io (lua_State *L) {
  392. createmeta(L);
  393. createupval(L);
  394. lua_pushvalue(L, -1);
  395. lua_replace(L, LUA_ENVIRONINDEX);
  396. luaL_openlib(L, LUA_IOLIBNAME, iolib, 0);
  397. /* put predefined file handles into `io' table */
  398. lua_rawgeti(L, -2, IO_INPUT); /* get current input from upval */
  399. lua_setfield(L, -2, "stdin"); /* io.stdin = upval[IO_INPUT] */
  400. lua_rawgeti(L, -2, IO_OUTPUT); /* get current output from upval */
  401. lua_setfield(L, -2, "stdout"); /* io.stdout = upval[IO_OUTPUT] */
  402. *newfile(L) = stderr;
  403. lua_setfield(L, -2, "stderr"); /* io.stderr = newfile(stderr) */
  404. return 1;
  405. }