Added file.exists() method to save the need to use file.list() for checking file existence

This commit is contained in:
jfollas 2016-02-13 17:37:04 -05:00
parent 2c687313de
commit 44786a22ff
2 changed files with 45 additions and 0 deletions

View File

@ -114,6 +114,22 @@ static int file_seek (lua_State *L)
return 1;
}
// Lua: exists(filename)
static int file_exists( lua_State* L )
{
size_t len;
const char *fname = luaL_checklstring( L, 1, &len );
if( len > FS_NAME_MAX_LENGTH )
return luaL_error(L, "filename too long");
spiffs_stat stat;
int rc = SPIFFS_stat(&fs, (char *)fname, &stat);
lua_pushboolean(L, (rc == SPIFFS_OK ? 1 : 0));
return 1;
}
// Lua: remove(filename)
static int file_remove( lua_State* L )
{
@ -312,6 +328,7 @@ static const LUA_REG_TYPE file_map[] = {
//{ LSTRKEY( "check" ), LFUNCVAL( file_check ) },
{ LSTRKEY( "rename" ), LFUNCVAL( file_rename ) },
{ LSTRKEY( "fsinfo" ), LFUNCVAL( file_fsinfo ) },
{ LSTRKEY( "exists" ), LFUNCVAL( file_exists ) },
#endif
{ LNILKEY, LNILVAL }
};

View File

@ -28,6 +28,34 @@ file.close()
#### See also
[`file.open()`](#fileopen)
## file.exists()
Determines whether the specified file exists.
#### Syntax
`file.exists(filename)`
#### Parameters
- `filename` file to check
#### Returns
true of the file exists (even if 0 bytes in size), and false if it does not exist
#### Example
```lua
files = file.list()
if files["device.config"] then
print("Config file exists")
end
if file.exists("device.config") then
print("Config file exists")
end
```
#### See also
[`file.list()`](#filelist)
## file.flush()
Flushes any pending writes to the file system, ensuring no data is lost on a restart. Closing the open file using [`file.close()`](#fileclose) performs an implicit flush as well.