add file.read() api, read(n) will read n byte.

This commit is contained in:
funshine 2014-12-31 13:53:26 +08:00
parent eb27c4fb27
commit 2553795b1e
1 changed files with 44 additions and 3 deletions

View File

@ -152,9 +152,15 @@ static int ICACHE_FLASH_ATTR file_check( lua_State* L )
#endif
// Lua: readline()
static int ICACHE_FLASH_ATTR file_readline( lua_State* L )
// g_read()
static int ICACHE_FLASH_ATTR file_g_read( lua_State* L, int n, int16_t end_char )
{
if(n< 0 || n>LUAL_BUFFERSIZE)
n = LUAL_BUFFERSIZE;
if(end_char < 0 || end_char >255)
end_char = EOF;
signed char ec = (signed char)end_char;
luaL_Buffer b;
if((FS_OPEN_OK - 1)==file_fd)
return luaL_error(L, "open a file first");
@ -170,7 +176,7 @@ static int ICACHE_FLASH_ATTR file_readline( lua_State* L )
break;
}
p[i++] = c;
}while((c!=EOF) && (c!='\n') && (i<LUAL_BUFFERSIZE) );
}while((c!=EOF) && (c!=ec) && (i<n) );
#if 0
if(i>0 && p[i-1] == '\n')
@ -187,6 +193,40 @@ static int ICACHE_FLASH_ATTR file_readline( lua_State* L )
return 1; /* read at least an `eol' */
}
// Lua: read()
// file.read() will read all byte in file
// file.read(10) will read 10 byte from file, or EOF is reached.
// file.read('q') will read until 'q' or EOF is reached.
static int ICACHE_FLASH_ATTR file_read( lua_State* L )
{
unsigned need_len = LUAL_BUFFERSIZE;
int16_t end_char = EOF;
size_t el;
if( lua_type( L, 1 ) == LUA_TNUMBER )
{
need_len = ( unsigned )luaL_checkinteger( L, 1 );
if( need_len > LUAL_BUFFERSIZE ){
need_len = LUAL_BUFFERSIZE;
}
}
else if(lua_isstring(L, 1))
{
const char *end = luaL_checklstring( L, 1, &el );
if(el!=1){
return luaL_error( L, "wrong arg range" );
}
end_char = (int16_t)end[0];
}
return file_g_read(L, need_len, end_char);
}
// Lua: readline()
static int ICACHE_FLASH_ATTR file_readline( lua_State* L )
{
return file_g_read(L, LUAL_BUFFERSIZE, '\n');
}
// Lua: write("string")
static int ICACHE_FLASH_ATTR file_write( lua_State* L )
{
@ -233,6 +273,7 @@ const LUA_REG_TYPE file_map[] =
{ LSTRKEY( "close" ), LFUNCVAL( file_close ) },
{ LSTRKEY( "write" ), LFUNCVAL( file_write ) },
{ LSTRKEY( "writeline" ), LFUNCVAL( file_writeline ) },
{ LSTRKEY( "read" ), LFUNCVAL( file_read ) },
{ LSTRKEY( "readline" ), LFUNCVAL( file_readline ) },
#if defined(BUILD_WOFS)
{ LSTRKEY( "format" ), LFUNCVAL( file_format ) },