diff --git a/docs/changes.md b/docs/changes.md index b9b71fb80..d258b3ebb 100644 --- a/docs/changes.md +++ b/docs/changes.md @@ -1,5 +1,8 @@ # 最新动态 +2021/11/03 + * 增加fs\_foreach\_file + 2021/11/02 * 增加tk\_str\_end\_with * 修复json解析对null的处理。 diff --git a/src/tkc/fs.c b/src/tkc/fs.c index f808d73cc..d4a95a93c 100644 --- a/src/tkc/fs.c +++ b/src/tkc/fs.c @@ -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; +} diff --git a/src/tkc/fs.h b/src/tkc/fs.h index 118ab6977..0dfc5786f 100644 --- a/src/tkc/fs.h +++ b/src/tkc/fs.h @@ -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 * diff --git a/tests/fs_test.cc b/tests/fs_test.cc index c16474011..88424549b 100644 --- a/tests/fs_test.cc +++ b/tests/fs_test.cc @@ -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;