2
0

liolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. ** $Id: liolib.c,v 2.56 2004/08/09 14:35:59 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) && lua_type(L, lua_upvalueindex(1)) == LUA_TTABLE)
  82. lua_rawgeti(L, lua_upvalueindex(1), 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_upvalueindex(1), 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_upvalueindex(1), f);
  135. }
  136. /* return current value */
  137. lua_rawgeti(L, lua_upvalueindex(1), 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 close) {
  148. lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
  149. lua_pushvalue(L, idx);
  150. lua_pushboolean(L, close); /* close/not close file when finished */
  151. lua_pushcclosure(L, io_readline, 3);
  152. }
  153. static int f_lines (lua_State *L) {
  154. tofile(L); /* check that it's a valid file handle */
  155. aux_lines(L, 1, 0);
  156. return 1;
  157. }
  158. static int io_lines (lua_State *L) {
  159. if (lua_isnoneornil(L, 1)) { /* no arguments? */
  160. /* will iterate over default input */
  161. lua_rawgeti(L, lua_upvalueindex(1), IO_INPUT);
  162. return f_lines(L);
  163. }
  164. else {
  165. const char *filename = luaL_checkstring(L, 1);
  166. FILE **pf = newfile(L);
  167. *pf = fopen(filename, "r");
  168. if (*pf == NULL)
  169. fileerror(L, 1, filename);
  170. aux_lines(L, lua_gettop(L), 1);
  171. return 1;
  172. }
  173. }
  174. /*
  175. ** {======================================================
  176. ** READ
  177. ** =======================================================
  178. */
  179. static int read_number (lua_State *L, FILE *f) {
  180. lua_Number d;
  181. if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
  182. lua_pushnumber(L, d);
  183. return 1;
  184. }
  185. else return 0; /* read fails */
  186. }
  187. static int test_eof (lua_State *L, FILE *f) {
  188. int c = getc(f);
  189. ungetc(c, f);
  190. lua_pushlstring(L, NULL, 0);
  191. return (c != EOF);
  192. }
  193. static int read_line (lua_State *L, FILE *f) {
  194. luaL_Buffer b;
  195. luaL_buffinit(L, &b);
  196. for (;;) {
  197. size_t l;
  198. char *p = luaL_prepbuffer(&b);
  199. if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
  200. luaL_pushresult(&b); /* close buffer */
  201. return (lua_strlen(L, -1) > 0); /* check whether read something */
  202. }
  203. l = strlen(p);
  204. if (p[l-1] != '\n')
  205. luaL_addsize(&b, l);
  206. else {
  207. luaL_addsize(&b, l - 1); /* do not include `eol' */
  208. luaL_pushresult(&b); /* close buffer */
  209. return 1; /* read at least an `eol' */
  210. }
  211. }
  212. }
  213. static int read_chars (lua_State *L, FILE *f, size_t n) {
  214. size_t rlen; /* how much to read */
  215. size_t nr; /* number of chars actually read */
  216. luaL_Buffer b;
  217. luaL_buffinit(L, &b);
  218. rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
  219. do {
  220. char *p = luaL_prepbuffer(&b);
  221. if (rlen > n) rlen = n; /* cannot read more than asked */
  222. nr = fread(p, sizeof(char), rlen, f);
  223. luaL_addsize(&b, nr);
  224. n -= nr; /* still have to read `n' chars */
  225. } while (n > 0 && nr == rlen); /* until end of count or eof */
  226. luaL_pushresult(&b); /* close buffer */
  227. return (n == 0 || lua_strlen(L, -1) > 0);
  228. }
  229. static int g_read (lua_State *L, FILE *f, int first) {
  230. int nargs = lua_gettop(L) - 1;
  231. int success;
  232. int n;
  233. clearerr(f);
  234. if (nargs == 0) { /* no arguments? */
  235. success = read_line(L, f);
  236. n = first+1; /* to return 1 result */
  237. }
  238. else { /* ensure stack space for all results and for auxlib's buffer */
  239. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  240. success = 1;
  241. for (n = first; nargs-- && success; n++) {
  242. if (lua_type(L, n) == LUA_TNUMBER) {
  243. size_t l = (size_t)lua_tointeger(L, n);
  244. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  245. }
  246. else {
  247. const char *p = lua_tostring(L, n);
  248. luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
  249. switch (p[1]) {
  250. case 'n': /* number */
  251. success = read_number(L, f);
  252. break;
  253. case 'l': /* line */
  254. success = read_line(L, f);
  255. break;
  256. case 'a': /* file */
  257. read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
  258. success = 1; /* always success */
  259. break;
  260. case 'w': /* word */
  261. return luaL_error(L, "obsolete option `*w' to `read'");
  262. default:
  263. return luaL_argerror(L, n, "invalid format");
  264. }
  265. }
  266. }
  267. }
  268. if (ferror(f))
  269. return pushresult(L, 0, NULL);
  270. if (!success) {
  271. lua_pop(L, 1); /* remove last result */
  272. lua_pushnil(L); /* push nil instead */
  273. }
  274. return n - first;
  275. }
  276. static int io_read (lua_State *L) {
  277. return g_read(L, getiofile(L, IO_INPUT), 1);
  278. }
  279. static int f_read (lua_State *L) {
  280. return g_read(L, tofile(L), 2);
  281. }
  282. static int io_readline (lua_State *L) {
  283. FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(2));
  284. int sucess;
  285. if (f == NULL) /* file is already closed? */
  286. luaL_error(L, "file is already closed");
  287. sucess = read_line(L, f);
  288. if (ferror(f))
  289. luaL_error(L, "%s", strerror(errno));
  290. if (sucess) return 1;
  291. else { /* EOF */
  292. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  293. lua_settop(L, 0);
  294. lua_pushvalue(L, lua_upvalueindex(2));
  295. aux_close(L); /* close it */
  296. }
  297. return 0;
  298. }
  299. }
  300. /* }====================================================== */
  301. static int g_write (lua_State *L, FILE *f, int arg) {
  302. int nargs = lua_gettop(L) - 1;
  303. int status = 1;
  304. for (; nargs--; arg++) {
  305. if (lua_type(L, arg) == LUA_TNUMBER) {
  306. /* optimization: could be done exactly as for strings */
  307. status = status &&
  308. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  309. }
  310. else {
  311. size_t l;
  312. const char *s = luaL_checklstring(L, arg, &l);
  313. status = status && (fwrite(s, sizeof(char), l, f) == l);
  314. }
  315. }
  316. return pushresult(L, status, NULL);
  317. }
  318. static int io_write (lua_State *L) {
  319. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  320. }
  321. static int f_write (lua_State *L) {
  322. return g_write(L, tofile(L), 2);
  323. }
  324. static int f_seek (lua_State *L) {
  325. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  326. static const char *const modenames[] = {"set", "cur", "end", NULL};
  327. FILE *f = tofile(L);
  328. int op = luaL_findstring(luaL_optstring(L, 2, "cur"), modenames);
  329. lua_Integer offset = luaL_optinteger(L, 3, 0);
  330. luaL_argcheck(L, op != -1, 2, "invalid mode");
  331. op = fseek(f, offset, mode[op]);
  332. if (op)
  333. return pushresult(L, 0, NULL); /* error */
  334. else {
  335. lua_pushinteger(L, ftell(f));
  336. return 1;
  337. }
  338. }
  339. static int f_setvbuf (lua_State *L) {
  340. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  341. static const char *const modenames[] = {"no", "full", "line", NULL};
  342. FILE *f = tofile(L);
  343. int op = luaL_findstring(luaL_checkstring(L, 2), modenames);
  344. luaL_argcheck(L, op != -1, 2, "invalid mode");
  345. return pushresult(L, setvbuf(f, NULL, mode[op], 0) == 0, NULL);
  346. }
  347. static int io_flush (lua_State *L) {
  348. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  349. }
  350. static int f_flush (lua_State *L) {
  351. return pushresult(L, fflush(tofile(L)) == 0, NULL);
  352. }
  353. static const luaL_reg iolib[] = {
  354. {"input", io_input},
  355. {"output", io_output},
  356. {"lines", io_lines},
  357. {"close", io_close},
  358. {"flush", io_flush},
  359. {"open", io_open},
  360. {"read", io_read},
  361. {"tmpfile", io_tmpfile},
  362. {"type", io_type},
  363. {"write", io_write},
  364. {NULL, NULL}
  365. };
  366. static const luaL_reg flib[] = {
  367. {"flush", f_flush},
  368. {"read", f_read},
  369. {"lines", f_lines},
  370. {"seek", f_seek},
  371. {"setvbuf", f_setvbuf},
  372. {"write", f_write},
  373. {"close", io_close},
  374. {"__gc", io_gc},
  375. {"__tostring", io_tostring},
  376. {NULL, NULL}
  377. };
  378. static void createmeta (lua_State *L) {
  379. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  380. lua_pushvalue(L, -1); /* push metatable */
  381. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  382. luaL_openlib(L, NULL, flib, 0); /* file methods */
  383. }
  384. static void createupval (lua_State *L) {
  385. lua_newtable(L);
  386. /* create (and set) default files */
  387. *newfile(L) = stdin;
  388. lua_rawseti(L, -2, IO_INPUT);
  389. *newfile(L) = stdout;
  390. lua_rawseti(L, -2, IO_OUTPUT);
  391. }
  392. LUALIB_API int luaopen_io (lua_State *L) {
  393. createmeta(L);
  394. createupval(L);
  395. lua_pushvalue(L, -1);
  396. luaL_openlib(L, LUA_IOLIBNAME, iolib, 1);
  397. /* put predefined file handles into `io' table */
  398. lua_rawgeti(L, -2, IO_INPUT); /* get current input from metatable */
  399. lua_setfield(L, -2, "stdin"); /* io.stdin = metatable[IO_INPUT] */
  400. lua_rawgeti(L, -2, IO_OUTPUT); /* get current output from metatable */
  401. lua_setfield(L, -2, "stdout"); /* io.stdout = metatable[IO_OUTPUT] */
  402. *newfile(L) = stderr;
  403. lua_setfield(L, -2, "stderr"); /* io.stderr = newfile(stderr) */
  404. return 1;
  405. }