liolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*
  2. ** $Id: liolib.c,v 2.59 2005/03/18 18:01:14 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. default:
  260. return luaL_argerror(L, n, "invalid format");
  261. }
  262. }
  263. }
  264. }
  265. if (ferror(f))
  266. return pushresult(L, 0, NULL);
  267. if (!success) {
  268. lua_pop(L, 1); /* remove last result */
  269. lua_pushnil(L); /* push nil instead */
  270. }
  271. return n - first;
  272. }
  273. static int io_read (lua_State *L) {
  274. return g_read(L, getiofile(L, IO_INPUT), 1);
  275. }
  276. static int f_read (lua_State *L) {
  277. return g_read(L, tofile(L), 2);
  278. }
  279. static int io_readline (lua_State *L) {
  280. FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
  281. int sucess;
  282. if (f == NULL) /* file is already closed? */
  283. luaL_error(L, "file is already closed");
  284. sucess = read_line(L, f);
  285. if (ferror(f))
  286. luaL_error(L, "%s", strerror(errno));
  287. if (sucess) return 1;
  288. else { /* EOF */
  289. if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
  290. lua_settop(L, 0);
  291. lua_pushvalue(L, lua_upvalueindex(1));
  292. aux_close(L); /* close it */
  293. }
  294. return 0;
  295. }
  296. }
  297. /* }====================================================== */
  298. static int g_write (lua_State *L, FILE *f, int arg) {
  299. int nargs = lua_gettop(L) - 1;
  300. int status = 1;
  301. for (; nargs--; arg++) {
  302. if (lua_type(L, arg) == LUA_TNUMBER) {
  303. /* optimization: could be done exactly as for strings */
  304. status = status &&
  305. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  306. }
  307. else {
  308. size_t l;
  309. const char *s = luaL_checklstring(L, arg, &l);
  310. status = status && (fwrite(s, sizeof(char), l, f) == l);
  311. }
  312. }
  313. return pushresult(L, status, NULL);
  314. }
  315. static int io_write (lua_State *L) {
  316. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  317. }
  318. static int f_write (lua_State *L) {
  319. return g_write(L, tofile(L), 2);
  320. }
  321. static int f_seek (lua_State *L) {
  322. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  323. static const char *const modenames[] = {"set", "cur", "end", NULL};
  324. FILE *f = tofile(L);
  325. int op = luaL_findstring(luaL_optstring(L, 2, "cur"), modenames);
  326. lua_Integer offset = luaL_optinteger(L, 3, 0);
  327. luaL_argcheck(L, op != -1, 2, "invalid mode");
  328. op = fseek(f, offset, mode[op]);
  329. if (op)
  330. return pushresult(L, 0, NULL); /* error */
  331. else {
  332. lua_pushinteger(L, ftell(f));
  333. return 1;
  334. }
  335. }
  336. static int f_setvbuf (lua_State *L) {
  337. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  338. static const char *const modenames[] = {"no", "full", "line", NULL};
  339. FILE *f = tofile(L);
  340. int op = luaL_findstring(luaL_checkstring(L, 2), modenames);
  341. luaL_argcheck(L, op != -1, 2, "invalid mode");
  342. return pushresult(L, setvbuf(f, NULL, mode[op], 0) == 0, NULL);
  343. }
  344. static int io_flush (lua_State *L) {
  345. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  346. }
  347. static int f_flush (lua_State *L) {
  348. return pushresult(L, fflush(tofile(L)) == 0, NULL);
  349. }
  350. static const luaL_reg iolib[] = {
  351. {"input", io_input},
  352. {"output", io_output},
  353. {"lines", io_lines},
  354. {"close", io_close},
  355. {"flush", io_flush},
  356. {"open", io_open},
  357. {"read", io_read},
  358. {"tmpfile", io_tmpfile},
  359. {"type", io_type},
  360. {"write", io_write},
  361. {NULL, NULL}
  362. };
  363. static const luaL_reg flib[] = {
  364. {"flush", f_flush},
  365. {"read", f_read},
  366. {"lines", f_lines},
  367. {"seek", f_seek},
  368. {"setvbuf", f_setvbuf},
  369. {"write", f_write},
  370. {"close", io_close},
  371. {"__gc", io_gc},
  372. {"__tostring", io_tostring},
  373. {NULL, NULL}
  374. };
  375. static void createmeta (lua_State *L) {
  376. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  377. lua_pushvalue(L, -1); /* push metatable */
  378. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  379. luaL_openlib(L, NULL, flib, 0); /* file methods */
  380. }
  381. static void createupval (lua_State *L) {
  382. lua_newtable(L);
  383. /* create (and set) default files */
  384. *newfile(L) = stdin;
  385. lua_rawseti(L, -2, IO_INPUT);
  386. *newfile(L) = stdout;
  387. lua_rawseti(L, -2, IO_OUTPUT);
  388. }
  389. LUALIB_API int luaopen_io (lua_State *L) {
  390. createmeta(L);
  391. createupval(L);
  392. lua_pushvalue(L, -1);
  393. lua_replace(L, LUA_ENVIRONINDEX);
  394. luaL_openlib(L, LUA_IOLIBNAME, iolib, 0);
  395. /* put predefined file handles into `io' table */
  396. lua_rawgeti(L, -2, IO_INPUT); /* get current input from upval */
  397. lua_setfield(L, -2, "stdin"); /* io.stdin = upval[IO_INPUT] */
  398. lua_rawgeti(L, -2, IO_OUTPUT); /* get current output from upval */
  399. lua_setfield(L, -2, "stdout"); /* io.stdout = upval[IO_OUTPUT] */
  400. *newfile(L) = stderr;
  401. lua_setfield(L, -2, "stderr"); /* io.stderr = newfile(stderr) */
  402. return 1;
  403. }