首页 > 解决方案 > 使用通配符的跨平台文件列表

问题描述

我正在寻找一个跨平台函数,它支持目录内容的通配符列表,类似于 Windows 上的 FindFirstFile。

windows 中接受的通配符模式是否非常特定于 windows?我想要一些支持 FindFirstFile 通配符模式的东西,但他也在 Linux 中工作。

标签: c++std-filesystem

解决方案


如果 C++17 及更高版本:您可以使用目录迭代器“遍历”目录,并将遍历的文件名与正则表达式匹配,如下所示:

static std::optional<std::string> find_file(const std::string& search_path, const std::regex& regex) {
    const std::filesystem::directory_iterator end;
    try {
        for (std::filesystem::directory_iterator iter{search_path}; iter != end; iter++) {
            const std::string file_ext = iter->path().extension().string();
            if (std::filesystem::is_regular_file(*iter)) {
                if (std::regex_match(file_ext, regex)) {
                    return (iter->path().string());
                }
            }
        }
    }
    catch (std::exception&) {}
    return std::nullopt;
}

例如,用于查找以 .txt 结尾的第一个文件:

auto first_file = find_file("DocumentsDirectory", std::regex("\\.(?:txt)"));

同样,如果您感兴趣的不仅仅是通过扩展匹配,功能行

const std::string file_ext = iter->path().extension().string();

应该修改为捕获您感兴趣的文件名部分(或文件的整个路径)的内容

然后可以在一个函数中使用它,该函数按目录执行通配符列表。


推荐阅读