2 ** $Id: liolib.c,v 2.151.1.1 2017/04/19 17:29:57 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 f_close (lua_State *L) {
210 tofile(L); /* make sure argument is an open stream */
215 static int io_close (lua_State *L) {
216 if (lua_isnone(L, 1)) /* no argument? */
217 lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
222 static int f_gc (lua_State *L) {
223 LStream *p = tolstream(L);
224 if (!isclosed(p) && p->f != NULL)
225 aux_close(L); /* ignore closed and incompletely open files */
231 ** function to close regular files
233 static int io_fclose (lua_State *L) {
234 LStream *p = tolstream(L);
235 int res = fclose(p->f);
236 return luaL_fileresult(L, (res == 0), NULL);
240 static LStream *newfile (lua_State *L) {
241 LStream *p = newprefile(L);
243 p->closef = &io_fclose;
248 static void opencheck (lua_State *L, const char *fname, const char *mode) {
249 LStream *p = newfile(L);
250 p->f = fopen(fname, mode);
252 luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
256 static int io_open (lua_State *L) {
257 const char *filename = luaL_checkstring(L, 1);
258 const char *mode = luaL_optstring(L, 2, "r");
259 LStream *p = newfile(L);
260 const char *md = mode; /* to traverse/check mode */
261 luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
262 p->f = fopen(filename, mode);
263 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
268 ** function to close 'popen' files
270 static int io_pclose (lua_State *L) {
271 LStream *p = tolstream(L);
272 return luaL_execresult(L, l_pclose(L, p->f));
276 static int io_popen (lua_State *L) {
277 const char *filename = luaL_checkstring(L, 1);
278 const char *mode = luaL_optstring(L, 2, "r");
279 LStream *p = newprefile(L);
280 p->f = l_popen(L, filename, mode);
281 p->closef = &io_pclose;
282 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
286 static int io_tmpfile (lua_State *L) {
287 LStream *p = newfile(L);
289 return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
293 static FILE *getiofile (lua_State *L, const char *findex) {
295 lua_getfield(L, LUA_REGISTRYINDEX, findex);
296 p = (LStream *)lua_touserdata(L, -1);
298 luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
303 static int g_iofile (lua_State *L, const char *f, const char *mode) {
304 if (!lua_isnoneornil(L, 1)) {
305 const char *filename = lua_tostring(L, 1);
307 opencheck(L, filename, mode);
309 tofile(L); /* check that it's a valid file handle */
312 lua_setfield(L, LUA_REGISTRYINDEX, f);
314 /* return current value */
315 lua_getfield(L, LUA_REGISTRYINDEX, f);
320 static int io_input (lua_State *L) {
321 return g_iofile(L, IO_INPUT, "r");
325 static int io_output (lua_State *L) {
326 return g_iofile(L, IO_OUTPUT, "w");
330 static int io_readline (lua_State *L);
334 ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
335 ** in the limit for upvalues of a closure)
337 #define MAXARGLINE 250
339 static void aux_lines (lua_State *L, int toclose) {
340 int n = lua_gettop(L) - 1; /* number of arguments to read */
341 luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
342 lua_pushinteger(L, n); /* number of arguments to read */
343 lua_pushboolean(L, toclose); /* close/not close file when finished */
344 lua_rotate(L, 2, 2); /* move 'n' and 'toclose' to their positions */
345 lua_pushcclosure(L, io_readline, 3 + n);
349 static int f_lines (lua_State *L) {
350 tofile(L); /* check that it's a valid file handle */
356 static int io_lines (lua_State *L) {
358 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
359 if (lua_isnil(L, 1)) { /* no file name? */
360 lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
361 lua_replace(L, 1); /* put it at index 1 */
362 tofile(L); /* check that it's a valid file handle */
363 toclose = 0; /* do not close it after iteration */
365 else { /* open a new file */
366 const char *filename = luaL_checkstring(L, 1);
367 opencheck(L, filename, "r");
368 lua_replace(L, 1); /* put file at index 1 */
369 toclose = 1; /* close it after iteration */
371 aux_lines(L, toclose);
377 ** {======================================================
379 ** =======================================================
383 /* maximum length of a numeral */
384 #if !defined (L_MAXLENNUM)
385 #define L_MAXLENNUM 200
389 /* auxiliary structure used by 'read_number' */
391 FILE *f; /* file being read */
392 int c; /* current character (look ahead) */
393 int n; /* number of elements in buffer 'buff' */
394 char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
399 ** Add current char to buffer (if not out of space) and read next one
401 static int nextc (RN *rn) {
402 if (rn->n >= L_MAXLENNUM) { /* buffer overflow? */
403 rn->buff[0] = '\0'; /* invalidate result */
407 rn->buff[rn->n++] = rn->c; /* save current char */
408 rn->c = l_getc(rn->f); /* read next one */
415 ** Accept current char if it is in 'set' (of size 2)
417 static int test2 (RN *rn, const char *set) {
418 if (rn->c == set[0] || rn->c == set[1])
425 ** Read a sequence of (hex)digits
427 static int readdigits (RN *rn, int hex) {
429 while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
436 ** Read a number: first reads a valid prefix of a numeral into a buffer.
437 ** Then it calls 'lua_stringtonumber' to check whether the format is
438 ** correct and to convert it to a Lua number
440 static int read_number (lua_State *L, FILE *f) {
446 decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
447 decp[1] = '.'; /* always accept a dot */
449 do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
450 test2(&rn, "-+"); /* optional signal */
451 if (test2(&rn, "00")) {
452 if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
453 else count = 1; /* count initial '0' as a valid digit */
455 count += readdigits(&rn, hex); /* integral part */
456 if (test2(&rn, decp)) /* decimal point? */
457 count += readdigits(&rn, hex); /* fractional part */
458 if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
459 test2(&rn, "-+"); /* exponent signal */
460 readdigits(&rn, 0); /* exponent digits */
462 ungetc(rn.c, rn.f); /* unread look-ahead char */
464 rn.buff[rn.n] = '\0'; /* finish string */
465 if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
467 else { /* invalid format */
468 lua_pushnil(L); /* "result" to be removed */
469 return 0; /* read fails */
474 static int test_eof (lua_State *L, FILE *f) {
476 ungetc(c, f); /* no-op when c == EOF */
477 lua_pushliteral(L, "");
482 static int read_line (lua_State *L, FILE *f, int chop) {
485 luaL_buffinit(L, &b);
486 while (c != EOF && c != '\n') { /* repeat until end of line */
487 char *buff = luaL_prepbuffer(&b); /* preallocate buffer */
489 l_lockfile(f); /* no memory errors can happen inside the lock */
490 while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
495 if (!chop && c == '\n') /* want a newline and have one? */
496 luaL_addchar(&b, c); /* add ending newline to result */
497 luaL_pushresult(&b); /* close buffer */
498 /* return ok if read something (either a newline or something else) */
499 return (c == '\n' || lua_rawlen(L, -1) > 0);
503 static void read_all (lua_State *L, FILE *f) {
506 luaL_buffinit(L, &b);
507 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
508 char *p = luaL_prepbuffer(&b);
509 nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
510 luaL_addsize(&b, nr);
511 } while (nr == LUAL_BUFFERSIZE);
512 luaL_pushresult(&b); /* close buffer */
516 static int read_chars (lua_State *L, FILE *f, size_t n) {
517 size_t nr; /* number of chars actually read */
520 luaL_buffinit(L, &b);
521 p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
522 nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
523 luaL_addsize(&b, nr);
524 luaL_pushresult(&b); /* close buffer */
525 return (nr > 0); /* true iff read something */
529 static int g_read (lua_State *L, FILE *f, int first) {
530 int nargs = lua_gettop(L) - 1;
534 if (nargs == 0) { /* no arguments? */
535 success = read_line(L, f, 1);
536 n = first+1; /* to return 1 result */
538 else { /* ensure stack space for all results and for auxlib's buffer */
539 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
541 for (n = first; nargs-- && success; n++) {
542 if (lua_type(L, n) == LUA_TNUMBER) {
543 size_t l = (size_t)luaL_checkinteger(L, n);
544 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
547 const char *p = luaL_checkstring(L, n);
548 if (*p == '*') p++; /* skip optional '*' (for compatibility) */
550 case 'n': /* number */
551 success = read_number(L, f);
554 success = read_line(L, f, 1);
556 case 'L': /* line with end-of-line */
557 success = read_line(L, f, 0);
560 read_all(L, f); /* read entire file */
561 success = 1; /* always success */
564 return luaL_argerror(L, n, "invalid format");
570 return luaL_fileresult(L, 0, NULL);
572 lua_pop(L, 1); /* remove last result */
573 lua_pushnil(L); /* push nil instead */
579 static int io_read (lua_State *L) {
580 return g_read(L, getiofile(L, IO_INPUT), 1);
584 static int f_read (lua_State *L) {
585 return g_read(L, tofile(L), 2);
589 static int io_readline (lua_State *L) {
590 LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
592 int n = (int)lua_tointeger(L, lua_upvalueindex(2));
593 if (isclosed(p)) /* file is already closed? */
594 return luaL_error(L, "file is already closed");
596 luaL_checkstack(L, n, "too many arguments");
597 for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
598 lua_pushvalue(L, lua_upvalueindex(3 + i));
599 n = g_read(L, p->f, 2); /* 'n' is number of results */
600 lua_assert(n > 0); /* should return at least a nil */
601 if (lua_toboolean(L, -n)) /* read at least one value? */
602 return n; /* return them */
603 else { /* first result is nil: EOF or error */
604 if (n > 1) { /* is there error information? */
605 /* 2nd result is error message */
606 return luaL_error(L, "%s", lua_tostring(L, -n + 1));
608 if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
610 lua_pushvalue(L, lua_upvalueindex(1));
611 aux_close(L); /* close it */
617 /* }====================================================== */
620 static int g_write (lua_State *L, FILE *f, int arg) {
621 int nargs = lua_gettop(L) - arg;
623 for (; nargs--; arg++) {
624 if (lua_type(L, arg) == LUA_TNUMBER) {
625 /* optimization: could be done exactly as for strings */
626 int len = lua_isinteger(L, arg)
627 ? fprintf(f, LUA_INTEGER_FMT,
628 (LUAI_UACINT)lua_tointeger(L, arg))
629 : fprintf(f, LUA_NUMBER_FMT,
630 (LUAI_UACNUMBER)lua_tonumber(L, arg));
631 status = status && (len > 0);
635 const char *s = luaL_checklstring(L, arg, &l);
636 status = status && (fwrite(s, sizeof(char), l, f) == l);
639 if (status) return 1; /* file handle already on stack top */
640 else return luaL_fileresult(L, status, NULL);
644 static int io_write (lua_State *L) {
645 return g_write(L, getiofile(L, IO_OUTPUT), 1);
649 static int f_write (lua_State *L) {
651 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
652 return g_write(L, f, 2);
656 static int f_seek (lua_State *L) {
657 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
658 static const char *const modenames[] = {"set", "cur", "end", NULL};
660 int op = luaL_checkoption(L, 2, "cur", modenames);
661 lua_Integer p3 = luaL_optinteger(L, 3, 0);
662 l_seeknum offset = (l_seeknum)p3;
663 luaL_argcheck(L, (lua_Integer)offset == p3, 3,
664 "not an integer in proper range");
665 op = l_fseek(f, offset, mode[op]);
667 return luaL_fileresult(L, 0, NULL); /* error */
669 lua_pushinteger(L, (lua_Integer)l_ftell(f));
675 static int f_setvbuf (lua_State *L) {
676 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
677 static const char *const modenames[] = {"no", "full", "line", NULL};
679 int op = luaL_checkoption(L, 2, NULL, modenames);
680 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
681 int res = setvbuf(f, NULL, mode[op], (size_t)sz);
682 return luaL_fileresult(L, res == 0, NULL);
687 static int io_flush (lua_State *L) {
688 return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
692 static int f_flush (lua_State *L) {
693 return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
698 ** functions for 'io' library
700 static const luaL_Reg iolib[] = {
706 {"output", io_output},
709 {"tmpfile", io_tmpfile},
717 ** methods for file handles
719 static const luaL_Reg flib[] = {
725 {"setvbuf", f_setvbuf},
728 {"__tostring", f_tostring},
733 static void createmeta (lua_State *L) {
734 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
735 lua_pushvalue(L, -1); /* push metatable */
736 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
737 luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
738 lua_pop(L, 1); /* pop new metatable */
743 ** function to (not) close the standard files stdin, stdout, and stderr
745 static int io_noclose (lua_State *L) {
746 LStream *p = tolstream(L);
747 p->closef = &io_noclose; /* keep file opened */
749 lua_pushliteral(L, "cannot close standard file");
754 static void createstdfile (lua_State *L, FILE *f, const char *k,
756 LStream *p = newprefile(L);
758 p->closef = &io_noclose;
760 lua_pushvalue(L, -1);
761 lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
763 lua_setfield(L, -2, fname); /* add file to module */
767 LUAMOD_API int luaopen_io (lua_State *L) {
768 luaL_newlib(L, iolib); /* new module */
770 /* create (and set) default files */
771 createstdfile(L, stdin, IO_INPUT, "stdin");
772 createstdfile(L, stdout, IO_OUTPUT, "stdout");
773 createstdfile(L, stderr, NULL, "stderr");