diff --git a/app/modules/file.c b/app/modules/file.c index 26f6224a..d9f77062 100644 --- a/app/modules/file.c +++ b/app/modules/file.c @@ -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 } }; diff --git a/docs/en/modules/file.md b/docs/en/modules/file.md index a6160b28..9c1ed9eb 100644 --- a/docs/en/modules/file.md +++ b/docs/en/modules/file.md @@ -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.