2 ** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
29 static const char *const fnames[] = {"input", "output"};
32 static int pushresult (lua_State *L, int i, const char *filename) {
33 int en = errno; /* calls to Lua API may change this value */
35 lua_pushboolean(L, 1);
41 lua_pushfstring(L, "%s: %s", filename, strerror(en));
43 lua_pushfstring(L, "%s", strerror(en));
44 lua_pushinteger(L, en);
50 static void fileerror (lua_State *L, int arg, const char *filename) {
51 lua_pushfstring(L, "%s: %s", filename, strerror(errno));
52 luaL_argerror(L, arg, lua_tostring(L, -1));
56 #define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
59 static int io_type (lua_State *L) {
62 ud = lua_touserdata(L, 1);
63 lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
64 if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
65 lua_pushnil(L); /* not a file */
66 else if (*((FILE **)ud) == NULL)
67 lua_pushliteral(L, "closed file");
69 lua_pushliteral(L, "file");
74 static FILE *tofile (lua_State *L) {
75 FILE **f = tofilep(L);
77 luaL_error(L, "attempt to use a closed file");
84 ** When creating file handles, always creates a `closed' file handle
85 ** before opening the actual file; so, if there is a memory error, the
86 ** file is not left opened.
88 static FILE **newfile (lua_State *L) {
89 FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
90 *pf = NULL; /* file handle is currently `closed' */
91 luaL_getmetatable(L, LUA_FILEHANDLE);
92 lua_setmetatable(L, -2);
98 ** function to (not) close the standard files stdin, stdout, and stderr
100 static int io_noclose (lua_State *L) {
102 lua_pushliteral(L, "cannot close standard file");
108 ** function to close 'popen' files
110 static int io_pclose (lua_State *L) {
111 FILE **p = tofilep(L);
112 int ok = lua_pclose(L, *p);
114 return pushresult(L, ok, NULL);
119 ** function to close regular files
121 static int io_fclose (lua_State *L) {
122 FILE **p = tofilep(L);
123 int ok = (fclose(*p) == 0);
125 return pushresult(L, ok, NULL);
129 static int aux_close (lua_State *L) {
131 lua_getfield(L, -1, "__close");
132 return (lua_tocfunction(L, -1))(L);
136 static int io_close (lua_State *L) {
137 if (lua_isnone(L, 1))
138 lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
139 tofile(L); /* make sure argument is a file */
144 static int io_gc (lua_State *L) {
145 FILE *f = *tofilep(L);
146 /* ignore closed files */
153 static int io_tostring (lua_State *L) {
154 FILE *f = *tofilep(L);
156 lua_pushliteral(L, "file (closed)");
158 lua_pushfstring(L, "file (%p)", f);
163 static int io_open (lua_State *L) {
164 const char *filename = luaL_checkstring(L, 1);
165 const char *mode = luaL_optstring(L, 2, "r");
166 FILE **pf = newfile(L);
167 *pf = fopen(filename, mode);
168 return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
173 ** this function has a separated environment, which defines the
174 ** correct __close for 'popen' files
176 static int io_popen (lua_State *L) {
177 const char *filename = luaL_checkstring(L, 1);
178 const char *mode = luaL_optstring(L, 2, "r");
179 FILE **pf = newfile(L);
180 *pf = lua_popen(L, filename, mode);
181 return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
185 static int io_tmpfile (lua_State *L) {
186 FILE **pf = newfile(L);
188 return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
192 static FILE *getiofile (lua_State *L, int findex) {
194 lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
195 f = *(FILE **)lua_touserdata(L, -1);
197 luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
202 static int g_iofile (lua_State *L, int f, const char *mode) {
203 if (!lua_isnoneornil(L, 1)) {
204 const char *filename = lua_tostring(L, 1);
206 FILE **pf = newfile(L);
207 *pf = fopen(filename, mode);
209 fileerror(L, 1, filename);
212 tofile(L); /* check that it's a valid file handle */
215 lua_rawseti(L, LUA_ENVIRONINDEX, f);
217 /* return current value */
218 lua_rawgeti(L, LUA_ENVIRONINDEX, f);
223 static int io_input (lua_State *L) {
224 return g_iofile(L, IO_INPUT, "r");
228 static int io_output (lua_State *L) {
229 return g_iofile(L, IO_OUTPUT, "w");
233 static int io_readline (lua_State *L);
236 static void aux_lines (lua_State *L, int idx, int toclose) {
237 lua_pushvalue(L, idx);
238 lua_pushboolean(L, toclose); /* close/not close file when finished */
239 lua_pushcclosure(L, io_readline, 2);
243 static int f_lines (lua_State *L) {
244 tofile(L); /* check that it's a valid file handle */
250 static int io_lines (lua_State *L) {
251 if (lua_isnoneornil(L, 1)) { /* no arguments? */
252 /* will iterate over default input */
253 lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
257 const char *filename = luaL_checkstring(L, 1);
258 FILE **pf = newfile(L);
259 *pf = fopen(filename, "r");
261 fileerror(L, 1, filename);
262 aux_lines(L, lua_gettop(L), 1);
269 ** {======================================================
271 ** =======================================================
275 * NOTE: Lua's usual '*n' format specifier reads numbers as floating point,
276 * and converts to integer if they are. IN ORDER TO NOT LOSE ACCURACY,
277 * a new '*i' format specifier is added (will also be speedier, on non-
281 static int read_number (lua_State *L, FILE *f) {
283 if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
286 lua_number2integer(tmp, d);
287 if (cast_num(tmp) == d)
288 lua_pushinteger(L, tmp);
291 lua_pushnumber(L, d);
295 lua_pushnil(L); /* "result" to be removed */
296 return 0; /* read fails */
300 static int read_integer (lua_State *L, FILE *f) {
302 if (fscanf(f, LUA_INTEGER_SCAN, &i) == 1) {
303 lua_pushinteger(L, i);
306 else return 0; /* read fails */
310 static int read_complex (lua_State *L, FILE *f) {
311 /* NNN / NNNi / NNN+MMMi / NNN-MMMi */
313 if (fscanf(f, LUA_NUMBER_SCAN, &a) == 1) {
317 lua_pushcomplex(L, a*I);
321 /* "i" is consumed if at the end; just 'NNN+MMM' will most likely
322 * behave as if "i" was there? (TBD: test)
324 if (fscanf(f, LUA_NUMBER_SCAN "i", &b) == 1) {
325 lua_pushcomplex(L, a+ (c=='+' ? b:-b)*I);
330 lua_pushnumber(L,a); /*real part only*/
333 return 0; /* read fails */
338 static int test_eof (lua_State *L, FILE *f) {
341 lua_pushlstring(L, NULL, 0);
346 static int read_line (lua_State *L, FILE *f) {
348 luaL_buffinit(L, &b);
351 char *p = luaL_prepbuffer(&b);
352 if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
353 luaL_pushresult(&b); /* close buffer */
354 return (lua_objlen(L, -1) > 0); /* check whether read something */
357 if (l == 0 || p[l-1] != '\n')
360 luaL_addsize(&b, l - 1); /* do not include `eol' */
361 luaL_pushresult(&b); /* close buffer */
362 return 1; /* read at least an `eol' */
368 static int read_chars (lua_State *L, FILE *f, size_t n) {
369 size_t rlen; /* how much to read */
370 size_t nr; /* number of chars actually read */
372 luaL_buffinit(L, &b);
373 rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
375 char *p = luaL_prepbuffer(&b);
376 if (rlen > n) rlen = n; /* cannot read more than asked */
377 nr = fread(p, sizeof(char), rlen, f);
378 luaL_addsize(&b, nr);
379 n -= nr; /* still have to read `n' chars */
380 } while (n > 0 && nr == rlen); /* until end of count or eof */
381 luaL_pushresult(&b); /* close buffer */
382 return (n == 0 || lua_objlen(L, -1) > 0);
386 static int g_read (lua_State *L, FILE *f, int first) {
387 int nargs = lua_gettop(L) - 1;
391 if (nargs == 0) { /* no arguments? */
392 success = read_line(L, f);
393 n = first+1; /* to return 1 result */
395 else { /* ensure stack space for all results and for auxlib's buffer */
396 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
398 for (n = first; nargs-- && success; n++) {
399 if (lua_type(L, n) == LUA_TNUMBER) {
400 size_t l = (size_t)lua_tointeger(L, n);
401 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
404 const char *p = lua_tostring(L, n);
405 luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
407 case 'n': /* number */
408 success = read_number(L, f);
410 case 'i': /* integer (full accuracy) */
411 success = read_integer(L, f);
414 case 'c': /* complex */
415 success = read_complex(L, f);
419 success = read_line(L, f);
422 read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
423 success = 1; /* always success */
426 return luaL_argerror(L, n, "invalid format");
432 return pushresult(L, 0, NULL);
434 lua_pop(L, 1); /* remove last result */
435 lua_pushnil(L); /* push nil instead */
441 static int io_read (lua_State *L) {
442 return g_read(L, getiofile(L, IO_INPUT), 1);
446 static int f_read (lua_State *L) {
447 return g_read(L, tofile(L), 2);
451 static int io_readline (lua_State *L) {
452 FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
454 if (f == NULL) /* file is already closed? */
455 luaL_error(L, "file is already closed");
456 sucess = read_line(L, f);
458 return luaL_error(L, "%s", strerror(errno));
459 if (sucess) return 1;
461 if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
463 lua_pushvalue(L, lua_upvalueindex(1));
464 aux_close(L); /* close it */
470 /* }====================================================== */
473 static int g_write (lua_State *L, FILE *f, int arg) {
474 int nargs = lua_gettop(L) - 1;
476 for (; nargs--; arg++) {
477 if (lua_type(L, arg) == LUA_TNUMBER) {
478 if (lua_isinteger(L,arg))
479 status = status && fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg)) > 0;
481 status = status && fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
485 const char *s = luaL_checklstring(L, arg, &l);
486 status = status && (fwrite(s, sizeof(char), l, f) == l);
489 return pushresult(L, status, NULL);
493 static int io_write (lua_State *L) {
494 return g_write(L, getiofile(L, IO_OUTPUT), 1);
498 static int f_write (lua_State *L) {
499 return g_write(L, tofile(L), 2);
503 static int f_seek (lua_State *L) {
504 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
505 static const char *const modenames[] = {"set", "cur", "end", NULL};
507 int op = luaL_checkoption(L, 2, "cur", modenames);
508 long offset = luaL_optlong(L, 3, 0);
509 op = fseek(f, offset, mode[op]);
511 return pushresult(L, 0, NULL); /* error */
513 lua_pushinteger(L, ftell(f));
519 static int f_setvbuf (lua_State *L) {
520 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
521 static const char *const modenames[] = {"no", "full", "line", NULL};
523 int op = luaL_checkoption(L, 2, NULL, modenames);
524 size_t sz = luaL_optint32(L, 3, LUAL_BUFFERSIZE);
525 int res = setvbuf(f, NULL, mode[op], sz);
526 return pushresult(L, res == 0, NULL);
531 static int io_flush (lua_State *L) {
532 return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
536 static int f_flush (lua_State *L) {
537 return pushresult(L, fflush(tofile(L)) == 0, NULL);
541 static const luaL_Reg iolib[] = {
547 {"output", io_output},
550 {"tmpfile", io_tmpfile},
557 static const luaL_Reg flib[] = {
563 {"setvbuf", f_setvbuf},
566 {"__tostring", io_tostring},
571 static void createmeta (lua_State *L) {
572 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
573 lua_pushvalue(L, -1); /* push metatable */
574 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
575 luaL_register(L, NULL, flib); /* file methods */
579 static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
582 lua_pushvalue(L, -1);
583 lua_rawseti(L, LUA_ENVIRONINDEX, k);
585 lua_pushvalue(L, -2); /* copy environment */
586 lua_setfenv(L, -2); /* set it */
587 lua_setfield(L, -3, fname);
591 static void newfenv (lua_State *L, lua_CFunction cls) {
592 lua_createtable(L, 0, 1);
593 lua_pushcfunction(L, cls);
594 lua_setfield(L, -2, "__close");
598 LUALIB_API int luaopen_io (lua_State *L) {
600 /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
601 newfenv(L, io_fclose);
602 lua_replace(L, LUA_ENVIRONINDEX);
604 luaL_register(L, LUA_IOLIBNAME, iolib);
605 /* create (and set) default files */
606 newfenv(L, io_noclose); /* close function for default files */
607 createstdfile(L, stdin, IO_INPUT, "stdin");
608 createstdfile(L, stdout, IO_OUTPUT, "stdout");
609 createstdfile(L, stderr, 0, "stderr");
610 lua_pop(L, 1); /* pop environment for default files */
611 lua_getfield(L, -1, "popen");
612 newfenv(L, io_pclose); /* create environment for 'popen' */
613 lua_setfenv(L, -2); /* set fenv for 'popen' */
614 lua_pop(L, 1); /* pop 'popen' */