Can I use a mask to iterate files in a directory with Boost?(我可以使用掩码在带有 Boost 的目录中迭代文件吗?)
问题描述
我想遍历一个目录中匹配somefiles*.txt 之类的所有文件.
I want to iterate over all files in a directory matching something like somefiles*.txt.
boost::filesystem 是否有内置的东西来做到这一点,或者我是否需要一个正则表达式或针对每个 leaf() 的东西?
Does boost::filesystem have something built in to do that, or do I need a regex or something against each leaf()?
推荐答案
EDIT:如评论中所述,以下代码适用于 boost::filesystem 在 v3 之前.对于 v3,请参考评论中的建议.
EDIT: As noted in the comments, the code below is valid for versions of boost::filesystem prior to v3. For v3, refer to the suggestions in the comments.
boost::filesystem 没有通配符搜索,你必须自己过滤文件.
boost::filesystem does not have wildcard search, you have to filter files yourself.
这是一个使用boost::filesystem的directory_iterator提取目录内容并使用boost::regex过滤的代码示例代码>:
This is a code sample extracting the content of a directory with a boost::filesystem's directory_iterator and filtering it with boost::regex:
const std::string target_path( "/my/directory/" );
const boost::regex my_filter( "somefiles.*.txt" );
std::vector< std::string > all_matching_files;
boost::filesystem::directory_iterator end_itr; // Default ctor yields past-the-end
for( boost::filesystem::directory_iterator i( target_path ); i != end_itr; ++i )
{
// Skip if not a file
if( !boost::filesystem::is_regular_file( i->status() ) ) continue;
boost::smatch what;
// Skip if no match for V2:
if( !boost::regex_match( i->leaf(), what, my_filter ) ) continue;
// For V3:
//if( !boost::regex_match( i->path().filename().string(), what, my_filter ) ) continue;
// File matches, store it
all_matching_files.push_back( i->leaf() );
}
(如果您正在寻找具有内置目录过滤功能的即用型类,请查看 Qt 的 QDir.)
(If you are looking for a ready-to-use class with builtin directory filtering, have a look at Qt's QDir.)
这篇关于我可以使用掩码在带有 Boost 的目录中迭代文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以使用掩码在带有 Boost 的目录中迭代文件吗?
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
