我想遍历目录中与 somefiles*.txt
等匹配的所有文件。
boost::filesystem
是否有内置的东西来做到这一点,还是我需要一个正则表达式或针对每个 leaf()
的东西?
最佳答案
编辑:如评论中所述,以下代码适用于 v3 之前的 boost::filesystem
版本。对于 v3,请参阅评论中的建议。
boost::filesystem
没有通配符搜索,需要自己过滤文件。
这是一个代码示例,使用 boost::filesystem
的 directory_iterator
提取目录内容并使用 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
。)
关于c++ - 我可以使用掩码在 Boost 目录中迭代文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1257721/