2 ** $Id: liolib.c,v 2.112.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
9 ** This definition must come before the inclusion of 'stdio.h'; it
10 ** should not affect non-POSIX systems
12 #if !defined(_FILE_OFFSET_BITS)
13 #define _LARGEFILE_SOURCE 1
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: configuration for longer offsets
84 ** =======================================================
87 #if !defined(lua_fseek) && !defined(LUA_ANSI) /* { */
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
108 #if !defined(l_fseek) /* default definitions */
109 #define l_fseek(f,o,w) fseek(f,o,w)
110 #define l_ftell(f) ftell(f)
111 #define l_seeknum long
114 /* }====================================================== */
117 #define IO_PREFIX "_IO_"
118 #define IO_INPUT (IO_PREFIX "input")
119 #define IO_OUTPUT (IO_PREFIX "output")
122 typedef luaL_Stream LStream;
125 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
127 #define isclosed(p) ((p)->closef == NULL)
130 static int io_type (lua_State *L) {
133 p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
135 lua_pushnil(L); /* not a file */
136 else if (isclosed(p))
137 lua_pushliteral(L, "closed file");
139 lua_pushliteral(L, "file");
144 static int f_tostring (lua_State *L) {
145 LStream *p = tolstream(L);
147 lua_pushliteral(L, "file (closed)");
149 lua_pushfstring(L, "file (%p)", p->f);
154 static FILE *tofile (lua_State *L) {
155 LStream *p = tolstream(L);
157 luaL_error(L, "attempt to use a closed file");
164 ** When creating file handles, always creates a `closed' file handle
165 ** before opening the actual file; so, if there is a memory error, the
166 ** file is not left opened.
168 static LStream *newprefile (lua_State *L) {
169 LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
170 p->closef = NULL; /* mark file handle as 'closed' */
171 luaL_setmetatable(L, LUA_FILEHANDLE);
176 static int aux_close (lua_State *L) {
177 LStream *p = tolstream(L);
178 lua_CFunction cf = p->closef;
179 p->closef = NULL; /* mark stream as closed */
180 return (*cf)(L); /* close it */
184 static int io_close (lua_State *L) {
185 if (lua_isnone(L, 1)) /* no argument? */
186 lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
187 tofile(L); /* make sure argument is an open stream */
192 static int f_gc (lua_State *L) {
193 LStream *p = tolstream(L);
194 if (!isclosed(p) && p->f != NULL)
195 aux_close(L); /* ignore closed and incompletely open files */
201 ** function to close regular files
203 static int io_fclose (lua_State *L) {
204 LStream *p = tolstream(L);
205 int res = fclose(p->f);
206 return luaL_fileresult(L, (res == 0), NULL);
210 static LStream *newfile (lua_State *L) {
211 LStream *p = newprefile(L);
213 p->closef = &io_fclose;
218 static void opencheck (lua_State *L, const char *fname, const char *mode) {
219 LStream *p = newfile(L);
220 p->f = fopen(fname, mode);
222 luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
226 static int io_open (lua_State *L) {
227 const char *filename = luaL_checkstring(L, 1);
228 const char *mode = luaL_optstring(L, 2, "r");
229 LStream *p = newfile(L);
230 const char *md = mode; /* to traverse/check mode */
231 luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode");
232 p->f = fopen(filename, mode);
233 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
238 ** function to close 'popen' files
240 static int io_pclose (lua_State *L) {
241 LStream *p = tolstream(L);
242 return luaL_execresult(L, lua_pclose(L, p->f));
246 static int io_popen (lua_State *L) {
247 const char *filename = luaL_checkstring(L, 1);
248 const char *mode = luaL_optstring(L, 2, "r");
249 LStream *p = newprefile(L);
250 p->f = lua_popen(L, filename, mode);
251 p->closef = &io_pclose;
252 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
256 static int io_tmpfile (lua_State *L) {
257 LStream *p = newfile(L);
259 return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
263 static FILE *getiofile (lua_State *L, const char *findex) {
265 lua_getfield(L, LUA_REGISTRYINDEX, findex);
266 p = (LStream *)lua_touserdata(L, -1);
268 luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
273 static int g_iofile (lua_State *L, const char *f, const char *mode) {
274 if (!lua_isnoneornil(L, 1)) {
275 const char *filename = lua_tostring(L, 1);
277 opencheck(L, filename, mode);
279 tofile(L); /* check that it's a valid file handle */
282 lua_setfield(L, LUA_REGISTRYINDEX, f);
284 /* return current value */
285 lua_getfield(L, LUA_REGISTRYINDEX, f);
290 static int io_input (lua_State *L) {
291 return g_iofile(L, IO_INPUT, "r");
295 static int io_output (lua_State *L) {
296 return g_iofile(L, IO_OUTPUT, "w");
300 static int io_readline (lua_State *L);
303 static void aux_lines (lua_State *L, int toclose) {
305 int n = lua_gettop(L) - 1; /* number of arguments to read */
306 /* ensure that arguments will fit here and into 'io_readline' stack */
307 luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options");
308 lua_pushvalue(L, 1); /* file handle */
309 lua_pushinteger(L, n); /* number of arguments to read */
310 lua_pushboolean(L, toclose); /* close/not close file when finished */
311 for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1); /* copy arguments */
312 lua_pushcclosure(L, io_readline, 3 + n);
316 static int f_lines (lua_State *L) {
317 tofile(L); /* check that it's a valid file handle */
323 static int io_lines (lua_State *L) {
325 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
326 if (lua_isnil(L, 1)) { /* no file name? */
327 lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
328 lua_replace(L, 1); /* put it at index 1 */
329 tofile(L); /* check that it's a valid file handle */
330 toclose = 0; /* do not close it after iteration */
332 else { /* open a new file */
333 const char *filename = luaL_checkstring(L, 1);
334 opencheck(L, filename, "r");
335 lua_replace(L, 1); /* put file at index 1 */
336 toclose = 1; /* close it after iteration */
338 aux_lines(L, toclose);
344 ** {======================================================
346 ** =======================================================
350 static int read_number (lua_State *L, FILE *f) {
352 if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
353 lua_pushnumber(L, d);
357 lua_pushnil(L); /* "result" to be removed */
358 return 0; /* read fails */
363 static int test_eof (lua_State *L, FILE *f) {
366 lua_pushlstring(L, NULL, 0);
371 static int read_line (lua_State *L, FILE *f, int chop) {
373 luaL_buffinit(L, &b);
376 char *p = luaL_prepbuffer(&b);
377 if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
378 luaL_pushresult(&b); /* close buffer */
379 return (lua_rawlen(L, -1) > 0); /* check whether read something */
382 if (l == 0 || p[l-1] != '\n')
385 luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
386 luaL_pushresult(&b); /* close buffer */
387 return 1; /* read at least an `eol' */
393 #define MAX_SIZE_T (~(size_t)0)
395 static void read_all (lua_State *L, FILE *f) {
396 size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */
398 luaL_buffinit(L, &b);
400 char *p = luaL_prepbuffsize(&b, rlen);
401 size_t nr = fread(p, sizeof(char), rlen, f);
402 luaL_addsize(&b, nr);
403 if (nr < rlen) break; /* eof? */
404 else if (rlen <= (MAX_SIZE_T / 4)) /* avoid buffers too large */
405 rlen *= 2; /* double buffer size at each iteration */
407 luaL_pushresult(&b); /* close buffer */
411 static int read_chars (lua_State *L, FILE *f, size_t n) {
412 size_t nr; /* number of chars actually read */
415 luaL_buffinit(L, &b);
416 p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
417 nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
418 luaL_addsize(&b, nr);
419 luaL_pushresult(&b); /* close buffer */
420 return (nr > 0); /* true iff read something */
424 static int g_read (lua_State *L, FILE *f, int first) {
425 int nargs = lua_gettop(L) - 1;
429 if (nargs == 0) { /* no arguments? */
430 success = read_line(L, f, 1);
431 n = first+1; /* to return 1 result */
433 else { /* ensure stack space for all results and for auxlib's buffer */
434 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
436 for (n = first; nargs-- && success; n++) {
437 if (lua_type(L, n) == LUA_TNUMBER) {
438 size_t l = (size_t)lua_tointeger(L, n);
439 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
442 const char *p = lua_tostring(L, n);
443 luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
445 case 'n': /* number */
446 success = read_number(L, f);
449 success = read_line(L, f, 1);
451 case 'L': /* line with end-of-line */
452 success = read_line(L, f, 0);
455 read_all(L, f); /* read entire file */
456 success = 1; /* always success */
459 return luaL_argerror(L, n, "invalid format");
465 return luaL_fileresult(L, 0, NULL);
467 lua_pop(L, 1); /* remove last result */
468 lua_pushnil(L); /* push nil instead */
474 static int io_read (lua_State *L) {
475 return g_read(L, getiofile(L, IO_INPUT), 1);
479 static int f_read (lua_State *L) {
480 return g_read(L, tofile(L), 2);
484 static int io_readline (lua_State *L) {
485 LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
487 int n = (int)lua_tointeger(L, lua_upvalueindex(2));
488 if (isclosed(p)) /* file is already closed? */
489 return luaL_error(L, "file is already closed");
491 for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
492 lua_pushvalue(L, lua_upvalueindex(3 + i));
493 n = g_read(L, p->f, 2); /* 'n' is number of results */
494 lua_assert(n > 0); /* should return at least a nil */
495 if (!lua_isnil(L, -n)) /* read at least one value? */
496 return n; /* return them */
497 else { /* first result is nil: EOF or error */
498 if (n > 1) { /* is there error information? */
499 /* 2nd result is error message */
500 return luaL_error(L, "%s", lua_tostring(L, -n + 1));
502 if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
504 lua_pushvalue(L, lua_upvalueindex(1));
505 aux_close(L); /* close it */
511 /* }====================================================== */
514 static int g_write (lua_State *L, FILE *f, int arg) {
515 int nargs = lua_gettop(L) - arg;
517 for (; nargs--; arg++) {
518 if (lua_type(L, arg) == LUA_TNUMBER) {
519 /* optimization: could be done exactly as for strings */
521 fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
525 const char *s = luaL_checklstring(L, arg, &l);
526 status = status && (fwrite(s, sizeof(char), l, f) == l);
529 if (status) return 1; /* file handle already on stack top */
530 else return luaL_fileresult(L, status, NULL);
534 static int io_write (lua_State *L) {
535 return g_write(L, getiofile(L, IO_OUTPUT), 1);
539 static int f_write (lua_State *L) {
541 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
542 return g_write(L, f, 2);
546 static int f_seek (lua_State *L) {
547 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
548 static const char *const modenames[] = {"set", "cur", "end", NULL};
550 int op = luaL_checkoption(L, 2, "cur", modenames);
551 lua_Number p3 = luaL_optnumber(L, 3, 0);
552 l_seeknum offset = (l_seeknum)p3;
553 luaL_argcheck(L, (lua_Number)offset == p3, 3,
554 "not an integer in proper range");
555 op = l_fseek(f, offset, mode[op]);
557 return luaL_fileresult(L, 0, NULL); /* error */
559 lua_pushnumber(L, (lua_Number)l_ftell(f));
565 static int f_setvbuf (lua_State *L) {
566 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
567 static const char *const modenames[] = {"no", "full", "line", NULL};
569 int op = luaL_checkoption(L, 2, NULL, modenames);
570 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
571 int res = setvbuf(f, NULL, mode[op], sz);
572 return luaL_fileresult(L, res == 0, NULL);
577 static int io_flush (lua_State *L) {
578 return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
582 static int f_flush (lua_State *L) {
583 return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
588 ** functions for 'io' library
590 static const luaL_Reg iolib[] = {
596 {"output", io_output},
599 {"tmpfile", io_tmpfile},
607 ** methods for file handles
609 static const luaL_Reg flib[] = {
615 {"setvbuf", f_setvbuf},
618 {"__tostring", f_tostring},
623 static void createmeta (lua_State *L) {
624 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
625 lua_pushvalue(L, -1); /* push metatable */
626 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
627 luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
628 lua_pop(L, 1); /* pop new metatable */
633 ** function to (not) close the standard files stdin, stdout, and stderr
635 static int io_noclose (lua_State *L) {
636 LStream *p = tolstream(L);
637 p->closef = &io_noclose; /* keep file opened */
639 lua_pushliteral(L, "cannot close standard file");
644 static void createstdfile (lua_State *L, FILE *f, const char *k,
646 LStream *p = newprefile(L);
648 p->closef = &io_noclose;
650 lua_pushvalue(L, -1);
651 lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
653 lua_setfield(L, -2, fname); /* add file to module */
657 LUAMOD_API int luaopen_io (lua_State *L) {
658 luaL_newlib(L, iolib); /* new module */
660 /* create (and set) default files */
661 createstdfile(L, stdin, IO_INPUT, "stdin");
662 createstdfile(L, stdout, IO_OUTPUT, "stdout");
663 createstdfile(L, stderr, NULL, "stderr");