2 ** $Id: liolib.c,v 2.151 2016/12/20 18:37:00 roberto Exp $
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 != '+' || (++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))
69 /* ISO C definitions */
70 #define l_popen(L,c,m) \
71 ((void)((void)c, m), \
72 luaL_error(L, "'popen' not supported"), \
74 #define l_pclose(L,file) ((void)L, (void)file, -1)
80 /* }====================================================== */
83 #if !defined(l_getc) /* { */
85 #if defined(LUA_USE_POSIX)
86 #define l_getc(f) getc_unlocked(f)
87 #define l_lockfile(f) flockfile(f)
88 #define l_unlockfile(f) funlockfile(f)
90 #define l_getc(f) getc(f)
91 #define l_lockfile(f) ((void)0)
92 #define l_unlockfile(f) ((void)0)
99 ** {======================================================
100 ** l_fseek: configuration for longer offsets
101 ** =======================================================
104 #if !defined(l_fseek) /* { */
106 #if defined(LUA_USE_POSIX) /* { */
108 #include <sys/types.h>
110 #define l_fseek(f,o,w) fseeko(f,o,w)
111 #define l_ftell(f) ftello(f)
112 #define l_seeknum off_t
114 #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
115 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
117 /* Windows (but not DDK) and Visual C++ 2005 or higher */
118 #define l_fseek(f,o,w) _fseeki64(f,o,w)
119 #define l_ftell(f) _ftelli64(f)
120 #define l_seeknum __int64
124 /* ISO C definitions */
125 #define l_fseek(f,o,w) fseek(f,o,w)
126 #define l_ftell(f) ftell(f)
127 #define l_seeknum long
133 /* }====================================================== */
136 #define IO_PREFIX "_IO_"
137 #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
138 #define IO_INPUT (IO_PREFIX "input")
139 #define IO_OUTPUT (IO_PREFIX "output")
142 typedef luaL_Stream LStream;
145 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
147 #define isclosed(p) ((p)->closef == NULL)
150 static int io_type (lua_State *L) {
153 p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
155 lua_pushnil(L); /* not a file */
156 else if (isclosed(p))
157 lua_pushliteral(L, "closed file");
159 lua_pushliteral(L, "file");
164 static int f_tostring (lua_State *L) {
165 LStream *p = tolstream(L);
167 lua_pushliteral(L, "file (closed)");
169 lua_pushfstring(L, "file (%p)", p->f);
174 static FILE *tofile (lua_State *L) {
175 LStream *p = tolstream(L);
177 luaL_error(L, "attempt to use a closed file");
184 ** When creating file handles, always creates a 'closed' file handle
185 ** before opening the actual file; so, if there is a memory error, the
186 ** handle is in a consistent state.
188 static LStream *newprefile (lua_State *L) {
189 LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
190 p->closef = NULL; /* mark file handle as 'closed' */
191 luaL_setmetatable(L, LUA_FILEHANDLE);
197 ** Calls the 'close' function from a file handle. The 'volatile' avoids
198 ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
201 static int aux_close (lua_State *L) {
202 LStream *p = tolstream(L);
203 volatile lua_CFunction cf = p->closef;
204 p->closef = NULL; /* mark stream as closed */
205 return (*cf)(L); /* close it */
209 static int io_close (lua_State *L) {
210 if (lua_isnone(L, 1)) /* no argument? */
211 lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
212 tofile(L); /* make sure argument is an open stream */
217 static int f_gc (lua_State *L) {
218 LStream *p = tolstream(L);
219 if (!isclosed(p) && p->f != NULL)
220 aux_close(L); /* ignore closed and incompletely open files */
226 ** function to close regular files
228 static int io_fclose (lua_State *L) {
229 LStream *p = tolstream(L);
230 int res = fclose(p->f);
231 return luaL_fileresult(L, (res == 0), NULL);
235 static LStream *newfile (lua_State *L) {
236 LStream *p = newprefile(L);
238 p->closef = &io_fclose;
243 static void opencheck (lua_State *L, const char *fname, const char *mode) {
244 LStream *p = newfile(L);
245 p->f = fopen(fname, mode);
247 luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
251 static int io_open (lua_State *L) {
252 const char *filename = luaL_checkstring(L, 1);
253 const char *mode = luaL_optstring(L, 2, "r");
254 LStream *p = newfile(L);
255 const char *md = mode; /* to traverse/check mode */
256 luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
257 p->f = fopen(filename, mode);
258 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
263 ** function to close 'popen' files
265 static int io_pclose (lua_State *L) {
266 LStream *p = tolstream(L);
267 return luaL_execresult(L, l_pclose(L, p->f));
271 static int io_popen (lua_State *L) {
272 const char *filename = luaL_checkstring(L, 1);
273 const char *mode = luaL_optstring(L, 2, "r");
274 LStream *p = newprefile(L);
275 p->f = l_popen(L, filename, mode);
276 p->closef = &io_pclose;
277 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
281 static int io_tmpfile (lua_State *L) {
282 LStream *p = newfile(L);
284 return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
288 static FILE *getiofile (lua_State *L, const char *findex) {
290 lua_getfield(L, LUA_REGISTRYINDEX, findex);
291 p = (LStream *)lua_touserdata(L, -1);
293 luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
298 static int g_iofile (lua_State *L, const char *f, const char *mode) {
299 if (!lua_isnoneornil(L, 1)) {
300 const char *filename = lua_tostring(L, 1);
302 opencheck(L, filename, mode);
304 tofile(L); /* check that it's a valid file handle */
307 lua_setfield(L, LUA_REGISTRYINDEX, f);
309 /* return current value */
310 lua_getfield(L, LUA_REGISTRYINDEX, f);
315 static int io_input (lua_State *L) {
316 return g_iofile(L, IO_INPUT, "r");
320 static int io_output (lua_State *L) {
321 return g_iofile(L, IO_OUTPUT, "w");
325 static int io_readline (lua_State *L);
329 ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
330 ** in the limit for upvalues of a closure)
332 #define MAXARGLINE 250
334 static void aux_lines (lua_State *L, int toclose) {
335 int n = lua_gettop(L) - 1; /* number of arguments to read */
336 luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
337 lua_pushinteger(L, n); /* number of arguments to read */
338 lua_pushboolean(L, toclose); /* close/not close file when finished */
339 lua_rotate(L, 2, 2); /* move 'n' and 'toclose' to their positions */
340 lua_pushcclosure(L, io_readline, 3 + n);
344 static int f_lines (lua_State *L) {
345 tofile(L); /* check that it's a valid file handle */
351 static int io_lines (lua_State *L) {
353 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
354 if (lua_isnil(L, 1)) { /* no file name? */
355 lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
356 lua_replace(L, 1); /* put it at index 1 */
357 tofile(L); /* check that it's a valid file handle */
358 toclose = 0; /* do not close it after iteration */
360 else { /* open a new file */
361 const char *filename = luaL_checkstring(L, 1);
362 opencheck(L, filename, "r");
363 lua_replace(L, 1); /* put file at index 1 */
364 toclose = 1; /* close it after iteration */
366 aux_lines(L, toclose);
372 ** {======================================================
374 ** =======================================================
378 /* maximum length of a numeral */
379 #if !defined (L_MAXLENNUM)
380 #define L_MAXLENNUM 200
384 /* auxiliary structure used by 'read_number' */
386 FILE *f; /* file being read */
387 int c; /* current character (look ahead) */
388 int n; /* number of elements in buffer 'buff' */
389 char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
394 ** Add current char to buffer (if not out of space) and read next one
396 static int nextc (RN *rn) {
397 if (rn->n >= L_MAXLENNUM) { /* buffer overflow? */
398 rn->buff[0] = '\0'; /* invalidate result */
402 rn->buff[rn->n++] = rn->c; /* save current char */
403 rn->c = l_getc(rn->f); /* read next one */
410 ** Accept current char if it is in 'set' (of size 2)
412 static int test2 (RN *rn, const char *set) {
413 if (rn->c == set[0] || rn->c == set[1])
420 ** Read a sequence of (hex)digits
422 static int readdigits (RN *rn, int hex) {
424 while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
431 ** Read a number: first reads a valid prefix of a numeral into a buffer.
432 ** Then it calls 'lua_stringtonumber' to check whether the format is
433 ** correct and to convert it to a Lua number
435 static int read_number (lua_State *L, FILE *f) {
441 decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
442 decp[1] = '.'; /* always accept a dot */
444 do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
445 test2(&rn, "-+"); /* optional signal */
446 if (test2(&rn, "00")) {
447 if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
448 else count = 1; /* count initial '0' as a valid digit */
450 count += readdigits(&rn, hex); /* integral part */
451 if (test2(&rn, decp)) /* decimal point? */
452 count += readdigits(&rn, hex); /* fractional part */
453 if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
454 test2(&rn, "-+"); /* exponent signal */
455 readdigits(&rn, 0); /* exponent digits */
457 ungetc(rn.c, rn.f); /* unread look-ahead char */
459 rn.buff[rn.n] = '\0'; /* finish string */
460 if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
462 else { /* invalid format */
463 lua_pushnil(L); /* "result" to be removed */
464 return 0; /* read fails */
469 static int test_eof (lua_State *L, FILE *f) {
471 ungetc(c, f); /* no-op when c == EOF */
472 lua_pushliteral(L, "");
477 static int read_line (lua_State *L, FILE *f, int chop) {
480 luaL_buffinit(L, &b);
481 while (c != EOF && c != '\n') { /* repeat until end of line */
482 char *buff = luaL_prepbuffer(&b); /* preallocate buffer */
484 l_lockfile(f); /* no memory errors can happen inside the lock */
485 while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
490 if (!chop && c == '\n') /* want a newline and have one? */
491 luaL_addchar(&b, c); /* add ending newline to result */
492 luaL_pushresult(&b); /* close buffer */
493 /* return ok if read something (either a newline or something else) */
494 return (c == '\n' || lua_rawlen(L, -1) > 0);
498 static void read_all (lua_State *L, FILE *f) {
501 luaL_buffinit(L, &b);
502 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
503 char *p = luaL_prepbuffer(&b);
504 nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
505 luaL_addsize(&b, nr);
506 } while (nr == LUAL_BUFFERSIZE);
507 luaL_pushresult(&b); /* close buffer */
511 static int read_chars (lua_State *L, FILE *f, size_t n) {
512 size_t nr; /* number of chars actually read */
515 luaL_buffinit(L, &b);
516 p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
517 nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
518 luaL_addsize(&b, nr);
519 luaL_pushresult(&b); /* close buffer */
520 return (nr > 0); /* true iff read something */
524 static int g_read (lua_State *L, FILE *f, int first) {
525 int nargs = lua_gettop(L) - 1;
529 if (nargs == 0) { /* no arguments? */
530 success = read_line(L, f, 1);
531 n = first+1; /* to return 1 result */
533 else { /* ensure stack space for all results and for auxlib's buffer */
534 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
536 for (n = first; nargs-- && success; n++) {
537 if (lua_type(L, n) == LUA_TNUMBER) {
538 size_t l = (size_t)luaL_checkinteger(L, n);
539 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
542 const char *p = luaL_checkstring(L, n);
543 if (*p == '*') p++; /* skip optional '*' (for compatibility) */
545 case 'n': /* number */
546 success = read_number(L, f);
549 success = read_line(L, f, 1);
551 case 'L': /* line with end-of-line */
552 success = read_line(L, f, 0);
555 read_all(L, f); /* read entire file */
556 success = 1; /* always success */
559 return luaL_argerror(L, n, "invalid format");
565 return luaL_fileresult(L, 0, NULL);
567 lua_pop(L, 1); /* remove last result */
568 lua_pushnil(L); /* push nil instead */
574 static int io_read (lua_State *L) {
575 return g_read(L, getiofile(L, IO_INPUT), 1);
579 static int f_read (lua_State *L) {
580 return g_read(L, tofile(L), 2);
584 static int io_readline (lua_State *L) {
585 LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
587 int n = (int)lua_tointeger(L, lua_upvalueindex(2));
588 if (isclosed(p)) /* file is already closed? */
589 return luaL_error(L, "file is already closed");
591 luaL_checkstack(L, n, "too many arguments");
592 for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
593 lua_pushvalue(L, lua_upvalueindex(3 + i));
594 n = g_read(L, p->f, 2); /* 'n' is number of results */
595 lua_assert(n > 0); /* should return at least a nil */
596 if (lua_toboolean(L, -n)) /* read at least one value? */
597 return n; /* return them */
598 else { /* first result is nil: EOF or error */
599 if (n > 1) { /* is there error information? */
600 /* 2nd result is error message */
601 return luaL_error(L, "%s", lua_tostring(L, -n + 1));
603 if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
605 lua_pushvalue(L, lua_upvalueindex(1));
606 aux_close(L); /* close it */
612 /* }====================================================== */
615 static int g_write (lua_State *L, FILE *f, int arg) {
616 int nargs = lua_gettop(L) - arg;
618 for (; nargs--; arg++) {
619 if (lua_type(L, arg) == LUA_TNUMBER) {
620 /* optimization: could be done exactly as for strings */
621 int len = lua_isinteger(L, arg)
622 ? fprintf(f, LUA_INTEGER_FMT,
623 (LUAI_UACINT)lua_tointeger(L, arg))
624 : fprintf(f, LUA_NUMBER_FMT,
625 (LUAI_UACNUMBER)lua_tonumber(L, arg));
626 status = status && (len > 0);
630 const char *s = luaL_checklstring(L, arg, &l);
631 status = status && (fwrite(s, sizeof(char), l, f) == l);
634 if (status) return 1; /* file handle already on stack top */
635 else return luaL_fileresult(L, status, NULL);
639 static int io_write (lua_State *L) {
640 return g_write(L, getiofile(L, IO_OUTPUT), 1);
644 static int f_write (lua_State *L) {
646 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
647 return g_write(L, f, 2);
651 static int f_seek (lua_State *L) {
652 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
653 static const char *const modenames[] = {"set", "cur", "end", NULL};
655 int op = luaL_checkoption(L, 2, "cur", modenames);
656 lua_Integer p3 = luaL_optinteger(L, 3, 0);
657 l_seeknum offset = (l_seeknum)p3;
658 luaL_argcheck(L, (lua_Integer)offset == p3, 3,
659 "not an integer in proper range");
660 op = l_fseek(f, offset, mode[op]);
662 return luaL_fileresult(L, 0, NULL); /* error */
664 lua_pushinteger(L, (lua_Integer)l_ftell(f));
670 static int f_setvbuf (lua_State *L) {
671 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
672 static const char *const modenames[] = {"no", "full", "line", NULL};
674 int op = luaL_checkoption(L, 2, NULL, modenames);
675 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
676 int res = setvbuf(f, NULL, mode[op], (size_t)sz);
677 return luaL_fileresult(L, res == 0, NULL);
682 static int io_flush (lua_State *L) {
683 return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
687 static int f_flush (lua_State *L) {
688 return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
693 ** functions for 'io' library
695 static const luaL_Reg iolib[] = {
701 {"output", io_output},
704 {"tmpfile", io_tmpfile},
712 ** methods for file handles
714 static const luaL_Reg flib[] = {
720 {"setvbuf", f_setvbuf},
723 {"__tostring", f_tostring},
728 static void createmeta (lua_State *L) {
729 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
730 lua_pushvalue(L, -1); /* push metatable */
731 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
732 luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
733 lua_pop(L, 1); /* pop new metatable */
738 ** function to (not) close the standard files stdin, stdout, and stderr
740 static int io_noclose (lua_State *L) {
741 LStream *p = tolstream(L);
742 p->closef = &io_noclose; /* keep file opened */
744 lua_pushliteral(L, "cannot close standard file");
749 static void createstdfile (lua_State *L, FILE *f, const char *k,
751 LStream *p = newprefile(L);
753 p->closef = &io_noclose;
755 lua_pushvalue(L, -1);
756 lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
758 lua_setfield(L, -2, fname); /* add file to module */
762 LUAMOD_API int luaopen_io (lua_State *L) {
763 luaL_newlib(L, iolib); /* new module */
765 /* create (and set) default files */
766 createstdfile(L, stdin, IO_INPUT, "stdin");
767 createstdfile(L, stdout, IO_OUTPUT, "stdout");
768 createstdfile(L, stderr, NULL, "stderr");