add fs_foreach_file

This commit is contained in:
lixianjing 2021-11-03 09:12:10 +08:00
parent 3059b5d99f
commit 472a5bd6ea
4 changed files with 74 additions and 0 deletions

View File

@ -1,5 +1,8 @@
# 最新动态
2021/11/03
* 增加fs\_foreach\_file
2021/11/02
* 增加tk\_str\_end\_with
* 修复json解析对null的处理。

View File

@ -642,3 +642,31 @@ ret_t fs_copy_dir(fs_t* fs, const char* src, const char* dst) {
return ret;
}
ret_t fs_foreach_file(const char* path, tk_visit_t on_file, void* ctx) {
fs_item_t item;
fs_t* fs = os_fs();
fs_dir_t* dir = NULL;
char filename[MAX_PATH + 1];
return_value_if_fail(fs != NULL && path != NULL && on_file != NULL, RET_BAD_PARAMS);
dir = fs_open_dir(fs, path);
return_value_if_fail(dir != NULL, RET_BAD_PARAMS);
while (fs_dir_read(dir, &item) == RET_OK) {
if (tk_str_eq(item.name, ".") || tk_str_eq(item.name, "..")) {
continue;
}
path_build(filename, MAX_PATH, path, item.name, NULL);
if (item.is_reg_file) {
if (on_file(ctx, filename) != RET_OK) {
break;
}
} else if (item.is_dir) {
fs_foreach_file(filename, on_file, ctx);
}
}
fs_dir_close(dir);
return RET_OK;
}

View File

@ -701,6 +701,34 @@ fs_t* os_fs(void);
/*wrapper*/
/**
* @method fs_foreach_file
*
*
* :
* ```c
* static ret_t on_file(void* ctx, const void* data) {
* const char* filename = (const char*)data;
* const char* extname = (const char*)ctx;
*
* if (tk_str_end_with(filename, extname)) {
* log_debug("%s\n", filename);
* }
* return RET_OK;
* }
* ...
* fs_foreach_file("tests/testdata", on_file, (void*)".json");
*```
*
* @param {const char*} path
* @param {tk_visit_t} on_file (data参数传入)
* @param {void*} ctx
*
* @return {bool_t} TRUE表示成功
*/
ret_t fs_foreach_file(const char* path, tk_visit_t on_file, void* ctx);
/**
* @method file_exist
*

View File

@ -1,5 +1,6 @@
#include "tkc/fs.h"
#include "tkc/mem.h"
#include "tkc/utils.h"
#include "gtest/gtest.h"
TEST(Fs, basic) {
@ -196,6 +197,20 @@ TEST(Fs, copy_dir) {
ASSERT_EQ(fs_remove_dir_r(os_fs(), "b"), RET_OK);
}
static ret_t on_file(void* ctx, const void* data) {
const char* filename = (const char*)data;
const char* extname = (const char*)ctx;
if (tk_str_end_with(filename, extname)) {
log_debug("%s\n", filename);
}
return RET_OK;
}
TEST(Fs, foreach_file) {
fs_foreach_file("tests/testdata", on_file, (void*)".json");
}
#ifdef WIN32
TEST(Fs, stat) {
fs_stat_info_t st;