1 /*
2 ** $Id: liolib.c $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
5 */
6
7 #define liolib_c
8 #define LUA_LIB
9
10 #include "lprefix.h"
11
12
13 #include <ctype.h>
14 #include <errno.h>
15 #include <locale.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19
20 #include "lua.h"
21
22 #include "lauxlib.h"
23 #include "lualib.h"
24
25
26
27
28 /*
29 ** Change this macro to accept other modes for 'fopen' besides
30 ** the standard ones.
31 */
32 #if !defined(l_checkmode)
33
34 /* accepted extensions to 'mode' in 'fopen' */
35 #if !defined(L_MODEEXT)
36 #define L_MODEEXT "b"
37 #endif
38
39 /* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
l_checkmode(const char * mode)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 */
44 }
45
46 #endif
47
48 /*
49 ** {======================================================
50 ** l_popen spawns a new process connected to the current
51 ** one through the file streams.
52 ** =======================================================
53 */
54
55 #if !defined(l_popen) /* { */
56
57 #if defined(LUA_USE_POSIX) /* { */
58
59 #define l_popen(L,c,m) (fflush(NULL), popen(c,m))
60 #define l_pclose(L,file) (pclose(file))
61
62 #elif defined(LUA_USE_WINDOWS) /* }{ */
63
64 #define l_popen(L,c,m) (_popen(c,m))
65 #define l_pclose(L,file) (_pclose(file))
66
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')))
71 #endif
72
73 #else /* }{ */
74
75 /* ISO C definitions */
76 #define l_popen(L,c,m) \
77 ((void)c, (void)m, \
78 luaL_error(L, "'popen' not supported"), \
79 (FILE*)0)
80 #define l_pclose(L,file) ((void)L, (void)file, -1)
81
82 #endif /* } */
83
84 #endif /* } */
85
86
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')
90 #endif
91
92 /* }====================================================== */
93
94
95 #if !defined(l_getc) /* { */
96
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)
101 #else
102 #define l_getc(f) getc(f)
103 #define l_lockfile(f) ((void)0)
104 #define l_unlockfile(f) ((void)0)
105 #endif
106
107 #endif /* } */
108
109
110 /*
111 ** {======================================================
112 ** l_fseek: configuration for longer offsets
113 ** =======================================================
114 */
115
116 #if !defined(l_fseek) /* { */
117
118 #if defined(LUA_USE_POSIX) /* { */
119
120 #include <sys/types.h>
121
122 #define l_fseek(f,o,w) fseeko(f,o,w)
123 #define l_ftell(f) ftello(f)
124 #define l_seeknum off_t
125
126 #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
127 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
128
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
133
134 #else /* }{ */
135
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
140
141 #endif /* } */
142
143 #endif /* } */
144
145 /* }====================================================== */
146
147
148
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")
153
154
155 typedef luaL_Stream LStream;
156
157
158 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
159
160 #define isclosed(p) ((p)->closef == NULL)
161
162
io_type(lua_State * L)163 static int io_type (lua_State *L) {
164 LStream *p;
165 luaL_checkany(L, 1);
166 p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
167 if (p == NULL)
168 luaL_pushfail(L); /* not a file */
169 else if (isclosed(p))
170 lua_pushliteral(L, "closed file");
171 else
172 lua_pushliteral(L, "file");
173 return 1;
174 }
175
176
f_tostring(lua_State * L)177 static int f_tostring (lua_State *L) {
178 LStream *p = tolstream(L);
179 if (isclosed(p))
180 lua_pushliteral(L, "file (closed)");
181 else
182 lua_pushfstring(L, "file (%p)", p->f);
183 return 1;
184 }
185
186
tofile(lua_State * L)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");
191 lua_assert(p->f);
192 return p->f;
193 }
194
195
196 /*
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.
200 */
newprefile(lua_State * L)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);
205 return p;
206 }
207
208
209 /*
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
212 ** 32 bits).
213 */
aux_close(lua_State * L)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 */
219 }
220
221
f_close(lua_State * L)222 static int f_close (lua_State *L) {
223 tofile(L); /* make sure argument is an open stream */
224 return aux_close(L);
225 }
226
227
io_close(lua_State * L)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 */
231 return f_close(L);
232 }
233
234
f_gc(lua_State * L)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 */
239 return 0;
240 }
241
242
243 /*
244 ** function to close regular files
245 */
io_fclose(lua_State * L)246 static int io_fclose (lua_State *L) {
247 LStream *p = tolstream(L);
248 errno = 0;
249 return luaL_fileresult(L, (fclose(p->f) == 0), NULL);
250 }
251
252
newfile(lua_State * L)253 static LStream *newfile (lua_State *L) {
254 LStream *p = newprefile(L);
255 p->f = NULL;
256 p->closef = &io_fclose;
257 return p;
258 }
259
260
opencheck(lua_State * L,const char * fname,const char * mode)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));
266 }
267
268
io_open(lua_State * L)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");
275 errno = 0;
276 p->f = fopen(filename, mode);
277 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
278 }
279
280
281 /*
282 ** function to close 'popen' files
283 */
io_pclose(lua_State * L)284 static int io_pclose (lua_State *L) {
285 LStream *p = tolstream(L);
286 errno = 0;
287 return luaL_execresult(L, l_pclose(L, p->f));
288 }
289
290
io_popen(lua_State * L)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");
296 errno = 0;
297 p->f = l_popen(L, filename, mode);
298 p->closef = &io_pclose;
299 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
300 }
301
302
io_tmpfile(lua_State * L)303 static int io_tmpfile (lua_State *L) {
304 LStream *p = newfile(L);
305 errno = 0;
306 p->f = tmpfile();
307 return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
308 }
309
310
getiofile(lua_State * L,const char * findex)311 static FILE *getiofile (lua_State *L, const char *findex) {
312 LStream *p;
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);
317 return p->f;
318 }
319
320
g_iofile(lua_State * L,const char * f,const char * mode)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);
324 if (filename)
325 opencheck(L, filename, mode);
326 else {
327 tofile(L); /* check that it's a valid file handle */
328 lua_pushvalue(L, 1);
329 }
330 lua_setfield(L, LUA_REGISTRYINDEX, f);
331 }
332 /* return current value */
333 lua_getfield(L, LUA_REGISTRYINDEX, f);
334 return 1;
335 }
336
337
io_input(lua_State * L)338 static int io_input (lua_State *L) {
339 return g_iofile(L, IO_INPUT, "r");
340 }
341
342
io_output(lua_State * L)343 static int io_output (lua_State *L) {
344 return g_iofile(L, IO_OUTPUT, "w");
345 }
346
347
348 static int io_readline (lua_State *L);
349
350
351 /*
352 ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
353 ** in the limit for upvalues of a closure)
354 */
355 #define MAXARGLINE 250
356
357 /*
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)
365 */
aux_lines(lua_State * L,int toclose)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);
374 }
375
376
f_lines(lua_State * L)377 static int f_lines (lua_State *L) {
378 tofile(L); /* check that it's a valid file handle */
379 aux_lines(L, 0);
380 return 1;
381 }
382
383
384 /*
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).
388 */
io_lines(lua_State * L)389 static int io_lines (lua_State *L) {
390 int toclose;
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 }
398 else { /* open a new file */
399 const char *filename = luaL_checkstring(L, 1);
400 opencheck(L, filename, "r");
401 lua_replace(L, 1); /* put file at index 1 */
402 toclose = 1; /* close it after iteration */
403 }
404 aux_lines(L, toclose); /* push iteration function */
405 if (toclose) {
406 lua_pushnil(L); /* state */
407 lua_pushnil(L); /* control */
408 lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */
409 return 4;
410 }
411 else
412 return 1;
413 }
414
415
416 /*
417 ** {======================================================
418 ** READ
419 ** =======================================================
420 */
421
422
423 /* maximum length of a numeral */
424 #if !defined (L_MAXLENNUM)
425 #define L_MAXLENNUM 200
426 #endif
427
428
429 /* auxiliary structure used by 'read_number' */
430 typedef struct {
431 FILE *f; /* file being read */
432 int c; /* current character (look ahead) */
433 int n; /* number of elements in buffer 'buff' */
434 char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
435 } RN;
436
437
438 /*
439 ** Add current char to buffer (if not out of space) and read next one
440 */
nextc(RN * rn)441 static int nextc (RN *rn) {
442 if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */
443 rn->buff[0] = '\0'; /* invalidate result */
444 return 0; /* fail */
445 }
446 else {
447 rn->buff[rn->n++] = rn->c; /* save current char */
448 rn->c = l_getc(rn->f); /* read next one */
449 return 1;
450 }
451 }
452
453
454 /*
455 ** Accept current char if it is in 'set' (of size 2)
456 */
test2(RN * rn,const char * set)457 static int test2 (RN *rn, const char *set) {
458 if (rn->c == set[0] || rn->c == set[1])
459 return nextc(rn);
460 else return 0;
461 }
462
463
464 /*
465 ** Read a sequence of (hex)digits
466 */
readdigits(RN * rn,int hex)467 static int readdigits (RN *rn, int hex) {
468 int count = 0;
469 while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
470 count++;
471 return count;
472 }
473
474
475 /*
476 ** Read a number: first reads a valid prefix of a numeral into a buffer.
477 ** Then it calls 'lua_stringtonumber' to check whether the format is
478 ** correct and to convert it to a Lua number.
479 */
read_number(lua_State * L,FILE * f)480 static int read_number (lua_State *L, FILE *f) {
481 RN rn;
482 int count = 0;
483 int hex = 0;
484 char decp[2];
485 rn.f = f; rn.n = 0;
486 decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
487 decp[1] = '.'; /* always accept a dot */
488 l_lockfile(rn.f);
489 do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
490 test2(&rn, "-+"); /* optional sign */
491 if (test2(&rn, "00")) {
492 if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
493 else count = 1; /* count initial '0' as a valid digit */
494 }
495 count += readdigits(&rn, hex); /* integral part */
496 if (test2(&rn, decp)) /* decimal point? */
497 count += readdigits(&rn, hex); /* fractional part */
498 if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
499 test2(&rn, "-+"); /* exponent sign */
500 readdigits(&rn, 0); /* exponent digits */
501 }
502 ungetc(rn.c, rn.f); /* unread look-ahead char */
503 l_unlockfile(rn.f);
504 rn.buff[rn.n] = '\0'; /* finish string */
505 if (l_likely(lua_stringtonumber(L, rn.buff)))
506 return 1; /* ok, it is a valid number */
507 else { /* invalid format */
508 lua_pushnil(L); /* "result" to be removed */
509 return 0; /* read fails */
510 }
511 }
512
513
test_eof(lua_State * L,FILE * f)514 static int test_eof (lua_State *L, FILE *f) {
515 int c = getc(f);
516 ungetc(c, f); /* no-op when c == EOF */
517 lua_pushliteral(L, "");
518 return (c != EOF);
519 }
520
521
read_line(lua_State * L,FILE * f,int chop)522 static int read_line (lua_State *L, FILE *f, int chop) {
523 luaL_Buffer b;
524 int c;
525 luaL_buffinit(L, &b);
526 do { /* may need to read several chunks to get whole line */
527 char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */
528 int i = 0;
529 l_lockfile(f); /* no memory errors can happen inside the lock */
530 while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
531 buff[i++] = c; /* read up to end of line or buffer limit */
532 l_unlockfile(f);
533 luaL_addsize(&b, i);
534 } while (c != EOF && c != '\n'); /* repeat until end of line */
535 if (!chop && c == '\n') /* want a newline and have one? */
536 luaL_addchar(&b, c); /* add ending newline to result */
537 luaL_pushresult(&b); /* close buffer */
538 /* return ok if read something (either a newline or something else) */
539 return (c == '\n' || lua_rawlen(L, -1) > 0);
540 }
541
542
read_all(lua_State * L,FILE * f)543 static void read_all (lua_State *L, FILE *f) {
544 size_t nr;
545 luaL_Buffer b;
546 luaL_buffinit(L, &b);
547 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
548 char *p = luaL_prepbuffer(&b);
549 nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
550 luaL_addsize(&b, nr);
551 } while (nr == LUAL_BUFFERSIZE);
552 luaL_pushresult(&b); /* close buffer */
553 }
554
555
read_chars(lua_State * L,FILE * f,size_t n)556 static int read_chars (lua_State *L, FILE *f, size_t n) {
557 size_t nr; /* number of chars actually read */
558 char *p;
559 luaL_Buffer b;
560 luaL_buffinit(L, &b);
561 p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
562 nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
563 luaL_addsize(&b, nr);
564 luaL_pushresult(&b); /* close buffer */
565 return (nr > 0); /* true iff read something */
566 }
567
568
g_read(lua_State * L,FILE * f,int first)569 static int g_read (lua_State *L, FILE *f, int first) {
570 int nargs = lua_gettop(L) - 1;
571 int n, success;
572 clearerr(f);
573 errno = 0;
574 if (nargs == 0) { /* no arguments? */
575 success = read_line(L, f, 1);
576 n = first + 1; /* to return 1 result */
577 }
578 else {
579 /* ensure stack space for all results and for auxlib's buffer */
580 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
581 success = 1;
582 for (n = first; nargs-- && success; n++) {
583 if (lua_type(L, n) == LUA_TNUMBER) {
584 size_t l = (size_t)luaL_checkinteger(L, n);
585 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
586 }
587 else {
588 const char *p = luaL_checkstring(L, n);
589 if (*p == '*') p++; /* skip optional '*' (for compatibility) */
590 switch (*p) {
591 case 'n': /* number */
592 success = read_number(L, f);
593 break;
594 case 'l': /* line */
595 success = read_line(L, f, 1);
596 break;
597 case 'L': /* line with end-of-line */
598 success = read_line(L, f, 0);
599 break;
600 case 'a': /* file */
601 read_all(L, f); /* read entire file */
602 success = 1; /* always success */
603 break;
604 default:
605 return luaL_argerror(L, n, "invalid format");
606 }
607 }
608 }
609 }
610 if (ferror(f))
611 return luaL_fileresult(L, 0, NULL);
612 if (!success) {
613 lua_pop(L, 1); /* remove last result */
614 luaL_pushfail(L); /* push nil instead */
615 }
616 return n - first;
617 }
618
619
io_read(lua_State * L)620 static int io_read (lua_State *L) {
621 return g_read(L, getiofile(L, IO_INPUT), 1);
622 }
623
624
f_read(lua_State * L)625 static int f_read (lua_State *L) {
626 return g_read(L, tofile(L), 2);
627 }
628
629
630 /*
631 ** Iteration function for 'lines'.
632 */
io_readline(lua_State * L)633 static int io_readline (lua_State *L) {
634 LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
635 int i;
636 int n = (int)lua_tointeger(L, lua_upvalueindex(2));
637 if (isclosed(p)) /* file is already closed? */
638 return luaL_error(L, "file is already closed");
639 lua_settop(L , 1);
640 luaL_checkstack(L, n, "too many arguments");
641 for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
642 lua_pushvalue(L, lua_upvalueindex(3 + i));
643 n = g_read(L, p->f, 2); /* 'n' is number of results */
644 lua_assert(n > 0); /* should return at least a nil */
645 if (lua_toboolean(L, -n)) /* read at least one value? */
646 return n; /* return them */
647 else { /* first result is false: EOF or error */
648 if (n > 1) { /* is there error information? */
649 /* 2nd result is error message */
650 return luaL_error(L, "%s", lua_tostring(L, -n + 1));
651 }
652 if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
653 lua_settop(L, 0); /* clear stack */
654 lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */
655 aux_close(L); /* close it */
656 }
657 return 0;
658 }
659 }
660
661 /* }====================================================== */
662
663
g_write(lua_State * L,FILE * f,int arg)664 static int g_write (lua_State *L, FILE *f, int arg) {
665 int nargs = lua_gettop(L) - arg;
666 int status = 1;
667 errno = 0;
668 for (; nargs--; arg++) {
669 if (lua_type(L, arg) == LUA_TNUMBER) {
670 /* optimization: could be done exactly as for strings */
671 int len = lua_isinteger(L, arg)
672 ? fprintf(f, LUA_INTEGER_FMT,
673 (LUAI_UACINT)lua_tointeger(L, arg))
674 : fprintf(f, LUA_NUMBER_FMT,
675 (LUAI_UACNUMBER)lua_tonumber(L, arg));
676 status = status && (len > 0);
677 }
678 else {
679 size_t l;
680 const char *s = luaL_checklstring(L, arg, &l);
681 status = status && (fwrite(s, sizeof(char), l, f) == l);
682 }
683 }
684 if (l_likely(status))
685 return 1; /* file handle already on stack top */
686 else
687 return luaL_fileresult(L, status, NULL);
688 }
689
690
io_write(lua_State * L)691 static int io_write (lua_State *L) {
692 return g_write(L, getiofile(L, IO_OUTPUT), 1);
693 }
694
695
f_write(lua_State * L)696 static int f_write (lua_State *L) {
697 FILE *f = tofile(L);
698 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
699 return g_write(L, f, 2);
700 }
701
702
f_seek(lua_State * L)703 static int f_seek (lua_State *L) {
704 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
705 static const char *const modenames[] = {"set", "cur", "end", NULL};
706 FILE *f = tofile(L);
707 int op = luaL_checkoption(L, 2, "cur", modenames);
708 lua_Integer p3 = luaL_optinteger(L, 3, 0);
709 l_seeknum offset = (l_seeknum)p3;
710 luaL_argcheck(L, (lua_Integer)offset == p3, 3,
711 "not an integer in proper range");
712 errno = 0;
713 op = l_fseek(f, offset, mode[op]);
714 if (l_unlikely(op))
715 return luaL_fileresult(L, 0, NULL); /* error */
716 else {
717 lua_pushinteger(L, (lua_Integer)l_ftell(f));
718 return 1;
719 }
720 }
721
722
f_setvbuf(lua_State * L)723 static int f_setvbuf (lua_State *L) {
724 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
725 static const char *const modenames[] = {"no", "full", "line", NULL};
726 FILE *f = tofile(L);
727 int op = luaL_checkoption(L, 2, NULL, modenames);
728 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
729 int res;
730 errno = 0;
731 res = setvbuf(f, NULL, mode[op], (size_t)sz);
732 return luaL_fileresult(L, res == 0, NULL);
733 }
734
735
736
io_flush(lua_State * L)737 static int io_flush (lua_State *L) {
738 FILE *f = getiofile(L, IO_OUTPUT);
739 errno = 0;
740 return luaL_fileresult(L, fflush(f) == 0, NULL);
741 }
742
743
f_flush(lua_State * L)744 static int f_flush (lua_State *L) {
745 FILE *f = tofile(L);
746 errno = 0;
747 return luaL_fileresult(L, fflush(f) == 0, NULL);
748 }
749
750
751 /*
752 ** functions for 'io' library
753 */
754 static const luaL_Reg iolib[] = {
755 {"close", io_close},
756 {"flush", io_flush},
757 {"input", io_input},
758 {"lines", io_lines},
759 {"open", io_open},
760 {"output", io_output},
761 {"popen", io_popen},
762 {"read", io_read},
763 {"tmpfile", io_tmpfile},
764 {"type", io_type},
765 {"write", io_write},
766 {NULL, NULL}
767 };
768
769
770 /*
771 ** methods for file handles
772 */
773 static const luaL_Reg meth[] = {
774 {"read", f_read},
775 {"write", f_write},
776 {"lines", f_lines},
777 {"flush", f_flush},
778 {"seek", f_seek},
779 {"close", f_close},
780 {"setvbuf", f_setvbuf},
781 {NULL, NULL}
782 };
783
784
785 /*
786 ** metamethods for file handles
787 */
788 static const luaL_Reg metameth[] = {
789 {"__index", NULL}, /* placeholder */
790 {"__gc", f_gc},
791 {"__close", f_gc},
792 {"__tostring", f_tostring},
793 {NULL, NULL}
794 };
795
796
createmeta(lua_State * L)797 static void createmeta (lua_State *L) {
798 luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */
799 luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */
800 luaL_newlibtable(L, meth); /* create method table */
801 luaL_setfuncs(L, meth, 0); /* add file methods to method table */
802 lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
803 lua_pop(L, 1); /* pop metatable */
804 }
805
806
807 /*
808 ** function to (not) close the standard files stdin, stdout, and stderr
809 */
io_noclose(lua_State * L)810 static int io_noclose (lua_State *L) {
811 LStream *p = tolstream(L);
812 p->closef = &io_noclose; /* keep file opened */
813 luaL_pushfail(L);
814 lua_pushliteral(L, "cannot close standard file");
815 return 2;
816 }
817
818
createstdfile(lua_State * L,FILE * f,const char * k,const char * fname)819 static void createstdfile (lua_State *L, FILE *f, const char *k,
820 const char *fname) {
821 LStream *p = newprefile(L);
822 p->f = f;
823 p->closef = &io_noclose;
824 if (k != NULL) {
825 lua_pushvalue(L, -1);
826 lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
827 }
828 lua_setfield(L, -2, fname); /* add file to module */
829 }
830
831
luaopen_io(lua_State * L)832 LUAMOD_API int luaopen_io (lua_State *L) {
833 luaL_newlib(L, iolib); /* new module */
834 createmeta(L);
835 /* create (and set) default files */
836 createstdfile(L, stdin, IO_INPUT, "stdin");
837 createstdfile(L, stdout, IO_OUTPUT, "stdout");
838 createstdfile(L, stderr, NULL, "stderr");
839 return 1;
840 }
841
842