2 ** $Id: liolib.c,v 2.73.1.3 2008/01/18 17:47:43 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
27 static const char *const fnames
[] = {"input", "output"};
30 static int pushresult (lua_State
*L
, int i
, const char *filename
) {
31 int en
= errno
; /* calls to Lua API may change this value */
33 lua_pushboolean(L
, 1);
39 lua_pushfstring(L
, "%s: %s", filename
, strerror(en
));
41 lua_pushfstring(L
, "%s", strerror(en
));
42 lua_pushinteger(L
, en
);
48 static void fileerror (lua_State
*L
, int arg
, const char *filename
) {
49 lua_pushfstring(L
, "%s: %s", filename
, strerror(errno
));
50 luaL_argerror(L
, arg
, lua_tostring(L
, -1));
54 #define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
57 static int io_type (lua_State
*L
) {
60 ud
= lua_touserdata(L
, 1);
61 lua_getfield(L
, LUA_REGISTRYINDEX
, LUA_FILEHANDLE
);
62 if (ud
== NULL
|| !lua_getmetatable(L
, 1) || !lua_rawequal(L
, -2, -1))
63 lua_pushnil(L
); /* not a file */
64 else if (*((FILE **)ud
) == NULL
)
65 lua_pushliteral(L
, "closed file");
67 lua_pushliteral(L
, "file");
72 static FILE *tofile (lua_State
*L
) {
73 FILE **f
= tofilep(L
);
75 luaL_error(L
, "attempt to use a closed file");
82 ** When creating file handles, always creates a `closed' file handle
83 ** before opening the actual file; so, if there is a memory error, the
84 ** file is not left opened.
86 static FILE **newfile (lua_State
*L
) {
87 FILE **pf
= (FILE **)lua_newuserdata(L
, sizeof(FILE *));
88 *pf
= NULL
; /* file handle is currently `closed' */
89 luaL_getmetatable(L
, LUA_FILEHANDLE
);
90 lua_setmetatable(L
, -2);
96 ** function to (not) close the standard files stdin, stdout, and stderr
98 static int io_noclose (lua_State
*L
) {
100 lua_pushliteral(L
, "cannot close standard file");
106 ** function to close 'popen' files
108 static int io_pclose (lua_State
*L
) {
109 FILE **p
= tofilep(L
);
110 int ok
= lua_pclose(L
, *p
);
112 return pushresult(L
, ok
, NULL
);
117 ** function to close regular files
119 static int io_fclose (lua_State
*L
) {
120 FILE **p
= tofilep(L
);
121 int ok
= (fclose(*p
) == 0);
123 return pushresult(L
, ok
, NULL
);
127 static int aux_close (lua_State
*L
) {
129 lua_getfield(L
, -1, "__close");
130 return (lua_tocfunction(L
, -1))(L
);
134 static int io_close (lua_State
*L
) {
135 if (lua_isnone(L
, 1))
136 lua_rawgeti(L
, LUA_ENVIRONINDEX
, IO_OUTPUT
);
137 tofile(L
); /* make sure argument is a file */
142 static int io_gc (lua_State
*L
) {
143 FILE *f
= *tofilep(L
);
144 /* ignore closed files */
151 static int io_tostring (lua_State
*L
) {
152 FILE *f
= *tofilep(L
);
154 lua_pushliteral(L
, "file (closed)");
156 lua_pushfstring(L
, "file (%p)", f
);
161 static int io_open (lua_State
*L
) {
162 const char *filename
= luaL_checkstring(L
, 1);
163 const char *mode
= luaL_optstring(L
, 2, "r");
164 FILE **pf
= newfile(L
);
165 *pf
= fopen(filename
, mode
);
166 return (*pf
== NULL
) ? pushresult(L
, 0, filename
) : 1;
171 ** this function has a separated environment, which defines the
172 ** correct __close for 'popen' files
174 static int io_popen (lua_State
*L
) {
175 const char *filename
= luaL_checkstring(L
, 1);
176 const char *mode
= luaL_optstring(L
, 2, "r");
177 FILE **pf
= newfile(L
);
178 *pf
= lua_popen(L
, filename
, mode
);
179 return (*pf
== NULL
) ? pushresult(L
, 0, filename
) : 1;
184 static int io_tmpfile (lua_State
*L
) {
185 FILE **pf
= newfile(L
);
187 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 static int read_number (lua_State
*L
, FILE *f
) {
277 if (fscanf(f
, LUA_NUMBER_SCAN
, &d
) == 1) {
278 lua_pushnumber(L
, d
);
281 else return 0; /* read fails */
285 static int test_eof (lua_State
*L
, FILE *f
) {
288 lua_pushlstring(L
, NULL
, 0);
294 static int read_line (lua_State
*L
, FILE *f
) {
296 luaL_buffinit(L
, &b
);
299 char *p
= luaL_prepbuffer(&b
);
300 if (fgets(p
, LUAL_BUFFERSIZE
, f
) == NULL
) { /* eof? */
301 luaL_pushresult(&b
); /* close buffer */
302 return (lua_objlen(L
, -1) > 0); /* check whether read something */
305 if (l
== 0 || p
[l
-1] != '\n')
308 luaL_addsize(&b
, l
- 1); /* do not include `eol' */
309 luaL_pushresult(&b
); /* close buffer */
310 return 1; /* read at least an `eol' */
316 static int read_chars (lua_State
*L
, FILE *f
, size_t n
) {
317 size_t rlen
; /* how much to read */
318 size_t nr
; /* number of chars actually read */
320 luaL_buffinit(L
, &b
);
321 rlen
= LUAL_BUFFERSIZE
; /* try to read that much each time */
323 char *p
= luaL_prepbuffer(&b
);
324 if (rlen
> n
) rlen
= n
; /* cannot read more than asked */
325 nr
= fread(p
, sizeof(char), rlen
, f
);
326 luaL_addsize(&b
, nr
);
327 n
-= nr
; /* still have to read `n' chars */
328 } while (n
> 0 && nr
== rlen
); /* until end of count or eof */
329 luaL_pushresult(&b
); /* close buffer */
330 return (n
== 0 || lua_objlen(L
, -1) > 0);
335 static int g_read (lua_State
*L
, FILE *f
, int first
) {
336 int nargs
= lua_gettop(L
) - 1;
340 if (nargs
== 0) { /* no arguments? */
341 success
= read_line(L
, f
);
342 n
= first
+1; /* to return 1 result */
344 else { /* ensure stack space for all results and for auxlib's buffer */
345 luaL_checkstack(L
, nargs
+LUA_MINSTACK
, "too many arguments");
347 for (n
= first
; nargs
-- && success
; n
++) {
348 if (lua_type(L
, n
) == LUA_TNUMBER
) {
349 size_t l
= (size_t)lua_tointeger(L
, n
);
350 success
= (l
== 0) ? test_eof(L
, f
) : read_chars(L
, f
, l
);
353 const char *p
= lua_tostring(L
, n
);
354 luaL_argcheck(L
, p
&& p
[0] == '*', n
, "invalid option");
356 case 'n': /* number */
357 success
= read_number(L
, f
);
360 success
= read_line(L
, f
);
363 read_chars(L
, f
, ~((size_t)0)); /* read MAX_SIZE_T chars */
364 success
= 1; /* always success */
367 return luaL_argerror(L
, n
, "invalid format");
373 return pushresult(L
, 0, NULL
);
375 lua_pop(L
, 1); /* remove last result */
376 lua_pushnil(L
); /* push nil instead */
382 static int io_read (lua_State
*L
) {
383 return g_read(L
, getiofile(L
, IO_INPUT
), 1);
387 static int f_read (lua_State
*L
) {
388 return g_read(L
, tofile(L
), 2);
393 static int io_readline (lua_State
*L
) {
394 FILE *f
= *(FILE **)lua_touserdata(L
, lua_upvalueindex(1));
396 if (f
== NULL
) /* file is already closed? */
397 luaL_error(L
, "file is already closed");
398 sucess
= read_line(L
, f
);
400 return luaL_error(L
, "%s", strerror(errno
));
401 if (sucess
) return 1;
403 if (lua_toboolean(L
, lua_upvalueindex(2))) { /* generator created file? */
405 lua_pushvalue(L
, lua_upvalueindex(1));
406 aux_close(L
); /* close it */
412 /* }====================================================== */
415 static int g_write (lua_State
*L
, FILE *f
, int arg
) {
416 int nargs
= lua_gettop(L
) - 1;
418 for (; nargs
--; arg
++) {
419 if (lua_type(L
, arg
) == LUA_TNUMBER
) {
420 /* optimization: could be done exactly as for strings */
422 fprintf(f
, LUA_NUMBER_FMT
, lua_tonumber(L
, arg
)) > 0;
426 const char *s
= luaL_checklstring(L
, arg
, &l
);
427 status
= status
&& (fwrite(s
, sizeof(char), l
, f
) == l
);
430 return pushresult(L
, status
, NULL
);
434 static int io_write (lua_State
*L
) {
435 return g_write(L
, getiofile(L
, IO_OUTPUT
), 1);
439 static int f_write (lua_State
*L
) {
440 return g_write(L
, tofile(L
), 2);
444 static int f_seek (lua_State
*L
) {
445 static const int mode
[] = {SEEK_SET
, SEEK_CUR
, SEEK_END
};
446 static const char *const modenames
[] = {"set", "cur", "end", NULL
};
448 int op
= luaL_checkoption(L
, 2, "cur", modenames
);
449 long offset
= luaL_optlong(L
, 3, 0);
450 op
= fseek(f
, offset
, mode
[op
]);
452 return pushresult(L
, 0, NULL
); /* error */
454 lua_pushinteger(L
, ftell(f
));
462 static int f_setvbuf (lua_State
*L
) {
463 static const int mode
[] = {_IONBF
, _IOFBF
, _IOLBF
};
464 static const char *const modenames
[] = {"no", "full", "line", NULL
};
466 int op
= luaL_checkoption(L
, 2, NULL
, modenames
);
467 lua_Integer sz
= luaL_optinteger(L
, 3, LUAL_BUFFERSIZE
);
468 int res
= setvbuf(f
, NULL
, mode
[op
], sz
);
469 return pushresult(L
, res
== 0, NULL
);
474 static int io_flush (lua_State
*L
) {
475 return pushresult(L
, fflush(getiofile(L
, IO_OUTPUT
)) == 0, NULL
);
479 static int f_flush (lua_State
*L
) {
480 return pushresult(L
, fflush(tofile(L
)) == 0, NULL
);
484 static const luaL_Reg iolib
[] = {
490 {"output", io_output
},
492 /* {"read", io_read}, */
493 /* {"tmpfile", io_tmpfile}, */
500 static const luaL_Reg flib
[] = {
504 /* {"read", f_read}, */
505 /* {"seek", f_seek}, */
506 /* {"setvbuf", f_setvbuf}, */
509 {"__tostring", io_tostring
},
514 static void createmeta (lua_State
*L
) {
515 luaL_newmetatable(L
, LUA_FILEHANDLE
); /* create metatable for file handles */
516 lua_pushvalue(L
, -1); /* push metatable */
517 lua_setfield(L
, -2, "__index"); /* metatable.__index = metatable */
518 luaL_register(L
, NULL
, flib
); /* file methods */
522 static void createstdfile (lua_State
*L
, FILE *f
, int k
, const char *fname
) {
525 lua_pushvalue(L
, -1);
526 lua_rawseti(L
, LUA_ENVIRONINDEX
, k
);
528 lua_pushvalue(L
, -2); /* copy environment */
529 lua_setfenv(L
, -2); /* set it */
530 lua_setfield(L
, -3, fname
);
534 static void newfenv (lua_State
*L
, lua_CFunction cls
) {
535 lua_createtable(L
, 0, 1);
536 lua_pushcfunction(L
, cls
);
537 lua_setfield(L
, -2, "__close");
541 LUALIB_API
int luaopen_io (lua_State
*L
) {
543 /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
544 newfenv(L
, io_fclose
);
545 lua_replace(L
, LUA_ENVIRONINDEX
);
547 luaL_register(L
, LUA_IOLIBNAME
, iolib
);
548 /* create (and set) default files */
549 newfenv(L
, io_noclose
); /* close function for default files */
550 createstdfile(L
, stdin
, IO_INPUT
, "stdin");
551 createstdfile(L
, stdout
, IO_OUTPUT
, "stdout");
552 createstdfile(L
, stderr
, 0, "stderr");
553 lua_pop(L
, 1); /* pop environment for default files */
554 lua_getfield(L
, -1, "popen");
555 newfenv(L
, io_pclose
); /* create environment for 'popen' */
556 lua_setfenv(L
, -2); /* set fenv for 'popen' */
557 lua_pop(L
, 1); /* pop 'popen' */