我可以使用掩码在带有 Boost 的目录中迭代文件吗?

Can I use a mask to iterate files in a directory with Boost?(我可以使用掩码在带有 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::filesystemdirectory_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 的目录中迭代文件吗?

基础教程推荐