From a81c908cc35167ceb4f563d48a6bc355a1b6f488 Mon Sep 17 00:00:00 2001 From: Johny Mattsson Date: Sat, 1 Jan 2022 17:36:48 +1100 Subject: [PATCH] Added mkdir/rmdir support to file module. --- components/modules/file.c | 27 +++++++++++++++++++++++++++ docs/modules/file.md | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/components/modules/file.c b/components/modules/file.c index e77ab54a2..b4aeee1e3 100644 --- a/components/modules/file.c +++ b/components/modules/file.c @@ -11,6 +11,7 @@ #include #include #include +#include static const char *default_fs_label = ((CONFIG_NODEMCU_DEFAULT_SPIFFS_LABEL && @@ -116,6 +117,30 @@ static int file_fsinfo( lua_State* L ) } +static int file_mkdir( lua_State *L ) +{ + const char *name = luaL_checkstring(L, 1); + unsigned mode = luaL_optint(L, 2, 0777); + int ret = mkdir(name, mode); + if (ret != 0) + return + luaL_error(L, "failed to create directory '%s'; code %d", name, errno); + else + return 0; +} + + +static int file_rmdir( lua_State *L ) +{ + const char *name = luaL_checkstring(L, 1); + int ret = rmdir(name); + if (ret != 0) + return + luaL_error(L, "failed to remove directory '%s'; code %d", name, errno); + return 0; +} + + // Module function map LROT_BEGIN(file, NULL, 0) LROT_FUNCENTRY( list, file_list ) @@ -124,6 +149,8 @@ LROT_BEGIN(file, NULL, 0) LROT_FUNCENTRY( rename, file_rename ) LROT_FUNCENTRY( exists, file_exists ) LROT_FUNCENTRY( fsinfo, file_fsinfo ) + LROT_FUNCENTRY( mkdir, file_mkdir ) + LROT_FUNCENTRY( rmdir, file_rmdir ) LROT_END(file, NULL, 0) diff --git a/docs/modules/file.md b/docs/modules/file.md index 095ffc7fe..0dd347b1f 100644 --- a/docs/modules/file.md +++ b/docs/modules/file.md @@ -115,6 +115,39 @@ for k,v in pairs(l) do end ``` +## file.mkdir() + +Creates a directory, provided the underlying file system supports directories. SPIFFS does not, but FAT (which you may have on an attached SD card) does. + +#### Syntax +`file.mkdir(path [, mode]) +``` + +#### Parameters +- `path` the full path name of the directory to create. E.g. "/SD0/MYDIR". +- `mode` optional, only used for file systems which use mode permissions. Defaults to 0777 (octal). + +#### Returns +`nil` + +Throws an error if the directory could not be created. Error code 134 (at the +time of writing) indicates that the filesystem at the given path does not +support directories. + +## file.rmdir() + +Removes an empty directory, provided the underlying file system supports directories. SPIFFS does not, but FAT (which you may have on an attached SD card) does. + +#### Syntax +`file.rmdir(path)` + +#### Parameters +- `path` the path to the directory to remove. The directory must be empty. + +#### Returns +`nil` + +Throws an error if the directory could not be removed. ## file.remove()