liolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /*
  2. ** $Id: liolib.c,v 2.53 2004/05/28 18:35:05 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. char buff[4*sizeof(void *) + 8]; /* enough space for a `%p' */
  89. FILE **f = topfile(L);
  90. if (*f == NULL)
  91. strcpy(buff, "closed");
  92. else
  93. sprintf(buff, "%p", lua_touserdata(L, 1));
  94. lua_pushfstring(L, "file (%s)", buff);
  95. return 1;
  96. }
  97. static int io_open (lua_State *L) {
  98. const char *filename = luaL_checkstring(L, 1);
  99. const char *mode = luaL_optstring(L, 2, "r");
  100. FILE **pf = newfile(L);
  101. *pf = fopen(filename, mode);
  102. return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
  103. }
  104. static int io_tmpfile (lua_State *L) {
  105. FILE **pf = newfile(L);
  106. *pf = tmpfile();
  107. return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
  108. }
  109. static FILE *getiofile (lua_State *L, int findex) {
  110. FILE *f;
  111. lua_rawgeti(L, lua_upvalueindex(1), findex);
  112. lua_assert(luaL_checkudata(L, -1, LUA_FILEHANDLE));
  113. f = *(FILE **)lua_touserdata(L, -1);
  114. if (f == NULL)
  115. luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
  116. return f;
  117. }
  118. static int g_iofile (lua_State *L, int f, const char *mode) {
  119. if (!lua_isnoneornil(L, 1)) {
  120. const char *filename = lua_tostring(L, 1);
  121. if (filename) {
  122. FILE **pf = newfile(L);
  123. *pf = fopen(filename, mode);
  124. if (*pf == NULL) {
  125. lua_pushfstring(L, "%s: %s", filename, strerror(errno));
  126. luaL_argerror(L, 1, lua_tostring(L, -1));
  127. }
  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. luaL_argcheck(L, *pf, 1, strerror(errno));
  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. if (nargs == 0) { /* no arguments? */
  233. success = read_line(L, f);
  234. n = first+1; /* to return 1 result */
  235. }
  236. else { /* ensure stack space for all results and for auxlib's buffer */
  237. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  238. success = 1;
  239. for (n = first; nargs-- && success; n++) {
  240. if (lua_type(L, n) == LUA_TNUMBER) {
  241. size_t l = (size_t)lua_tointeger(L, n);
  242. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  243. }
  244. else {
  245. const char *p = lua_tostring(L, n);
  246. luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
  247. switch (p[1]) {
  248. case 'n': /* number */
  249. success = read_number(L, f);
  250. break;
  251. case 'l': /* line */
  252. success = read_line(L, f);
  253. break;
  254. case 'a': /* file */
  255. read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
  256. success = 1; /* always success */
  257. break;
  258. case 'w': /* word */
  259. return luaL_error(L, "obsolete option `*w' to `read'");
  260. default:
  261. return luaL_argerror(L, n, "invalid format");
  262. }
  263. }
  264. }
  265. }
  266. if (!success) {
  267. lua_pop(L, 1); /* remove last result */
  268. lua_pushnil(L); /* push nil instead */
  269. }
  270. return n - first;
  271. }
  272. static int io_read (lua_State *L) {
  273. return g_read(L, getiofile(L, IO_INPUT), 1);
  274. }
  275. static int f_read (lua_State *L) {
  276. return g_read(L, tofile(L), 2);
  277. }
  278. static int io_readline (lua_State *L) {
  279. FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(2));
  280. if (f == NULL) /* file is already closed? */
  281. luaL_error(L, "file is already closed");
  282. if (read_line(L, f)) return 1;
  283. else { /* EOF */
  284. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  285. lua_settop(L, 0);
  286. lua_pushvalue(L, lua_upvalueindex(2));
  287. aux_close(L); /* close it */
  288. }
  289. return 0;
  290. }
  291. }
  292. /* }====================================================== */
  293. static int g_write (lua_State *L, FILE *f, int arg) {
  294. int nargs = lua_gettop(L) - 1;
  295. int status = 1;
  296. for (; nargs--; arg++) {
  297. if (lua_type(L, arg) == LUA_TNUMBER) {
  298. /* optimization: could be done exactly as for strings */
  299. status = status &&
  300. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  301. }
  302. else {
  303. size_t l;
  304. const char *s = luaL_checklstring(L, arg, &l);
  305. status = status && (fwrite(s, sizeof(char), l, f) == l);
  306. }
  307. }
  308. return pushresult(L, status, NULL);
  309. }
  310. static int io_write (lua_State *L) {
  311. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  312. }
  313. static int f_write (lua_State *L) {
  314. return g_write(L, tofile(L), 2);
  315. }
  316. static int f_seek (lua_State *L) {
  317. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  318. static const char *const modenames[] = {"set", "cur", "end", NULL};
  319. FILE *f = tofile(L);
  320. int op = luaL_findstring(luaL_optstring(L, 2, "cur"), modenames);
  321. lua_Integer offset = luaL_optinteger(L, 3, 0);
  322. luaL_argcheck(L, op != -1, 2, "invalid mode");
  323. op = fseek(f, offset, mode[op]);
  324. if (op)
  325. return pushresult(L, 0, NULL); /* error */
  326. else {
  327. lua_pushinteger(L, ftell(f));
  328. return 1;
  329. }
  330. }
  331. static int f_setvbuf (lua_State *L) {
  332. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  333. static const char *const modenames[] = {"no", "full", "line", NULL};
  334. FILE *f = tofile(L);
  335. int op = luaL_findstring(luaL_checkstring(L, 2), modenames);
  336. luaL_argcheck(L, op != -1, 2, "invalid mode");
  337. return pushresult(L, setvbuf(f, NULL, mode[op], 0) == 0, NULL);
  338. }
  339. static int io_flush (lua_State *L) {
  340. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  341. }
  342. static int f_flush (lua_State *L) {
  343. return pushresult(L, fflush(tofile(L)) == 0, NULL);
  344. }
  345. static const luaL_reg iolib[] = {
  346. {"input", io_input},
  347. {"output", io_output},
  348. {"lines", io_lines},
  349. {"close", io_close},
  350. {"flush", io_flush},
  351. {"open", io_open},
  352. {"read", io_read},
  353. {"tmpfile", io_tmpfile},
  354. {"type", io_type},
  355. {"write", io_write},
  356. {NULL, NULL}
  357. };
  358. static const luaL_reg flib[] = {
  359. {"flush", f_flush},
  360. {"read", f_read},
  361. {"lines", f_lines},
  362. {"seek", f_seek},
  363. {"setvbuf", f_setvbuf},
  364. {"write", f_write},
  365. {"close", io_close},
  366. {"__gc", io_gc},
  367. {"__tostring", io_tostring},
  368. {NULL, NULL}
  369. };
  370. static void createmeta (lua_State *L) {
  371. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  372. lua_pushvalue(L, -1); /* push metatable */
  373. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  374. luaL_openlib(L, NULL, flib, 0); /* file methods */
  375. }
  376. static void createupval (lua_State *L) {
  377. lua_newtable(L);
  378. /* create (and set) default files */
  379. *newfile(L) = stdin;
  380. lua_rawseti(L, -2, IO_INPUT);
  381. *newfile(L) = stdout;
  382. lua_rawseti(L, -2, IO_OUTPUT);
  383. }
  384. LUALIB_API int luaopen_io (lua_State *L) {
  385. createmeta(L);
  386. createupval(L);
  387. lua_pushvalue(L, -1);
  388. luaL_openlib(L, LUA_IOLIBNAME, iolib, 1);
  389. /* put predefined file handles into `io' table */
  390. lua_rawgeti(L, -2, IO_INPUT); /* get current input from metatable */
  391. lua_setfield(L, -2, "stdin"); /* io.stdin = metatable[IO_INPUT] */
  392. lua_rawgeti(L, -2, IO_OUTPUT); /* get current output from metatable */
  393. lua_setfield(L, -2, "stdout"); /* io.stdout = metatable[IO_OUTPUT] */
  394. *newfile(L) = stderr;
  395. lua_setfield(L, -2, "stderr"); /* io.stderr = newfile(stderr) */
  396. return 1;
  397. }