2 ** $Id: liolib.c,v 2.149 2016/05/02 14:03:19 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 #define l_checkmode(mode) \
41 (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
42 (*mode != '+' || (++mode, 1)) && /* skip if char is '+' */ \
43 (strspn(mode, L_MODEEXT) == strlen(mode)))
48 ** {======================================================
49 ** l_popen spawns a new process connected to the current
50 ** one through the file streams.
51 ** =======================================================
54 #if !defined(l_popen) /* { */
56 #if defined(LUA_USE_POSIX) /* { */
58 #define l_popen(L,c,m) (fflush(NULL), popen(c,m))
59 #define l_pclose(L,file) (pclose(file))
61 #elif defined(LUA_USE_WINDOWS) /* }{ */
63 #define l_popen(L,c,m) (_popen(c,m))
64 #define l_pclose(L,file) (_pclose(file))
68 /* ISO C definitions */
69 #define l_popen(L,c,m) \
70 ((void)((void)c, m), \
71 luaL_error(L, "'popen' not supported"), \
73 #define l_pclose(L,file) ((void)L, (void)file, -1)
79 /* }====================================================== */
82 #if !defined(l_getc) /* { */
84 #if defined(LUA_USE_POSIX)
85 #define l_getc(f) getc_unlocked(f)
86 #define l_lockfile(f) flockfile(f)
87 #define l_unlockfile(f) funlockfile(f)
89 #define l_getc(f) getc(f)
90 #define l_lockfile(f) ((void)0)
91 #define l_unlockfile(f) ((void)0)
98 ** {======================================================
99 ** l_fseek: configuration for longer offsets
100 ** =======================================================
103 #if !defined(l_fseek) /* { */
105 #if defined(LUA_USE_POSIX) /* { */
107 #include <sys/types.h>
109 #define l_fseek(f,o,w) fseeko(f,o,w)
110 #define l_ftell(f) ftello(f)
111 #define l_seeknum off_t
113 #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
114 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
116 /* Windows (but not DDK) and Visual C++ 2005 or higher */
117 #define l_fseek(f,o,w) _fseeki64(f,o,w)
118 #define l_ftell(f) _ftelli64(f)
119 #define l_seeknum __int64
123 /* ISO C definitions */
124 #define l_fseek(f,o,w) fseek(f,o,w)
125 #define l_ftell(f) ftell(f)
126 #define l_seeknum long
132 /* }====================================================== */
135 #define IO_PREFIX "_IO_"
136 #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
137 #define IO_INPUT (IO_PREFIX "input")
138 #define IO_OUTPUT (IO_PREFIX "output")
141 typedef luaL_Stream LStream;
144 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
146 #define isclosed(p) ((p)->closef == NULL)
149 static int io_type (lua_State *L) {
152 p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
154 lua_pushnil(L); /* not a file */
155 else if (isclosed(p))
156 lua_pushliteral(L, "closed file");
158 lua_pushliteral(L, "file");
163 static int f_tostring (lua_State *L) {
164 LStream *p = tolstream(L);
166 lua_pushliteral(L, "file (closed)");
168 lua_pushfstring(L, "file (%p)", p->f);
173 static FILE *tofile (lua_State *L) {
174 LStream *p = tolstream(L);
176 luaL_error(L, "attempt to use a closed file");
183 ** When creating file handles, always creates a 'closed' file handle
184 ** before opening the actual file; so, if there is a memory error, the
185 ** handle is in a consistent state.
187 static LStream *newprefile (lua_State *L) {
188 LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
189 p->closef = NULL; /* mark file handle as 'closed' */
190 luaL_setmetatable(L, LUA_FILEHANDLE);
196 ** Calls the 'close' function from a file handle. The 'volatile' avoids
197 ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
200 static int aux_close (lua_State *L) {
201 LStream *p = tolstream(L);
202 volatile lua_CFunction cf = p->closef;
203 p->closef = NULL; /* mark stream as closed */
204 return (*cf)(L); /* close it */
208 static int io_close (lua_State *L) {
209 if (lua_isnone(L, 1)) /* no argument? */
210 lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
211 tofile(L); /* make sure argument is an open stream */
216 static int f_gc (lua_State *L) {
217 LStream *p = tolstream(L);
218 if (!isclosed(p) && p->f != NULL)
219 aux_close(L); /* ignore closed and incompletely open files */
225 ** function to close regular files
227 static int io_fclose (lua_State *L) {
228 LStream *p = tolstream(L);
229 int res = fclose(p->f);
230 return luaL_fileresult(L, (res == 0), NULL);
234 static LStream *newfile (lua_State *L) {
235 LStream *p = newprefile(L);
237 p->closef = &io_fclose;
242 static void opencheck (lua_State *L, const char *fname, const char *mode) {
243 LStream *p = newfile(L);
244 p->f = fopen(fname, mode);
246 luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
250 static int io_open (lua_State *L) {
251 const char *filename = luaL_checkstring(L, 1);
252 const char *mode = luaL_optstring(L, 2, "r");
253 LStream *p = newfile(L);
254 const char *md = mode; /* to traverse/check mode */
255 luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
256 p->f = fopen(filename, mode);
257 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
262 ** function to close 'popen' files
264 static int io_pclose (lua_State *L) {
265 LStream *p = tolstream(L);
266 return luaL_execresult(L, l_pclose(L, p->f));
270 static int io_popen (lua_State *L) {
271 const char *filename = luaL_checkstring(L, 1);
272 const char *mode = luaL_optstring(L, 2, "r");
273 LStream *p = newprefile(L);
274 p->f = l_popen(L, filename, mode);
275 p->closef = &io_pclose;
276 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
280 static int io_tmpfile (lua_State *L) {
281 LStream *p = newfile(L);
283 return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
287 static FILE *getiofile (lua_State *L, const char *findex) {
289 lua_getfield(L, LUA_REGISTRYINDEX, findex);
290 p = (LStream *)lua_touserdata(L, -1);
292 luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
297 static int g_iofile (lua_State *L, const char *f, const char *mode) {
298 if (!lua_isnoneornil(L, 1)) {
299 const char *filename = lua_tostring(L, 1);
301 opencheck(L, filename, mode);
303 tofile(L); /* check that it's a valid file handle */
306 lua_setfield(L, LUA_REGISTRYINDEX, f);
308 /* return current value */
309 lua_getfield(L, LUA_REGISTRYINDEX, f);
314 static int io_input (lua_State *L) {
315 return g_iofile(L, IO_INPUT, "r");
319 static int io_output (lua_State *L) {
320 return g_iofile(L, IO_OUTPUT, "w");
324 static int io_readline (lua_State *L);
328 ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
329 ** in the limit for upvalues of a closure)
331 #define MAXARGLINE 250
333 static void aux_lines (lua_State *L, int toclose) {
334 int n = lua_gettop(L) - 1; /* number of arguments to read */
335 luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
336 lua_pushinteger(L, n); /* number of arguments to read */
337 lua_pushboolean(L, toclose); /* close/not close file when finished */
338 lua_rotate(L, 2, 2); /* move 'n' and 'toclose' to their positions */
339 lua_pushcclosure(L, io_readline, 3 + n);
343 static int f_lines (lua_State *L) {
344 tofile(L); /* check that it's a valid file handle */
350 static int io_lines (lua_State *L) {
352 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
353 if (lua_isnil(L, 1)) { /* no file name? */
354 lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
355 lua_replace(L, 1); /* put it at index 1 */
356 tofile(L); /* check that it's a valid file handle */
357 toclose = 0; /* do not close it after iteration */
359 else { /* open a new file */
360 const char *filename = luaL_checkstring(L, 1);
361 opencheck(L, filename, "r");
362 lua_replace(L, 1); /* put file at index 1 */
363 toclose = 1; /* close it after iteration */
365 aux_lines(L, toclose);
371 ** {======================================================
373 ** =======================================================
377 /* maximum length of a numeral */
378 #if !defined (L_MAXLENNUM)
379 #define L_MAXLENNUM 200
383 /* auxiliary structure used by 'read_number' */
385 FILE *f; /* file being read */
386 int c; /* current character (look ahead) */
387 int n; /* number of elements in buffer 'buff' */
388 char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
393 ** Add current char to buffer (if not out of space) and read next one
395 static int nextc (RN *rn) {
396 if (rn->n >= L_MAXLENNUM) { /* buffer overflow? */
397 rn->buff[0] = '\0'; /* invalidate result */
401 rn->buff[rn->n++] = rn->c; /* save current char */
402 rn->c = l_getc(rn->f); /* read next one */
409 ** Accept current char if it is in 'set' (of size 2)
411 static int test2 (RN *rn, const char *set) {
412 if (rn->c == set[0] || rn->c == set[1])
419 ** Read a sequence of (hex)digits
421 static int readdigits (RN *rn, int hex) {
423 while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
430 ** Read a number: first reads a valid prefix of a numeral into a buffer.
431 ** Then it calls 'lua_stringtonumber' to check whether the format is
432 ** correct and to convert it to a Lua number
434 static int read_number (lua_State *L, FILE *f) {
440 decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
441 decp[1] = '.'; /* always accept a dot */
443 do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
444 test2(&rn, "-+"); /* optional signal */
445 if (test2(&rn, "00")) {
446 if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
447 else count = 1; /* count initial '0' as a valid digit */
449 count += readdigits(&rn, hex); /* integral part */
450 if (test2(&rn, decp)) /* decimal point? */
451 count += readdigits(&rn, hex); /* fractional part */
452 if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
453 test2(&rn, "-+"); /* exponent signal */
454 readdigits(&rn, 0); /* exponent digits */
456 ungetc(rn.c, rn.f); /* unread look-ahead char */
458 rn.buff[rn.n] = '\0'; /* finish string */
459 if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
461 else { /* invalid format */
462 lua_pushnil(L); /* "result" to be removed */
463 return 0; /* read fails */
468 static int test_eof (lua_State *L, FILE *f) {
470 ungetc(c, f); /* no-op when c == EOF */
471 lua_pushliteral(L, "");
476 static int read_line (lua_State *L, FILE *f, int chop) {
479 luaL_buffinit(L, &b);
480 while (c != EOF && c != '\n') { /* repeat until end of line */
481 char *buff = luaL_prepbuffer(&b); /* preallocate buffer */
483 l_lockfile(f); /* no memory errors can happen inside the lock */
484 while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
489 if (!chop && c == '\n') /* want a newline and have one? */
490 luaL_addchar(&b, c); /* add ending newline to result */
491 luaL_pushresult(&b); /* close buffer */
492 /* return ok if read something (either a newline or something else) */
493 return (c == '\n' || lua_rawlen(L, -1) > 0);
497 static void read_all (lua_State *L, FILE *f) {
500 luaL_buffinit(L, &b);
501 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
502 char *p = luaL_prepbuffer(&b);
503 nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
504 luaL_addsize(&b, nr);
505 } while (nr == LUAL_BUFFERSIZE);
506 luaL_pushresult(&b); /* close buffer */
510 static int read_chars (lua_State *L, FILE *f, size_t n) {
511 size_t nr; /* number of chars actually read */
514 luaL_buffinit(L, &b);
515 p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
516 nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
517 luaL_addsize(&b, nr);
518 luaL_pushresult(&b); /* close buffer */
519 return (nr > 0); /* true iff read something */
523 static int g_read (lua_State *L, FILE *f, int first) {
524 int nargs = lua_gettop(L) - 1;
528 if (nargs == 0) { /* no arguments? */
529 success = read_line(L, f, 1);
530 n = first+1; /* to return 1 result */
532 else { /* ensure stack space for all results and for auxlib's buffer */
533 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
535 for (n = first; nargs-- && success; n++) {
536 if (lua_type(L, n) == LUA_TNUMBER) {
537 size_t l = (size_t)luaL_checkinteger(L, n);
538 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
541 const char *p = luaL_checkstring(L, n);
542 if (*p == '*') p++; /* skip optional '*' (for compatibility) */
544 case 'n': /* number */
545 success = read_number(L, f);
548 success = read_line(L, f, 1);
550 case 'L': /* line with end-of-line */
551 success = read_line(L, f, 0);
554 read_all(L, f); /* read entire file */
555 success = 1; /* always success */
558 return luaL_argerror(L, n, "invalid format");
564 return luaL_fileresult(L, 0, NULL);
566 lua_pop(L, 1); /* remove last result */
567 lua_pushnil(L); /* push nil instead */
573 static int io_read (lua_State *L) {
574 return g_read(L, getiofile(L, IO_INPUT), 1);
578 static int f_read (lua_State *L) {
579 return g_read(L, tofile(L), 2);
583 static int io_readline (lua_State *L) {
584 LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
586 int n = (int)lua_tointeger(L, lua_upvalueindex(2));
587 if (isclosed(p)) /* file is already closed? */
588 return luaL_error(L, "file is already closed");
590 luaL_checkstack(L, n, "too many arguments");
591 for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
592 lua_pushvalue(L, lua_upvalueindex(3 + i));
593 n = g_read(L, p->f, 2); /* 'n' is number of results */
594 lua_assert(n > 0); /* should return at least a nil */
595 if (lua_toboolean(L, -n)) /* read at least one value? */
596 return n; /* return them */
597 else { /* first result is nil: EOF or error */
598 if (n > 1) { /* is there error information? */
599 /* 2nd result is error message */
600 return luaL_error(L, "%s", lua_tostring(L, -n + 1));
602 if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
604 lua_pushvalue(L, lua_upvalueindex(1));
605 aux_close(L); /* close it */
611 /* }====================================================== */
614 static int g_write (lua_State *L, FILE *f, int arg) {
615 int nargs = lua_gettop(L) - arg;
617 for (; nargs--; arg++) {
618 if (lua_type(L, arg) == LUA_TNUMBER) {
619 /* optimization: could be done exactly as for strings */
620 int len = lua_isinteger(L, arg)
621 ? fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg))
622 : fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg));
623 status = status && (len > 0);
627 const char *s = luaL_checklstring(L, arg, &l);
628 status = status && (fwrite(s, sizeof(char), l, f) == l);
631 if (status) return 1; /* file handle already on stack top */
632 else return luaL_fileresult(L, status, NULL);
636 static int io_write (lua_State *L) {
637 return g_write(L, getiofile(L, IO_OUTPUT), 1);
641 static int f_write (lua_State *L) {
643 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
644 return g_write(L, f, 2);
648 static int f_seek (lua_State *L) {
649 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
650 static const char *const modenames[] = {"set", "cur", "end", NULL};
652 int op = luaL_checkoption(L, 2, "cur", modenames);
653 lua_Integer p3 = luaL_optinteger(L, 3, 0);
654 l_seeknum offset = (l_seeknum)p3;
655 luaL_argcheck(L, (lua_Integer)offset == p3, 3,
656 "not an integer in proper range");
657 op = l_fseek(f, offset, mode[op]);
659 return luaL_fileresult(L, 0, NULL); /* error */
661 lua_pushinteger(L, (lua_Integer)l_ftell(f));
667 static int f_setvbuf (lua_State *L) {
668 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
669 static const char *const modenames[] = {"no", "full", "line", NULL};
671 int op = luaL_checkoption(L, 2, NULL, modenames);
672 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
673 int res = setvbuf(f, NULL, mode[op], (size_t)sz);
674 return luaL_fileresult(L, res == 0, NULL);
679 static int io_flush (lua_State *L) {
680 return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
684 static int f_flush (lua_State *L) {
685 return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
690 ** functions for 'io' library
692 static const luaL_Reg iolib[] = {
698 {"output", io_output},
701 {"tmpfile", io_tmpfile},
709 ** methods for file handles
711 static const luaL_Reg flib[] = {
717 {"setvbuf", f_setvbuf},
720 {"__tostring", f_tostring},
725 static void createmeta (lua_State *L) {
726 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
727 lua_pushvalue(L, -1); /* push metatable */
728 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
729 luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
730 lua_pop(L, 1); /* pop new metatable */
735 ** function to (not) close the standard files stdin, stdout, and stderr
737 static int io_noclose (lua_State *L) {
738 LStream *p = tolstream(L);
739 p->closef = &io_noclose; /* keep file opened */
741 lua_pushliteral(L, "cannot close standard file");
746 static void createstdfile (lua_State *L, FILE *f, const char *k,
748 LStream *p = newprefile(L);
750 p->closef = &io_noclose;
752 lua_pushvalue(L, -1);
753 lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
755 lua_setfield(L, -2, fname); /* add file to module */
759 LUAMOD_API int luaopen_io (lua_State *L) {
760 luaL_newlib(L, iolib); /* new module */
762 /* create (and set) default files */
763 createstdfile(L, stdin, IO_INPUT, "stdin");
764 createstdfile(L, stdout, IO_OUTPUT, "stdout");
765 createstdfile(L, stderr, NULL, "stderr");