liolib.c 12 KB

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