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
23 #define NO_READ_NUMBER 1
25 #define NO_CLEAR_ERR 1
27 #define NO_F_SETVBUF 1
33 static const char *const fnames
[] = {"input", "output"};
36 static int pushresult (lua_State
*L
, int i
, const char *filename
) {
37 int en
= errno
; /* calls to Lua API may change this value */
39 lua_pushboolean(L
, 1);
45 lua_pushfstring(L
, "%s: %s", filename
, strerror(en
));
47 lua_pushfstring(L
, "%s", strerror(en
));
48 lua_pushinteger(L
, en
);
54 static void fileerror (lua_State
*L
, int arg
, const char *filename
) {
55 lua_pushfstring(L
, "%s: %s", filename
, strerror(errno
));
56 luaL_argerror(L
, arg
, lua_tostring(L
, -1));
60 #define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
63 static int io_type (lua_State
*L
) {
66 ud
= lua_touserdata(L
, 1);
67 lua_getfield(L
, LUA_REGISTRYINDEX
, LUA_FILEHANDLE
);
68 if (ud
== NULL
|| !lua_getmetatable(L
, 1) || !lua_rawequal(L
, -2, -1))
69 lua_pushnil(L
); /* not a file */
70 else if (*((FILE **)ud
) == NULL
)
71 lua_pushliteral(L
, "closed file");
73 lua_pushliteral(L
, "file");
78 static FILE *tofile (lua_State
*L
) {
79 FILE **f
= tofilep(L
);
81 luaL_error(L
, "attempt to use a closed file");
88 ** When creating file handles, always creates a `closed' file handle
89 ** before opening the actual file; so, if there is a memory error, the
90 ** file is not left opened.
92 static FILE **newfile (lua_State
*L
) {
93 FILE **pf
= (FILE **)lua_newuserdata(L
, sizeof(FILE *));
94 *pf
= NULL
; /* file handle is currently `closed' */
95 luaL_getmetatable(L
, LUA_FILEHANDLE
);
96 lua_setmetatable(L
, -2);
102 ** function to (not) close the standard files stdin, stdout, and stderr
104 static int io_noclose (lua_State
*L
) {
106 lua_pushliteral(L
, "cannot close standard file");
112 ** function to close 'popen' files
114 static int io_pclose (lua_State
*L
) {
115 FILE **p
= tofilep(L
);
116 int ok
= lua_pclose(L
, *p
);
118 return pushresult(L
, ok
, NULL
);
123 ** function to close regular files
125 static int io_fclose (lua_State
*L
) {
126 FILE **p
= tofilep(L
);
127 int ok
= (fclose(*p
) == 0);
129 return pushresult(L
, ok
, NULL
);
133 static int aux_close (lua_State
*L
) {
135 lua_getfield(L
, -1, "__close");
136 return (lua_tocfunction(L
, -1))(L
);
140 static int io_close (lua_State
*L
) {
141 if (lua_isnone(L
, 1))
142 lua_rawgeti(L
, LUA_ENVIRONINDEX
, IO_OUTPUT
);
143 tofile(L
); /* make sure argument is a file */
148 static int io_gc (lua_State
*L
) {
149 FILE *f
= *tofilep(L
);
150 /* ignore closed files */
157 static int io_tostring (lua_State
*L
) {
158 FILE *f
= *tofilep(L
);
160 lua_pushliteral(L
, "file (closed)");
162 lua_pushfstring(L
, "file (%p)", f
);
167 static int io_open (lua_State
*L
) {
168 const char *filename
= luaL_checkstring(L
, 1);
169 const char *mode
= luaL_optstring(L
, 2, "r");
170 FILE **pf
= newfile(L
);
171 *pf
= fopen(filename
, mode
);
172 return (*pf
== NULL
) ? pushresult(L
, 0, filename
) : 1;
177 ** this function has a separated environment, which defines the
178 ** correct __close for 'popen' files
180 static int io_popen (lua_State
*L
) {
181 const char *filename
= luaL_checkstring(L
, 1);
182 const char *mode
= luaL_optstring(L
, 2, "r");
183 FILE **pf
= newfile(L
);
184 *pf
= lua_popen(L
, filename
, mode
);
185 return (*pf
== NULL
) ? pushresult(L
, 0, filename
) : 1;
190 static int io_tmpfile (lua_State
*L
) {
191 FILE **pf
= newfile(L
);
193 return (*pf
== NULL
) ? pushresult(L
, 0, NULL
) : 1;
198 static FILE *getiofile (lua_State
*L
, int findex
) {
200 lua_rawgeti(L
, LUA_ENVIRONINDEX
, findex
);
201 f
= *(FILE **)lua_touserdata(L
, -1);
203 luaL_error(L
, "standard %s file is closed", fnames
[findex
- 1]);
208 static int g_iofile (lua_State
*L
, int f
, const char *mode
) {
209 if (!lua_isnoneornil(L
, 1)) {
210 const char *filename
= lua_tostring(L
, 1);
212 FILE **pf
= newfile(L
);
213 *pf
= fopen(filename
, mode
);
215 fileerror(L
, 1, filename
);
218 tofile(L
); /* check that it's a valid file handle */
221 lua_rawseti(L
, LUA_ENVIRONINDEX
, f
);
223 /* return current value */
224 lua_rawgeti(L
, LUA_ENVIRONINDEX
, f
);
229 static int io_input (lua_State
*L
) {
230 return g_iofile(L
, IO_INPUT
, "r");
234 static int io_output (lua_State
*L
) {
235 return g_iofile(L
, IO_OUTPUT
, "w");
239 static int io_readline (lua_State
*L
);
242 static void aux_lines (lua_State
*L
, int idx
, int toclose
) {
243 lua_pushvalue(L
, idx
);
244 lua_pushboolean(L
, toclose
); /* close/not close file when finished */
245 lua_pushcclosure(L
, io_readline
, 2);
249 static int f_lines (lua_State
*L
) {
250 tofile(L
); /* check that it's a valid file handle */
256 static int io_lines (lua_State
*L
) {
257 if (lua_isnoneornil(L
, 1)) { /* no arguments? */
258 /* will iterate over default input */
259 lua_rawgeti(L
, LUA_ENVIRONINDEX
, IO_INPUT
);
263 const char *filename
= luaL_checkstring(L
, 1);
264 FILE **pf
= newfile(L
);
265 *pf
= fopen(filename
, "r");
267 fileerror(L
, 1, filename
);
268 aux_lines(L
, lua_gettop(L
), 1);
275 ** {======================================================
277 ** =======================================================
280 #ifndef NO_READ_NUMBER /* No fscanf() and thus no read_number() */
281 static int read_number (lua_State
*L
, FILE *f
) {
283 if (fscanf(f
, LUA_NUMBER_SCAN
, &d
) == 1) {
284 lua_pushnumber(L
, d
);
288 lua_pushnil(L
); /* "result" to be removed */
289 return 0; /* read fails */
294 #ifndef NO_TEST_EOF /* no buffering -> no ungetc() -> no EOF test */
295 static int test_eof (lua_State
*L
, FILE *f
) {
298 lua_pushlstring(L
, NULL
, 0);
304 static int read_line (lua_State
*L
, FILE *f
) {
306 luaL_buffinit(L
, &b
);
309 char *p
= luaL_prepbuffer(&b
);
310 if (fgets(p
, LUAL_BUFFERSIZE
, f
) == NULL
) { /* eof? */
311 luaL_pushresult(&b
); /* close buffer */
312 return (lua_objlen(L
, -1) > 0); /* check whether read something */
315 if (l
== 0 || p
[l
-1] != '\n')
318 luaL_addsize(&b
, l
- 1); /* do not include `eol' */
319 luaL_pushresult(&b
); /* close buffer */
320 return 1; /* read at least an `eol' */
325 static int read_chars (lua_State
*L
, FILE *f
, size_t n
) {
326 size_t rlen
; /* how much to read */
327 size_t nr
; /* number of chars actually read */
329 luaL_buffinit(L
, &b
);
330 rlen
= LUAL_BUFFERSIZE
; /* try to read that much each time */
332 char *p
= luaL_prepbuffer(&b
);
333 if (rlen
> n
) rlen
= n
; /* cannot read more than asked */
334 nr
= fread(p
, sizeof(char), rlen
, f
);
335 luaL_addsize(&b
, nr
);
336 n
-= nr
; /* still have to read `n' chars */
337 } while (n
> 0 && nr
== rlen
); /* until end of count or eof */
338 luaL_pushresult(&b
); /* close buffer */
339 return (n
== 0 || lua_objlen(L
, -1) > 0);
342 static int g_read (lua_State
*L
, FILE *f
, int first
) {
343 int nargs
= lua_gettop(L
) - 1;
349 if (nargs
== 0) { /* no arguments? */
350 success
= read_line(L
, f
);
351 n
= first
+1; /* to return 1 result */
353 else { /* ensure stack space for all results and for auxlib's buffer */
354 luaL_checkstack(L
, nargs
+LUA_MINSTACK
, "too many arguments");
356 for (n
= first
; nargs
-- && success
; n
++) {
357 if (lua_type(L
, n
) == LUA_TNUMBER
) {
358 size_t l
= (size_t)lua_tointeger(L
, n
);
360 success
= (l
== 0) ? test_eof(L
, f
) : read_chars(L
, f
, l
);
361 #else /* we don't have test_eof defined */
362 success
= (l
== 0) ? 1 : read_chars(L
, f
, l
);
366 const char *p
= lua_tostring(L
, n
);
367 luaL_argcheck(L
, p
&& p
[0] == '*', n
, "invalid option");
369 case 'n': /* number */
370 #ifndef NO_READ_NUMBER
371 success
= read_number(L
, f
);
373 return luaL_argerror(L
, n
, "\"*number\" not supported");
377 success
= read_line(L
, f
);
380 read_chars(L
, f
, ~((size_t)0)); /* read MAX_SIZE_T chars */
381 success
= 1; /* always success */
384 return luaL_argerror(L
, n
, "invalid format");
390 return pushresult(L
, 0, NULL
);
392 lua_pop(L
, 1); /* remove last result */
393 lua_pushnil(L
); /* push nil instead */
399 static int io_read (lua_State
*L
) {
400 return g_read(L
, getiofile(L
, IO_INPUT
), 1);
404 static int f_read (lua_State
*L
) {
405 return g_read(L
, tofile(L
), 2);
409 static int io_readline (lua_State
*L
) {
410 FILE *f
= *(FILE **)lua_touserdata(L
, lua_upvalueindex(1));
412 if (f
== NULL
) /* file is already closed? */
413 luaL_error(L
, "file is already closed");
414 sucess
= read_line(L
, f
);
416 return luaL_error(L
, "%s", strerror(errno
));
417 if (sucess
) return 1;
419 if (lua_toboolean(L
, lua_upvalueindex(2))) { /* generator created file? */
421 lua_pushvalue(L
, lua_upvalueindex(1));
422 aux_close(L
); /* close it */
428 /* }====================================================== */
431 static int g_write (lua_State
*L
, FILE *f
, int arg
) {
432 int nargs
= lua_gettop(L
) - 1;
434 for (; nargs
--; arg
++) {
435 if (lua_type(L
, arg
) == LUA_TNUMBER
) {
436 /* optimization: could be done exactly as for strings */
438 fprintf(f
, LUA_NUMBER_FMT
, lua_tonumber(L
, arg
)) > 0;
442 const char *s
= luaL_checklstring(L
, arg
, &l
);
443 status
= status
&& (fwrite(s
, sizeof(char), l
, f
) == l
);
446 return pushresult(L
, status
, NULL
);
450 static int io_write (lua_State
*L
) {
451 return g_write(L
, getiofile(L
, IO_OUTPUT
), 1);
455 static int f_write (lua_State
*L
) {
456 return g_write(L
, tofile(L
), 2);
460 static int f_seek (lua_State
*L
) {
461 static const int mode
[] = {SEEK_SET
, SEEK_CUR
, SEEK_END
};
462 static const char *const modenames
[] = {"set", "cur", "end", NULL
};
464 int op
= luaL_checkoption(L
, 2, "cur", modenames
);
465 long offset
= luaL_optlong(L
, 3, 0);
466 op
= fseek(f
, offset
, mode
[op
]);
468 return pushresult(L
, 0, NULL
); /* error */
470 lua_pushinteger(L
, ftell(f
));
477 static int f_setvbuf (lua_State
*L
) {
478 static const int mode
[] = {_IONBF
, _IOFBF
, _IOLBF
};
479 static const char *const modenames
[] = {"no", "full", "line", NULL
};
481 int op
= luaL_checkoption(L
, 2, NULL
, modenames
);
482 lua_Integer sz
= luaL_optinteger(L
, 3, LUAL_BUFFERSIZE
);
483 int res
= setvbuf(f
, NULL
, mode
[op
], sz
);
484 return pushresult(L
, res
== 0, NULL
);
489 static int io_flush (lua_State
*L
) {
490 return pushresult(L
, fflush(getiofile(L
, IO_OUTPUT
)) == 0, NULL
);
494 static int f_flush (lua_State
*L
) {
495 return pushresult(L
, fflush(tofile(L
)) == 0, NULL
);
499 static const luaL_Reg iolib
[] = {
505 {"output", io_output
},
509 {"tmpfile", io_tmpfile
},
517 static const luaL_Reg flib
[] = {
526 {"setvbuf", f_setvbuf
},
530 {"__tostring", io_tostring
},
535 static void createmeta (lua_State
*L
) {
536 luaL_newmetatable(L
, LUA_FILEHANDLE
); /* create metatable for file handles */
537 lua_pushvalue(L
, -1); /* push metatable */
538 lua_setfield(L
, -2, "__index"); /* metatable.__index = metatable */
539 luaL_register(L
, NULL
, flib
); /* file methods */
543 static void createstdfile (lua_State
*L
, FILE *f
, int k
, const char *fname
) {
546 lua_pushvalue(L
, -1);
547 lua_rawseti(L
, LUA_ENVIRONINDEX
, k
);
549 lua_pushvalue(L
, -2); /* copy environment */
550 lua_setfenv(L
, -2); /* set it */
551 lua_setfield(L
, -3, fname
);
555 static void newfenv (lua_State
*L
, lua_CFunction cls
) {
556 lua_createtable(L
, 0, 1);
557 lua_pushcfunction(L
, cls
);
558 lua_setfield(L
, -2, "__close");
562 LUALIB_API
int luaopen_io (lua_State
*L
) {
564 /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
565 newfenv(L
, io_fclose
);
566 lua_replace(L
, LUA_ENVIRONINDEX
);
568 luaL_register(L
, LUA_IOLIBNAME
, iolib
);
569 /* create (and set) default files */
570 newfenv(L
, io_noclose
); /* close function for default files */
571 createstdfile(L
, stdin
, IO_INPUT
, "stdin");
572 createstdfile(L
, stdout
, IO_OUTPUT
, "stdout");
573 createstdfile(L
, stderr
, 0, "stderr");
574 lua_pop(L
, 1); /* pop environment for default files */
575 lua_getfield(L
, -1, "popen");
576 newfenv(L
, io_pclose
); /* create environment for 'popen' */
577 lua_setfenv(L
, -2); /* set fenv for 'popen' */
578 lua_pop(L
, 1); /* pop 'popen' */