Browse Source

增加ls

paint_robot_new-v1.5
Lizongdi 2 weeks ago
parent
commit
093dd7dc2c
  1. 10
      library/common/include/rd_stdio.h
  2. 32
      library/common/rd_stdio.c
  3. 23
      lua/lua.c

10
library/common/include/rd_stdio.h

@ -92,6 +92,16 @@ int Rd_fflush(void *file);
int Rd_remove(const char *filename);
int Rd_rename(const char *oldpath, const char *newpath);
/**
* @brief 遍历目录, 对每个条目调用回调
* @param path 目录路径
* @param callback 回调函数(name, is_dir, size, arg) 返回非0可提前终止
* @param arg 传给回调的用户数据
* @return 0 成功, -1 失败
*/
typedef int (*Rd_DirEntryCb)(const char *name, int is_dir, uint32_t size, void *arg);
int Rd_ListDir(const char *path, Rd_DirEntryCb callback, void *arg);
#ifdef __cplusplus
#if __cplusplus
}

32
library/common/rd_stdio.c

@ -347,4 +347,36 @@ WEAK void Rd_FatFSInit(void)
return;
}
WEAK int Rd_ListDir(const char *path, Rd_DirEntryCb callback, void *arg)
{
#ifdef USE_W25QXX
const char *p = path;
if (strlen(path) >= 2 && path[1] == ':') p = path + 2;
if (*p == '\0') p = "/";
lfs_dir_t dir;
int err = lfs_dir_open(&g_lfs, &dir, p);
if (err) return RD_FAILURE;
struct lfs_info info;
while (lfs_dir_read(&g_lfs, &dir, &info) > 0)
{
if (strcmp(info.name, ".") == 0 || strcmp(info.name, "..") == 0)
continue;
int is_dir = (info.type == LFS_TYPE_DIR) ? 1 : 0;
if (callback(info.name, is_dir, info.size, arg) != 0)
break;
}
lfs_dir_close(&g_lfs, &dir);
return RD_SUCCESS;
#else
(void)path;
(void)callback;
(void)arg;
return RD_FAILURE;
#endif
}
#endif

23
lua/lua.c

@ -502,6 +502,28 @@ static int l_rm(lua_State *L)
return 0;
}
static int ls_entry_cb(const char *name, int is_dir, uint32_t size, void *arg)
{
if (is_dir)
lua_print(" [DIR] %s\n", name);
else
lua_print(" %6u %s\n", size, name);
return 0;
}
static int l_ls(lua_State *L)
{
const char *path = "/";
if (lua_isstring(L, 1))
path = luaL_checkstring(L, 1);
if (Rd_ListDir(path, ls_entry_cb, NULL) != RD_SUCCESS)
{
lua_print("ls: cannot access '%s'\n", path);
}
return 0;
}
static int luaopen_default(lua_State *L)
{
lua_register_help(L, "help", l_help, "Show this help message");
@ -510,6 +532,7 @@ static int luaopen_default(lua_State *L)
lua_register_help(L, "cat", l_cat, "eg: cat(\"C:a.txt\")");
lua_register_help(L, "mv", l_mv, "eg: mv(\"C:a.txt\", \"C:b.txt\")");
lua_register_help(L, "rm", l_rm, "eg: rm(\"C:a.txt\")");
lua_register_help(L, "ls", l_ls, "eg: ls()");
return 0;
}

Loading…
Cancel
Save