aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2014-03-06 14:12:02 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2014-03-06 14:12:02 -0300
commitc5bb3643ab28d5309971f1960dd5222b9c81fd3a (patch)
tree9ccf14e3a72d63fda13b49b89994e439bab5dfd5
parent5ff1c18a715b842a6146a6a07d99c84f48cac999 (diff)
downloadlua-c5bb3643ab28d5309971f1960dd5222b9c81fd3a.tar.gz
lua-c5bb3643ab28d5309971f1960dd5222b9c81fd3a.tar.bz2
lua-c5bb3643ab28d5309971f1960dd5222b9c81fd3a.zip
simpler code to read a line from a file (using 'getc' or, if present,
'getc_unlocked')
-rw-r--r--liolib.c41
1 files changed, 24 insertions, 17 deletions
diff --git a/liolib.c b/liolib.c
index 88be99ec..adb72ef3 100644
--- a/liolib.c
+++ b/liolib.c
@@ -1,5 +1,5 @@
1/* 1/*
2** $Id: liolib.c,v 2.116 2014/02/21 14:39:50 roberto Exp roberto $ 2** $Id: liolib.c,v 2.117 2014/02/26 15:27:56 roberto Exp roberto $
3** Standard I/O (and system) library 3** Standard I/O (and system) library
4** See Copyright Notice in lua.h 4** See Copyright Notice in lua.h
5*/ 5*/
@@ -79,6 +79,21 @@
79/* }====================================================== */ 79/* }====================================================== */
80 80
81 81
82#if !defined(lua_getc) /* { */
83
84#if defined(LUA_USE_POSIX)
85#define lua_getc(f) getc_unlocked(f)
86#define lua_lockfile(f) flockfile(f)
87#define lua_unlockfile(f) funlockfile(f)
88#else
89#define lua_getc(f) getc(f)
90#define lua_lockfile(f) ((void)0)
91#define lua_unlockfile(f) ((void)0)
92#endif
93
94#endif /* } */
95
96
82/* 97/*
83** {====================================================== 98** {======================================================
84** lua_fseek: configuration for longer offsets 99** lua_fseek: configuration for longer offsets
@@ -384,23 +399,15 @@ static int test_eof (lua_State *L, FILE *f) {
384 399
385static int read_line (lua_State *L, FILE *f, int chop) { 400static int read_line (lua_State *L, FILE *f, int chop) {
386 luaL_Buffer b; 401 luaL_Buffer b;
402 int c;
387 luaL_buffinit(L, &b); 403 luaL_buffinit(L, &b);
388 for (;;) { 404 lua_lockfile(f);
389 size_t l; 405 while ((c = lua_getc(f)) != EOF && c != '\n')
390 char *p = luaL_prepbuffer(&b); 406 luaL_addchar(&b, c);
391 if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ 407 lua_unlockfile(f);
392 luaL_pushresult(&b); /* close buffer */ 408 if (!chop && c == '\n') luaL_addchar(&b, c);
393 return (lua_rawlen(L, -1) > 0); /* check whether read something */ 409 luaL_pushresult(&b); /* close buffer */
394 } 410 return (c == '\n' || lua_rawlen(L, -1) > 0);
395 l = strlen(p);
396 if (l == 0 || p[l-1] != '\n')
397 luaL_addsize(&b, l);
398 else {
399 luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
400 luaL_pushresult(&b); /* close buffer */
401 return 1; /* read at least an `eol' */
402 }
403 }
404} 411}
405 412
406 413