c++ - 使用通配符的跨平台文件列表
问题描述
我正在寻找一个跨平台函数,它支持目录内容的通配符列表,类似于 Windows 上的 FindFirstFile。
windows 中接受的通配符模式是否非常特定于 windows?我想要一些支持 FindFirstFile 通配符模式的东西,但他也在 Linux 中工作。
解决方案
如果 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();
应该修改为捕获您感兴趣的文件名部分(或文件的整个路径)的内容
然后可以在一个函数中使用它,该函数按目录执行通配符列表。
推荐阅读
- mod-security - mod_security(2.x):如何匹配未定义的 mod-sec 变量?
- linux-mint - 在 Linux Mint 20.2 Xfce 上将 alacritty 设置为默认终端仿真器
- prometheus - 普罗米修斯规则变量?
- python - 如何计算给定颜色图像中的角点
- r - 如何在 R 中使用函数获得的多个图创建演示文稿?
- polymer - Vaadin 14 聚合物元素 this.dispatchEvent 不是函数
- python-3.x - 如何使用 python 提取给定 url 的身份验证承载令牌?
- c++ - 使用 std::accumulate(v.begin(), v.end(), 0) 发出警告;
- python - 在 Pandas 上将 DataFrame 拆分为多个 .txt
- assembly - 如何使用 nasm 编写的引导扇区制作可引导的 USB 驱动器?