2 ** $Id: liolib.c,v 2.111 2013/03/21 13:57:27 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
10 ** This definition must come before the inclusion of 'stdio.h'; it
11 ** should not affect non-POSIX systems
13 #if !defined(_FILE_OFFSET_BITS)
14 #define _FILE_OFFSET_BITS 64
32 #if !defined(lua_checkmode)
35 ** Check whether 'mode' matches '[rwa]%+?b?'.
36 ** Change this macro to accept other modes for 'fopen' besides
39 #define lua_checkmode(mode) \
40 (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
41 (*mode != '+' || ++mode) && /* skip if char is '+' */ \
42 (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \
48 ** {======================================================
49 ** lua_popen spawns a new process connected to the current
50 ** one through the file streams.
51 ** =======================================================
54 #if !defined(lua_popen) /* { */
56 #if defined(LUA_USE_POPEN) /* { */
58 #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
59 #define lua_pclose(L,file) ((void)L, pclose(file))
61 #elif defined(LUA_WIN) /* }{ */
63 #define lua_popen(L,c,m) ((void)L, _popen(c,m))
64 #define lua_pclose(L,file) ((void)L, _pclose(file))
69 #define lua_popen(L,c,m) ((void)((void)c, m), \
70 luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
71 #define lua_pclose(L,file) ((void)((void)L, file), -1)
78 /* }====================================================== */
82 ** {======================================================
83 ** lua_fseek/lua_ftell: configuration for longer offsets
84 ** =======================================================
87 #if !defined(lua_fseek) /* { */
89 #if defined(LUA_USE_POSIX)
91 #define l_fseek(f,o,w) fseeko(f,o,w)
92 #define l_ftell(f) ftello(f)
93 #define l_seeknum off_t
95 #elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
96 && defined(_MSC_VER) && (_MSC_VER >= 1400)
97 /* Windows (but not DDK) and Visual C++ 2005 or higher */
99 #define l_fseek(f,o,w) _fseeki64(f,o,w)
100 #define l_ftell(f) _ftelli64(f)
101 #define l_seeknum __int64
105 #define l_fseek(f,o,w) fseek(f,o,w)
106 #define l_ftell(f) ftell(f)
107 #define l_seeknum long
113 /* }====================================================== */
116 #define IO_PREFIX "_IO_"
117 #define IO_INPUT (IO_PREFIX "input")
118 #define IO_OUTPUT (IO_PREFIX "output")
121 typedef luaL_Stream LStream
;
124 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
126 #define isclosed(p) ((p)->closef == NULL)
129 static int io_type(lua_State
*L
) {
132 p
= (LStream
*)luaL_testudata(L
, 1, LUA_FILEHANDLE
);
134 lua_pushnil(L
); /* not a file */
135 else if (isclosed(p
))
136 lua_pushliteral(L
, "closed file");
138 lua_pushliteral(L
, "file");
143 static int f_tostring(lua_State
*L
) {
144 LStream
*p
= tolstream(L
);
146 lua_pushliteral(L
, "file (closed)");
148 lua_pushfstring(L
, "file (%p)", p
->f
);
153 static FILE *tofile(lua_State
*L
) {
154 LStream
*p
= tolstream(L
);
156 luaL_error(L
, "attempt to use a closed file");
163 ** When creating file handles, always creates a `closed' file handle
164 ** before opening the actual file; so, if there is a memory error, the
165 ** file is not left opened.
167 static LStream
*newprefile(lua_State
*L
) {
168 LStream
*p
= (LStream
*)lua_newuserdata(L
, sizeof(LStream
));
169 p
->closef
= NULL
; /* mark file handle as 'closed' */
170 luaL_setmetatable(L
, LUA_FILEHANDLE
);
175 static int aux_close(lua_State
*L
) {
176 LStream
*p
= tolstream(L
);
177 lua_CFunction cf
= p
->closef
;
178 p
->closef
= NULL
; /* mark stream as closed */
179 return (*cf
)(L
); /* close it */
183 static int io_close(lua_State
*L
) {
184 if (lua_isnone(L
, 1)) /* no argument? */
185 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_OUTPUT
); /* use standard output */
186 tofile(L
); /* make sure argument is an open stream */
191 static int f_gc(lua_State
*L
) {
192 LStream
*p
= tolstream(L
);
193 if (!isclosed(p
) && p
->f
!= NULL
)
194 aux_close(L
); /* ignore closed and incompletely open files */
200 ** function to close regular files
202 static int io_fclose(lua_State
*L
) {
203 LStream
*p
= tolstream(L
);
204 int res
= fclose(p
->f
);
205 return luaL_fileresult(L
, (res
== 0), NULL
);
209 static LStream
*newfile(lua_State
*L
) {
210 LStream
*p
= newprefile(L
);
212 p
->closef
= &io_fclose
;
217 static void opencheck(lua_State
*L
, const char *fname
, const char *mode
) {
218 LStream
*p
= newfile(L
);
219 p
->f
= fopen(fname
, mode
);
221 luaL_error(L
, "cannot open file " LUA_QS
" (%s)", fname
, strerror(errno
));
225 static int io_open(lua_State
*L
) {
226 const char *filename
= luaL_checkstring(L
, 1);
227 const char *mode
= luaL_optstring(L
, 2, "r");
228 LStream
*p
= newfile(L
);
229 const char *md
= mode
; /* to traverse/check mode */
230 luaL_argcheck(L
, lua_checkmode(md
), 2, "invalid mode");
231 p
->f
= fopen(filename
, mode
);
232 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
237 ** function to close 'popen' files
239 static int io_pclose(lua_State
*L
) {
240 LStream
*p
= tolstream(L
);
241 return luaL_execresult(L
, lua_pclose(L
, p
->f
));
245 static int io_popen(lua_State
*L
) {
246 const char *filename
= luaL_checkstring(L
, 1);
247 const char *mode
= luaL_optstring(L
, 2, "r");
248 LStream
*p
= newprefile(L
);
249 p
->f
= lua_popen(L
, filename
, mode
);
250 p
->closef
= &io_pclose
;
251 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
255 static int io_tmpfile(lua_State
*L
) {
256 LStream
*p
= newfile(L
);
258 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, NULL
) : 1;
262 static FILE *getiofile(lua_State
*L
, const char *findex
) {
264 lua_getfield(L
, LUA_REGISTRYINDEX
, findex
);
265 p
= (LStream
*)lua_touserdata(L
, -1);
267 luaL_error(L
, "standard %s file is closed", findex
+ strlen(IO_PREFIX
));
272 static int g_iofile(lua_State
*L
, const char *f
, const char *mode
) {
273 if (!lua_isnoneornil(L
, 1)) {
274 const char *filename
= lua_tostring(L
, 1);
276 opencheck(L
, filename
, mode
);
278 tofile(L
); /* check that it's a valid file handle */
281 lua_setfield(L
, LUA_REGISTRYINDEX
, f
);
283 /* return current value */
284 lua_getfield(L
, LUA_REGISTRYINDEX
, f
);
289 static int io_input(lua_State
*L
) {
290 return g_iofile(L
, IO_INPUT
, "r");
294 static int io_output(lua_State
*L
) {
295 return g_iofile(L
, IO_OUTPUT
, "w");
299 static int io_readline(lua_State
*L
);
302 static void aux_lines(lua_State
*L
, int toclose
) {
304 int n
= lua_gettop(L
) - 1; /* number of arguments to read */
305 /* ensure that arguments will fit here and into 'io_readline' stack */
306 luaL_argcheck(L
, n
<= LUA_MINSTACK
- 3, LUA_MINSTACK
- 3, "too many options");
307 lua_pushvalue(L
, 1); /* file handle */
308 lua_pushinteger(L
, n
); /* number of arguments to read */
309 lua_pushboolean(L
, toclose
); /* close/not close file when finished */
310 for (i
= 1; i
<= n
; i
++) lua_pushvalue(L
, i
+ 1); /* copy arguments */
311 lua_pushcclosure(L
, io_readline
, 3 + n
);
315 static int f_lines(lua_State
*L
) {
316 tofile(L
); /* check that it's a valid file handle */
322 static int io_lines(lua_State
*L
) {
324 if (lua_isnone(L
, 1)) lua_pushnil(L
); /* at least one argument */
325 if (lua_isnil(L
, 1)) { /* no file name? */
326 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_INPUT
); /* get default input */
327 lua_replace(L
, 1); /* put it at index 1 */
328 tofile(L
); /* check that it's a valid file handle */
329 toclose
= 0; /* do not close it after iteration */
330 } else { /* open a new file */
331 const char *filename
= luaL_checkstring(L
, 1);
332 opencheck(L
, filename
, "r");
333 lua_replace(L
, 1); /* put file at index 1 */
334 toclose
= 1; /* close it after iteration */
336 aux_lines(L
, toclose
);
342 ** {======================================================
344 ** =======================================================
348 static int read_number(lua_State
*L
, FILE *f
) {
350 if (fscanf(f
, LUA_NUMBER_SCAN
, &d
) == 1) {
351 lua_pushnumber(L
, d
);
354 lua_pushnil(L
); /* "result" to be removed */
355 return 0; /* read fails */
360 static int test_eof(lua_State
*L
, FILE *f
) {
363 lua_pushlstring(L
, NULL
, 0);
368 static int read_line(lua_State
*L
, FILE *f
, int chop
) {
370 luaL_buffinit(L
, &b
);
373 char *p
= luaL_prepbuffer(&b
);
374 if (fgets(p
, LUAL_BUFFERSIZE
, f
) == NULL
) { /* eof? */
375 luaL_pushresult(&b
); /* close buffer */
376 return (lua_rawlen(L
, -1) > 0); /* check whether read something */
379 if (l
== 0 || p
[l
- 1] != '\n')
382 luaL_addsize(&b
, l
- chop
); /* chop 'eol' if needed */
383 luaL_pushresult(&b
); /* close buffer */
384 return 1; /* read at least an `eol' */
390 #define MAX_SIZE_T (~(size_t)0)
392 static void read_all(lua_State
*L
, FILE *f
) {
393 size_t rlen
= LUAL_BUFFERSIZE
; /* how much to read in each cycle */
395 luaL_buffinit(L
, &b
);
397 char *p
= luaL_prepbuffsize(&b
, rlen
);
398 size_t nr
= fread(p
, sizeof(char), rlen
, f
);
399 luaL_addsize(&b
, nr
);
400 if (nr
< rlen
) break; /* eof? */
401 else if (rlen
<= (MAX_SIZE_T
/ 4)) /* avoid buffers too large */
402 rlen
*= 2; /* double buffer size at each iteration */
404 luaL_pushresult(&b
); /* close buffer */
408 static int read_chars(lua_State
*L
, FILE *f
, size_t n
) {
409 size_t nr
; /* number of chars actually read */
412 luaL_buffinit(L
, &b
);
413 p
= luaL_prepbuffsize(&b
, n
); /* prepare buffer to read whole block */
414 nr
= fread(p
, sizeof(char), n
, f
); /* try to read 'n' chars */
415 luaL_addsize(&b
, nr
);
416 luaL_pushresult(&b
); /* close buffer */
417 return (nr
> 0); /* true iff read something */
421 static int g_read(lua_State
*L
, FILE *f
, int first
) {
422 int nargs
= lua_gettop(L
) - 1;
426 if (nargs
== 0) { /* no arguments? */
427 success
= read_line(L
, f
, 1);
428 n
= first
+ 1; /* to return 1 result */
429 } else { /* ensure stack space for all results and for auxlib's buffer */
430 luaL_checkstack(L
, nargs
+ LUA_MINSTACK
, "too many arguments");
432 for (n
= first
; nargs
-- && success
; n
++) {
433 if (lua_type(L
, n
) == LUA_TNUMBER
) {
434 size_t l
= (size_t)lua_tointeger(L
, n
);
435 success
= (l
== 0) ? test_eof(L
, f
) : read_chars(L
, f
, l
);
437 const char *p
= lua_tostring(L
, n
);
438 luaL_argcheck(L
, p
&& p
[0] == '*', n
, "invalid option");
440 case 'n': /* number */
441 success
= read_number(L
, f
);
444 success
= read_line(L
, f
, 1);
446 case 'L': /* line with end-of-line */
447 success
= read_line(L
, f
, 0);
450 read_all(L
, f
); /* read entire file */
451 success
= 1; /* always success */
454 return luaL_argerror(L
, n
, "invalid format");
460 return luaL_fileresult(L
, 0, NULL
);
462 lua_pop(L
, 1); /* remove last result */
463 lua_pushnil(L
); /* push nil instead */
469 static int io_read(lua_State
*L
) {
470 return g_read(L
, getiofile(L
, IO_INPUT
), 1);
474 static int f_read(lua_State
*L
) {
475 return g_read(L
, tofile(L
), 2);
479 static int io_readline(lua_State
*L
) {
480 LStream
*p
= (LStream
*)lua_touserdata(L
, lua_upvalueindex(1));
482 int n
= (int)lua_tointeger(L
, lua_upvalueindex(2));
483 if (isclosed(p
)) /* file is already closed? */
484 return luaL_error(L
, "file is already closed");
486 for (i
= 1; i
<= n
; i
++) /* push arguments to 'g_read' */
487 lua_pushvalue(L
, lua_upvalueindex(3 + i
));
488 n
= g_read(L
, p
->f
, 2); /* 'n' is number of results */
489 lua_assert(n
> 0); /* should return at least a nil */
490 if (!lua_isnil(L
, -n
)) /* read at least one value? */
491 return n
; /* return them */
492 else { /* first result is nil: EOF or error */
493 if (n
> 1) { /* is there error information? */
494 /* 2nd result is error message */
495 return luaL_error(L
, "%s", lua_tostring(L
, -n
+ 1));
497 if (lua_toboolean(L
, lua_upvalueindex(3))) { /* generator created file? */
499 lua_pushvalue(L
, lua_upvalueindex(1));
500 aux_close(L
); /* close it */
506 /* }====================================================== */
509 static int g_write(lua_State
*L
, FILE *f
, int arg
) {
510 int nargs
= lua_gettop(L
) - arg
;
512 for (; nargs
--; arg
++) {
513 if (lua_type(L
, arg
) == LUA_TNUMBER
) {
514 /* optimization: could be done exactly as for strings */
516 fprintf(f
, LUA_NUMBER_FMT
, lua_tonumber(L
, arg
)) > 0;
519 const char *s
= luaL_checklstring(L
, arg
, &l
);
520 status
= status
&& (fwrite(s
, sizeof(char), l
, f
) == l
);
523 if (status
) return 1; /* file handle already on stack top */
524 else return luaL_fileresult(L
, status
, NULL
);
528 static int io_write(lua_State
*L
) {
529 return g_write(L
, getiofile(L
, IO_OUTPUT
), 1);
533 static int f_write(lua_State
*L
) {
535 lua_pushvalue(L
, 1); /* push file at the stack top (to be returned) */
536 return g_write(L
, f
, 2);
540 static int f_seek(lua_State
*L
) {
541 static const int mode
[] = {SEEK_SET
, SEEK_CUR
, SEEK_END
};
542 static const char *const modenames
[] = {"set", "cur", "end", NULL
};
544 int op
= luaL_checkoption(L
, 2, "cur", modenames
);
545 lua_Number p3
= luaL_optnumber(L
, 3, 0);
546 l_seeknum offset
= (l_seeknum
)p3
;
547 luaL_argcheck(L
, (lua_Number
)offset
== p3
, 3,
548 "not an integer in proper range");
549 op
= l_fseek(f
, offset
, mode
[op
]);
551 return luaL_fileresult(L
, 0, NULL
); /* error */
553 lua_pushnumber(L
, (lua_Number
)l_ftell(f
));
559 static int f_setvbuf(lua_State
*L
) {
560 static const int mode
[] = {_IONBF
, _IOFBF
, _IOLBF
};
561 static const char *const modenames
[] = {"no", "full", "line", NULL
};
563 int op
= luaL_checkoption(L
, 2, NULL
, modenames
);
564 lua_Integer sz
= luaL_optinteger(L
, 3, LUAL_BUFFERSIZE
);
565 int res
= setvbuf(f
, NULL
, mode
[op
], sz
);
566 return luaL_fileresult(L
, res
== 0, NULL
);
571 static int io_flush(lua_State
*L
) {
572 return luaL_fileresult(L
, fflush(getiofile(L
, IO_OUTPUT
)) == 0, NULL
);
576 static int f_flush(lua_State
*L
) {
577 return luaL_fileresult(L
, fflush(tofile(L
)) == 0, NULL
);
582 ** functions for 'io' library
584 static const luaL_Reg iolib
[] = {
590 {"output", io_output
},
593 {"tmpfile", io_tmpfile
},
601 ** methods for file handles
603 static const luaL_Reg flib
[] = {
609 {"setvbuf", f_setvbuf
},
612 {"__tostring", f_tostring
},
617 static void createmeta(lua_State
*L
) {
618 luaL_newmetatable(L
, LUA_FILEHANDLE
); /* create metatable for file handles */
619 lua_pushvalue(L
, -1); /* push metatable */
620 lua_setfield(L
, -2, "__index"); /* metatable.__index = metatable */
621 luaL_setfuncs(L
, flib
, 0); /* add file methods to new metatable */
622 lua_pop(L
, 1); /* pop new metatable */
627 ** function to (not) close the standard files stdin, stdout, and stderr
629 static int io_noclose(lua_State
*L
) {
630 LStream
*p
= tolstream(L
);
631 p
->closef
= &io_noclose
; /* keep file opened */
633 lua_pushliteral(L
, "cannot close standard file");
638 static void createstdfile(lua_State
*L
, FILE *f
, const char *k
,
640 LStream
*p
= newprefile(L
);
642 p
->closef
= &io_noclose
;
644 lua_pushvalue(L
, -1);
645 lua_setfield(L
, LUA_REGISTRYINDEX
, k
); /* add file to registry */
647 lua_setfield(L
, -2, fname
); /* add file to module */
651 LUAMOD_API
int luaopen_io(lua_State
*L
) {
652 luaL_newlib(L
, iolib
); /* new module */
654 /* create (and set) default files */
655 createstdfile(L
, stdin
, IO_INPUT
, "stdin");
656 createstdfile(L
, stdout
, IO_OUTPUT
, "stdout");
657 createstdfile(L
, stderr
, NULL
, "stderr");