simpler code to read a line from a file (using 'getc' or, if present,
'getc_unlocked')
This commit is contained in:
39
liolib.c
39
liolib.c
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
** $Id: liolib.c,v 2.116 2014/02/21 14:39:50 roberto Exp roberto $
|
** $Id: liolib.c,v 2.117 2014/02/26 15:27:56 roberto Exp roberto $
|
||||||
** Standard I/O (and system) library
|
** Standard I/O (and system) library
|
||||||
** See Copyright Notice in lua.h
|
** See Copyright Notice in lua.h
|
||||||
*/
|
*/
|
||||||
@@ -79,6 +79,21 @@
|
|||||||
/* }====================================================== */
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(lua_getc) /* { */
|
||||||
|
|
||||||
|
#if defined(LUA_USE_POSIX)
|
||||||
|
#define lua_getc(f) getc_unlocked(f)
|
||||||
|
#define lua_lockfile(f) flockfile(f)
|
||||||
|
#define lua_unlockfile(f) funlockfile(f)
|
||||||
|
#else
|
||||||
|
#define lua_getc(f) getc(f)
|
||||||
|
#define lua_lockfile(f) ((void)0)
|
||||||
|
#define lua_unlockfile(f) ((void)0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
** {======================================================
|
** {======================================================
|
||||||
** lua_fseek: configuration for longer offsets
|
** lua_fseek: configuration for longer offsets
|
||||||
@@ -384,23 +399,15 @@ static int test_eof (lua_State *L, FILE *f) {
|
|||||||
|
|
||||||
static int read_line (lua_State *L, FILE *f, int chop) {
|
static int read_line (lua_State *L, FILE *f, int chop) {
|
||||||
luaL_Buffer b;
|
luaL_Buffer b;
|
||||||
|
int c;
|
||||||
luaL_buffinit(L, &b);
|
luaL_buffinit(L, &b);
|
||||||
for (;;) {
|
lua_lockfile(f);
|
||||||
size_t l;
|
while ((c = lua_getc(f)) != EOF && c != '\n')
|
||||||
char *p = luaL_prepbuffer(&b);
|
luaL_addchar(&b, c);
|
||||||
if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
|
lua_unlockfile(f);
|
||||||
|
if (!chop && c == '\n') luaL_addchar(&b, c);
|
||||||
luaL_pushresult(&b); /* close buffer */
|
luaL_pushresult(&b); /* close buffer */
|
||||||
return (lua_rawlen(L, -1) > 0); /* check whether read something */
|
return (c == '\n' || lua_rawlen(L, -1) > 0);
|
||||||
}
|
|
||||||
l = strlen(p);
|
|
||||||
if (l == 0 || p[l-1] != '\n')
|
|
||||||
luaL_addsize(&b, l);
|
|
||||||
else {
|
|
||||||
luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
|
|
||||||
luaL_pushresult(&b); /* close buffer */
|
|
||||||
return 1; /* read at least an `eol' */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user