3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
29 ** Change this macro to accept other modes for 'fopen' besides
32 #if !defined(l_checkmode)
34 /* accepted extensions to 'mode' in 'fopen' */
35 #if !defined(L_MODEEXT)
39 /* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
40 static int l_checkmode(const char *mode
) {
41 return (*mode
!= '\0' && strchr("rwa", *(mode
++)) != NULL
&&
42 (*mode
!= '+' || ((void)(++mode
), 1)) && /* skip if char is '+' */
43 (strspn(mode
, L_MODEEXT
) == strlen(mode
))); /* check extensions */
49 ** {======================================================
50 ** l_popen spawns a new process connected to the current
51 ** one through the file streams.
52 ** =======================================================
55 #if !defined(l_popen) /* { */
57 #if defined(LUA_USE_POSIX) /* { */
59 #define l_popen(L,c,m) (fflush(NULL), popen(c,m))
60 #define l_pclose(L,file) (pclose(file))
62 #elif defined(LUA_USE_WINDOWS) /* }{ */
64 #define l_popen(L,c,m) (_popen(c,m))
65 #define l_pclose(L,file) (_pclose(file))
67 #if !defined(l_checkmodep)
68 /* Windows accepts "[rw][bt]?" as valid modes */
69 #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \
70 (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
75 /* ISO C definitions */
76 #define l_popen(L,c,m) \
78 luaL_error(L, "'popen' not supported"), \
80 #define l_pclose(L,file) ((void)L, (void)file, -1)
87 #if !defined(l_checkmodep)
88 /* By default, Lua accepts only "r" or "w" as valid modes */
89 #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
92 /* }====================================================== */
95 #if !defined(l_getc) /* { */
97 #if defined(LUA_USE_POSIX)
98 #define l_getc(f) getc_unlocked(f)
99 #define l_lockfile(f) flockfile(f)
100 #define l_unlockfile(f) funlockfile(f)
102 #define l_getc(f) getc(f)
103 #define l_lockfile(f) ((void)0)
104 #define l_unlockfile(f) ((void)0)
111 ** {======================================================
112 ** l_fseek: configuration for longer offsets
113 ** =======================================================
116 #if !defined(l_fseek) /* { */
118 #if defined(LUA_USE_POSIX) /* { */
120 #include <sys/types.h>
122 #define l_fseek(f,o,w) fseeko(f,o,w)
123 #define l_ftell(f) ftello(f)
124 #define l_seeknum off_t
126 #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
127 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
129 /* Windows (but not DDK) and Visual C++ 2005 or higher */
130 #define l_fseek(f,o,w) _fseeki64(f,o,w)
131 #define l_ftell(f) _ftelli64(f)
132 #define l_seeknum __int64
136 /* ISO C definitions */
137 #define l_fseek(f,o,w) fseek(f,o,w)
138 #define l_ftell(f) ftell(f)
139 #define l_seeknum long
145 /* }====================================================== */
149 #define IO_PREFIX "_IO_"
150 #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
151 #define IO_INPUT (IO_PREFIX "input")
152 #define IO_OUTPUT (IO_PREFIX "output")
155 typedef luaL_Stream LStream
;
158 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
160 #define isclosed(p) ((p)->closef == NULL)
163 static int io_type(lua_State
*L
) {
166 p
= (LStream
*)luaL_testudata(L
, 1, LUA_FILEHANDLE
);
168 luaL_pushfail(L
); /* not a file */
169 else if (isclosed(p
))
170 lua_pushliteral(L
, "closed file");
172 lua_pushliteral(L
, "file");
177 static int f_tostring(lua_State
*L
) {
178 LStream
*p
= tolstream(L
);
180 lua_pushliteral(L
, "file (closed)");
182 lua_pushfstring(L
, "file (%p)", p
->f
);
187 static FILE *tofile(lua_State
*L
) {
188 LStream
*p
= tolstream(L
);
189 if (l_unlikely(isclosed(p
)))
190 luaL_error(L
, "attempt to use a closed file");
197 ** When creating file handles, always creates a 'closed' file handle
198 ** before opening the actual file; so, if there is a memory error, the
199 ** handle is in a consistent state.
201 static LStream
*newprefile(lua_State
*L
) {
202 LStream
*p
= (LStream
*)lua_newuserdatauv(L
, sizeof(LStream
), 0);
203 p
->closef
= NULL
; /* mark file handle as 'closed' */
204 luaL_setmetatable(L
, LUA_FILEHANDLE
);
210 ** Calls the 'close' function from a file handle. The 'volatile' avoids
211 ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
214 static int aux_close(lua_State
*L
) {
215 LStream
*p
= tolstream(L
);
216 volatile lua_CFunction cf
= p
->closef
;
217 p
->closef
= NULL
; /* mark stream as closed */
218 return (*cf
)(L
); /* close it */
222 static int f_close(lua_State
*L
) {
223 tofile(L
); /* make sure argument is an open stream */
228 static int io_close(lua_State
*L
) {
229 if (lua_isnone(L
, 1)) /* no argument? */
230 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_OUTPUT
); /* use default output */
235 static int f_gc(lua_State
*L
) {
236 LStream
*p
= tolstream(L
);
237 if (!isclosed(p
) && p
->f
!= NULL
)
238 aux_close(L
); /* ignore closed and incompletely open files */
244 ** function to close regular files
246 static int io_fclose(lua_State
*L
) {
247 LStream
*p
= tolstream(L
);
249 return luaL_fileresult(L
, (fclose(p
->f
) == 0), NULL
);
253 static LStream
*newfile(lua_State
*L
) {
254 LStream
*p
= newprefile(L
);
256 p
->closef
= &io_fclose
;
261 static void opencheck(lua_State
*L
, const char *fname
, const char *mode
) {
262 LStream
*p
= newfile(L
);
263 p
->f
= fopen(fname
, mode
);
264 if (l_unlikely(p
->f
== NULL
))
265 luaL_error(L
, "cannot open file '%s' (%s)", fname
, strerror(errno
));
269 static int io_open(lua_State
*L
) {
270 const char *filename
= luaL_checkstring(L
, 1);
271 const char *mode
= luaL_optstring(L
, 2, "r");
272 LStream
*p
= newfile(L
);
273 const char *md
= mode
; /* to traverse/check mode */
274 luaL_argcheck(L
, l_checkmode(md
), 2, "invalid mode");
276 p
->f
= fopen(filename
, mode
);
277 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
282 ** function to close 'popen' files
284 static int io_pclose(lua_State
*L
) {
285 LStream
*p
= tolstream(L
);
287 return luaL_execresult(L
, l_pclose(L
, p
->f
));
291 static int io_popen(lua_State
*L
) {
292 const char *filename
= luaL_checkstring(L
, 1);
293 const char *mode
= luaL_optstring(L
, 2, "r");
294 LStream
*p
= newprefile(L
);
295 luaL_argcheck(L
, l_checkmodep(mode
), 2, "invalid mode");
297 p
->f
= l_popen(L
, filename
, mode
);
298 p
->closef
= &io_pclose
;
299 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
303 static int io_tmpfile(lua_State
*L
) {
304 LStream
*p
= newfile(L
);
307 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, NULL
) : 1;
311 static FILE *getiofile(lua_State
*L
, const char *findex
) {
313 lua_getfield(L
, LUA_REGISTRYINDEX
, findex
);
314 p
= (LStream
*)lua_touserdata(L
, -1);
315 if (l_unlikely(isclosed(p
)))
316 luaL_error(L
, "default %s file is closed", findex
+ IOPREF_LEN
);
321 static int g_iofile(lua_State
*L
, const char *f
, const char *mode
) {
322 if (!lua_isnoneornil(L
, 1)) {
323 const char *filename
= lua_tostring(L
, 1);
325 opencheck(L
, filename
, mode
);
327 tofile(L
); /* check that it's a valid file handle */
330 lua_setfield(L
, LUA_REGISTRYINDEX
, f
);
332 /* return current value */
333 lua_getfield(L
, LUA_REGISTRYINDEX
, f
);
338 static int io_input(lua_State
*L
) {
339 return g_iofile(L
, IO_INPUT
, "r");
343 static int io_output(lua_State
*L
) {
344 return g_iofile(L
, IO_OUTPUT
, "w");
348 static int io_readline(lua_State
*L
);
352 ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
353 ** in the limit for upvalues of a closure)
355 #define MAXARGLINE 250
358 ** Auxiliary function to create the iteration function for 'lines'.
359 ** The iteration function is a closure over 'io_readline', with
360 ** the following upvalues:
361 ** 1) The file being read (first value in the stack)
362 ** 2) the number of arguments to read
363 ** 3) a boolean, true iff file has to be closed when finished ('toclose')
364 ** *) a variable number of format arguments (rest of the stack)
366 static void aux_lines(lua_State
*L
, int toclose
) {
367 int n
= lua_gettop(L
) - 1; /* number of arguments to read */
368 luaL_argcheck(L
, n
<= MAXARGLINE
, MAXARGLINE
+ 2, "too many arguments");
369 lua_pushvalue(L
, 1); /* file */
370 lua_pushinteger(L
, n
); /* number of arguments to read */
371 lua_pushboolean(L
, toclose
); /* close/not close file when finished */
372 lua_rotate(L
, 2, 3); /* move the three values to their positions */
373 lua_pushcclosure(L
, io_readline
, 3 + n
);
377 static int f_lines(lua_State
*L
) {
378 tofile(L
); /* check that it's a valid file handle */
385 ** Return an iteration function for 'io.lines'. If file has to be
386 ** closed, also returns the file itself as a second result (to be
387 ** closed as the state at the exit of a generic for).
389 static int io_lines(lua_State
*L
) {
391 if (lua_isnone(L
, 1)) lua_pushnil(L
); /* at least one argument */
392 if (lua_isnil(L
, 1)) { /* no file name? */
393 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_INPUT
); /* get default input */
394 lua_replace(L
, 1); /* put it at index 1 */
395 tofile(L
); /* check that it's a valid file handle */
396 toclose
= 0; /* do not close it after iteration */
397 } else { /* open a new file */
398 const char *filename
= luaL_checkstring(L
, 1);
399 opencheck(L
, filename
, "r");
400 lua_replace(L
, 1); /* put file at index 1 */
401 toclose
= 1; /* close it after iteration */
403 aux_lines(L
, toclose
); /* push iteration function */
405 lua_pushnil(L
); /* state */
406 lua_pushnil(L
); /* control */
407 lua_pushvalue(L
, 1); /* file is the to-be-closed variable (4th result) */
415 ** {======================================================
417 ** =======================================================
421 /* maximum length of a numeral */
422 #if !defined (L_MAXLENNUM)
423 #define L_MAXLENNUM 200
427 /* auxiliary structure used by 'read_number' */
429 FILE *f
; /* file being read */
430 int c
; /* current character (look ahead) */
431 int n
; /* number of elements in buffer 'buff' */
432 char buff
[L_MAXLENNUM
+ 1]; /* +1 for ending '\0' */
437 ** Add current char to buffer (if not out of space) and read next one
439 static int nextc(RN
*rn
) {
440 if (l_unlikely(rn
->n
>= L_MAXLENNUM
)) { /* buffer overflow? */
441 rn
->buff
[0] = '\0'; /* invalidate result */
444 rn
->buff
[rn
->n
++] = rn
->c
; /* save current char */
445 rn
->c
= l_getc(rn
->f
); /* read next one */
452 ** Accept current char if it is in 'set' (of size 2)
454 static int test2(RN
*rn
, const char *set
) {
455 if (rn
->c
== set
[0] || rn
->c
== set
[1])
462 ** Read a sequence of (hex)digits
464 static int readdigits(RN
*rn
, int hex
) {
466 while ((hex
? isxdigit(rn
->c
) : isdigit(rn
->c
)) && nextc(rn
))
473 ** Read a number: first reads a valid prefix of a numeral into a buffer.
474 ** Then it calls 'lua_stringtonumber' to check whether the format is
475 ** correct and to convert it to a Lua number.
477 static int read_number(lua_State
*L
, FILE *f
) {
484 decp
[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
485 decp
[1] = '.'; /* always accept a dot */
487 do { rn
.c
= l_getc(rn
.f
); }
488 while (isspace(rn
.c
)); /* skip spaces */
489 test2(&rn
, "-+"); /* optional sign */
490 if (test2(&rn
, "00")) {
491 if (test2(&rn
, "xX")) hex
= 1; /* numeral is hexadecimal */
492 else count
= 1; /* count initial '0' as a valid digit */
494 count
+= readdigits(&rn
, hex
); /* integral part */
495 if (test2(&rn
, decp
)) /* decimal point? */
496 count
+= readdigits(&rn
, hex
); /* fractional part */
497 if (count
> 0 && test2(&rn
, (hex
? "pP" : "eE"))) { /* exponent mark? */
498 test2(&rn
, "-+"); /* exponent sign */
499 readdigits(&rn
, 0); /* exponent digits */
501 ungetc(rn
.c
, rn
.f
); /* unread look-ahead char */
503 rn
.buff
[rn
.n
] = '\0'; /* finish string */
504 if (l_likely(lua_stringtonumber(L
, rn
.buff
)))
505 return 1; /* ok, it is a valid number */
506 else { /* invalid format */
507 lua_pushnil(L
); /* "result" to be removed */
508 return 0; /* read fails */
513 static int test_eof(lua_State
*L
, FILE *f
) {
515 ungetc(c
, f
); /* no-op when c == EOF */
516 lua_pushliteral(L
, "");
521 static int read_line(lua_State
*L
, FILE *f
, int chop
) {
524 luaL_buffinit(L
, &b
);
525 do { /* may need to read several chunks to get whole line */
526 char *buff
= luaL_prepbuffer(&b
); /* preallocate buffer space */
528 l_lockfile(f
); /* no memory errors can happen inside the lock */
529 while (i
< LUAL_BUFFERSIZE
&& (c
= l_getc(f
)) != EOF
&& c
!= '\n')
530 buff
[i
++] = c
; /* read up to end of line or buffer limit */
533 } while (c
!= EOF
&& c
!= '\n'); /* repeat until end of line */
534 if (!chop
&& c
== '\n') /* want a newline and have one? */
535 luaL_addchar(&b
, c
); /* add ending newline to result */
536 luaL_pushresult(&b
); /* close buffer */
537 /* return ok if read something (either a newline or something else) */
538 return (c
== '\n' || lua_rawlen(L
, -1) > 0);
542 static void read_all(lua_State
*L
, FILE *f
) {
545 luaL_buffinit(L
, &b
);
546 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
547 char *p
= luaL_prepbuffer(&b
);
548 nr
= fread(p
, sizeof(char), LUAL_BUFFERSIZE
, f
);
549 luaL_addsize(&b
, nr
);
550 } while (nr
== LUAL_BUFFERSIZE
);
551 luaL_pushresult(&b
); /* close buffer */
555 static int read_chars(lua_State
*L
, FILE *f
, size_t n
) {
556 size_t nr
; /* number of chars actually read */
559 luaL_buffinit(L
, &b
);
560 p
= luaL_prepbuffsize(&b
, n
); /* prepare buffer to read whole block */
561 nr
= fread(p
, sizeof(char), n
, f
); /* try to read 'n' chars */
562 luaL_addsize(&b
, nr
);
563 luaL_pushresult(&b
); /* close buffer */
564 return (nr
> 0); /* true iff read something */
568 static int g_read(lua_State
*L
, FILE *f
, int first
) {
569 int nargs
= lua_gettop(L
) - 1;
573 if (nargs
== 0) { /* no arguments? */
574 success
= read_line(L
, f
, 1);
575 n
= first
+ 1; /* to return 1 result */
577 /* ensure stack space for all results and for auxlib's buffer */
578 luaL_checkstack(L
, nargs
+ LUA_MINSTACK
, "too many arguments");
580 for (n
= first
; nargs
-- && success
; n
++) {
581 if (lua_type(L
, n
) == LUA_TNUMBER
) {
582 size_t l
= (size_t)luaL_checkinteger(L
, n
);
583 success
= (l
== 0) ? test_eof(L
, f
) : read_chars(L
, f
, l
);
585 const char *p
= luaL_checkstring(L
, n
);
586 if (*p
== '*') p
++; /* skip optional '*' (for compatibility) */
588 case 'n': /* number */
589 success
= read_number(L
, f
);
592 success
= read_line(L
, f
, 1);
594 case 'L': /* line with end-of-line */
595 success
= read_line(L
, f
, 0);
598 read_all(L
, f
); /* read entire file */
599 success
= 1; /* always success */
602 return luaL_argerror(L
, n
, "invalid format");
608 return luaL_fileresult(L
, 0, NULL
);
610 lua_pop(L
, 1); /* remove last result */
611 luaL_pushfail(L
); /* push nil instead */
617 static int io_read(lua_State
*L
) {
618 return g_read(L
, getiofile(L
, IO_INPUT
), 1);
622 static int f_read(lua_State
*L
) {
623 return g_read(L
, tofile(L
), 2);
628 ** Iteration function for 'lines'.
630 static int io_readline(lua_State
*L
) {
631 LStream
*p
= (LStream
*)lua_touserdata(L
, lua_upvalueindex(1));
633 int n
= (int)lua_tointeger(L
, lua_upvalueindex(2));
634 if (isclosed(p
)) /* file is already closed? */
635 return luaL_error(L
, "file is already closed");
637 luaL_checkstack(L
, n
, "too many arguments");
638 for (i
= 1; i
<= n
; i
++) /* push arguments to 'g_read' */
639 lua_pushvalue(L
, lua_upvalueindex(3 + i
));
640 n
= g_read(L
, p
->f
, 2); /* 'n' is number of results */
641 lua_assert(n
> 0); /* should return at least a nil */
642 if (lua_toboolean(L
, -n
)) /* read at least one value? */
643 return n
; /* return them */
644 else { /* first result is false: EOF or error */
645 if (n
> 1) { /* is there error information? */
646 /* 2nd result is error message */
647 return luaL_error(L
, "%s", lua_tostring(L
, -n
+ 1));
649 if (lua_toboolean(L
, lua_upvalueindex(3))) { /* generator created file? */
650 lua_settop(L
, 0); /* clear stack */
651 lua_pushvalue(L
, lua_upvalueindex(1)); /* push file at index 1 */
652 aux_close(L
); /* close it */
658 /* }====================================================== */
661 static int g_write(lua_State
*L
, FILE *f
, int arg
) {
662 int nargs
= lua_gettop(L
) - arg
;
665 for (; nargs
--; arg
++) {
666 if (lua_type(L
, arg
) == LUA_TNUMBER
) {
667 /* optimization: could be done exactly as for strings */
668 int len
= lua_isinteger(L
, arg
)
669 ? fprintf(f
, LUA_INTEGER_FMT
,
670 (LUAI_UACINT
)lua_tointeger(L
, arg
))
671 : fprintf(f
, LUA_NUMBER_FMT
,
672 (LUAI_UACNUMBER
)lua_tonumber(L
, arg
));
673 status
= status
&& (len
> 0);
676 const char *s
= luaL_checklstring(L
, arg
, &l
);
677 status
= status
&& (fwrite(s
, sizeof(char), l
, f
) == l
);
680 if (l_likely(status
))
681 return 1; /* file handle already on stack top */
683 return luaL_fileresult(L
, status
, NULL
);
687 static int io_write(lua_State
*L
) {
688 return g_write(L
, getiofile(L
, IO_OUTPUT
), 1);
692 static int f_write(lua_State
*L
) {
694 lua_pushvalue(L
, 1); /* push file at the stack top (to be returned) */
695 return g_write(L
, f
, 2);
699 static int f_seek(lua_State
*L
) {
700 static const int mode
[] = {SEEK_SET
, SEEK_CUR
, SEEK_END
};
701 static const char *const modenames
[] = {"set", "cur", "end", NULL
};
703 int op
= luaL_checkoption(L
, 2, "cur", modenames
);
704 lua_Integer p3
= luaL_optinteger(L
, 3, 0);
705 l_seeknum offset
= (l_seeknum
)p3
;
706 luaL_argcheck(L
, (lua_Integer
)offset
== p3
, 3,
707 "not an integer in proper range");
709 op
= l_fseek(f
, offset
, mode
[op
]);
711 return luaL_fileresult(L
, 0, NULL
); /* error */
713 lua_pushinteger(L
, (lua_Integer
)l_ftell(f
));
719 static int f_setvbuf(lua_State
*L
) {
720 static const int mode
[] = {_IONBF
, _IOFBF
, _IOLBF
};
721 static const char *const modenames
[] = {"no", "full", "line", NULL
};
723 int op
= luaL_checkoption(L
, 2, NULL
, modenames
);
724 lua_Integer sz
= luaL_optinteger(L
, 3, LUAL_BUFFERSIZE
);
727 res
= setvbuf(f
, NULL
, mode
[op
], (size_t)sz
);
728 return luaL_fileresult(L
, res
== 0, NULL
);
733 static int io_flush(lua_State
*L
) {
734 FILE *f
= getiofile(L
, IO_OUTPUT
);
736 return luaL_fileresult(L
, fflush(f
) == 0, NULL
);
740 static int f_flush(lua_State
*L
) {
743 return luaL_fileresult(L
, fflush(f
) == 0, NULL
);
748 ** functions for 'io' library
750 static const luaL_Reg iolib
[] = {
756 {"output", io_output
},
759 {"tmpfile", io_tmpfile
},
767 ** methods for file handles
769 static const luaL_Reg meth
[] = {
776 {"setvbuf", f_setvbuf
},
782 ** metamethods for file handles
784 static const luaL_Reg metameth
[] = {
785 {"__index", NULL
}, /* placeholder */
788 {"__tostring", f_tostring
},
793 static void createmeta(lua_State
*L
) {
794 luaL_newmetatable(L
, LUA_FILEHANDLE
); /* metatable for file handles */
795 luaL_setfuncs(L
, metameth
, 0); /* add metamethods to new metatable */
796 luaL_newlibtable(L
, meth
); /* create method table */
797 luaL_setfuncs(L
, meth
, 0); /* add file methods to method table */
798 lua_setfield(L
, -2, "__index"); /* metatable.__index = method table */
799 lua_pop(L
, 1); /* pop metatable */
804 ** function to (not) close the standard files stdin, stdout, and stderr
806 static int io_noclose(lua_State
*L
) {
807 LStream
*p
= tolstream(L
);
808 p
->closef
= &io_noclose
; /* keep file opened */
810 lua_pushliteral(L
, "cannot close standard file");
815 static void createstdfile(lua_State
*L
, FILE *f
, const char *k
,
817 LStream
*p
= newprefile(L
);
819 p
->closef
= &io_noclose
;
821 lua_pushvalue(L
, -1);
822 lua_setfield(L
, LUA_REGISTRYINDEX
, k
); /* add file to registry */
824 lua_setfield(L
, -2, fname
); /* add file to module */
828 LUAMOD_API
int luaopen_io(lua_State
*L
) {
829 luaL_newlib(L
, iolib
); /* new module */
831 /* create (and set) default files */
832 createstdfile(L
, stdin
, IO_INPUT
, "stdin");
833 createstdfile(L
, stdout
, IO_OUTPUT
, "stdout");
834 createstdfile(L
, stderr
, NULL
, "stderr");