1 /* $NetBSD: liolib.c,v 1.1.1.2 2012/03/15 00:08:04 alnsn Exp $ */
4 ** $Id: liolib.c,v 1.1.1.2 2012/03/15 00:08:04 alnsn Exp $
5 ** Standard I/O (and system) library
6 ** 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 static int read_number (lua_State
*L
, FILE *f
) {
277 if (fscanf(f
, LUA_NUMBER_SCAN
, &d
) == 1) {
278 lua_pushnumber(L
, d
);
282 lua_pushnil(L
); /* "result" to be removed */
283 return 0; /* read fails */
288 static int test_eof (lua_State
*L
, FILE *f
) {
291 lua_pushlstring(L
, NULL
, 0);
296 static int read_line (lua_State
*L
, FILE *f
) {
298 luaL_buffinit(L
, &b
);
301 char *p
= luaL_prepbuffer(&b
);
302 if (fgets(p
, LUAL_BUFFERSIZE
, f
) == NULL
) { /* eof? */
303 luaL_pushresult(&b
); /* close buffer */
304 return (lua_objlen(L
, -1) > 0); /* check whether read something */
307 if (l
== 0 || p
[l
-1] != '\n')
310 luaL_addsize(&b
, l
- 1); /* do not include `eol' */
311 luaL_pushresult(&b
); /* close buffer */
312 return 1; /* read at least an `eol' */
318 static int read_chars (lua_State
*L
, FILE *f
, size_t n
) {
319 size_t rlen
; /* how much to read */
320 size_t nr
; /* number of chars actually read */
322 luaL_buffinit(L
, &b
);
323 rlen
= LUAL_BUFFERSIZE
; /* try to read that much each time */
325 char *p
= luaL_prepbuffer(&b
);
326 if (rlen
> n
) rlen
= n
; /* cannot read more than asked */
327 nr
= fread(p
, sizeof(char), rlen
, f
);
328 luaL_addsize(&b
, nr
);
329 n
-= nr
; /* still have to read `n' chars */
330 } while (n
> 0 && nr
== rlen
); /* until end of count or eof */
331 luaL_pushresult(&b
); /* close buffer */
332 return (n
== 0 || lua_objlen(L
, -1) > 0);
336 static int g_read (lua_State
*L
, FILE *f
, int first
) {
337 int nargs
= lua_gettop(L
) - 1;
341 if (nargs
== 0) { /* no arguments? */
342 success
= read_line(L
, f
);
343 n
= first
+1; /* to return 1 result */
345 else { /* ensure stack space for all results and for auxlib's buffer */
346 luaL_checkstack(L
, nargs
+LUA_MINSTACK
, "too many arguments");
348 for (n
= first
; nargs
-- && success
; n
++) {
349 if (lua_type(L
, n
) == LUA_TNUMBER
) {
350 size_t l
= (size_t)lua_tointeger(L
, n
);
351 success
= (l
== 0) ? test_eof(L
, f
) : read_chars(L
, f
, l
);
354 const char *p
= lua_tostring(L
, n
);
355 luaL_argcheck(L
, p
&& p
[0] == '*', n
, "invalid option");
357 case 'n': /* number */
358 success
= read_number(L
, f
);
361 success
= read_line(L
, f
);
364 read_chars(L
, f
, ~((size_t)0)); /* read MAX_SIZE_T chars */
365 success
= 1; /* always success */
368 return luaL_argerror(L
, n
, "invalid format");
374 return pushresult(L
, 0, NULL
);
376 lua_pop(L
, 1); /* remove last result */
377 lua_pushnil(L
); /* push nil instead */
383 static int io_read (lua_State
*L
) {
384 return g_read(L
, getiofile(L
, IO_INPUT
), 1);
388 static int f_read (lua_State
*L
) {
389 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
));
460 static int f_setvbuf (lua_State
*L
) {
461 static const int mode
[] = {_IONBF
, _IOFBF
, _IOLBF
};
462 static const char *const modenames
[] = {"no", "full", "line", NULL
};
464 int op
= luaL_checkoption(L
, 2, NULL
, modenames
);
465 lua_Integer sz
= luaL_optinteger(L
, 3, LUAL_BUFFERSIZE
);
466 int res
= setvbuf(f
, NULL
, mode
[op
], sz
);
467 return pushresult(L
, res
== 0, NULL
);
472 static int io_flush (lua_State
*L
) {
473 return pushresult(L
, fflush(getiofile(L
, IO_OUTPUT
)) == 0, NULL
);
477 static int f_flush (lua_State
*L
) {
478 return pushresult(L
, fflush(tofile(L
)) == 0, NULL
);
482 static const luaL_Reg iolib
[] = {
488 {"output", io_output
},
491 {"tmpfile", io_tmpfile
},
498 static const luaL_Reg flib
[] = {
504 {"setvbuf", f_setvbuf
},
507 {"__tostring", io_tostring
},
512 static void createmeta (lua_State
*L
) {
513 luaL_newmetatable(L
, LUA_FILEHANDLE
); /* create metatable for file handles */
514 lua_pushvalue(L
, -1); /* push metatable */
515 lua_setfield(L
, -2, "__index"); /* metatable.__index = metatable */
516 luaL_register(L
, NULL
, flib
); /* file methods */
520 static void createstdfile (lua_State
*L
, FILE *f
, int k
, const char *fname
) {
523 lua_pushvalue(L
, -1);
524 lua_rawseti(L
, LUA_ENVIRONINDEX
, k
);
526 lua_pushvalue(L
, -2); /* copy environment */
527 lua_setfenv(L
, -2); /* set it */
528 lua_setfield(L
, -3, fname
);
532 static void newfenv (lua_State
*L
, lua_CFunction cls
) {
533 lua_createtable(L
, 0, 1);
534 lua_pushcfunction(L
, cls
);
535 lua_setfield(L
, -2, "__close");
539 LUALIB_API
int luaopen_io (lua_State
*L
) {
541 /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
542 newfenv(L
, io_fclose
);
543 lua_replace(L
, LUA_ENVIRONINDEX
);
545 luaL_register(L
, LUA_IOLIBNAME
, iolib
);
546 /* create (and set) default files */
547 newfenv(L
, io_noclose
); /* close function for default files */
548 createstdfile(L
, stdin
, IO_INPUT
, "stdin");
549 createstdfile(L
, stdout
, IO_OUTPUT
, "stdout");
550 createstdfile(L
, stderr
, 0, "stderr");
551 lua_pop(L
, 1); /* pop environment for default files */
552 lua_getfield(L
, -1, "popen");
553 newfenv(L
, io_pclose
); /* create environment for 'popen' */
554 lua_setfenv(L
, -2); /* set fenv for 'popen' */
555 lua_pop(L
, 1); /* pop 'popen' */