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 的目录中迭代文件吗?
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
