c++ - 我可以使用掩码在 Boost 目录中迭代文件吗?

标签 c++ boost filesystems

我想遍历目录中与 somefiles*.txt 等匹配的所有文件。

boost::filesystem 是否有内置的东西来做到这一点,还是我需要一个正则表达式或针对每个 leaf() 的东西?

最佳答案

编辑:如评论中所述,以下代码适用于 v3 之前的 boost::filesystem 版本。对于 v3,请参阅评论中的建议。


boost::filesystem没有通配符搜索,需要自己过滤文件。

这是一个代码示例,使用 boost::filesystemdirectory_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/

相关文章:

C++未知调用约定

c++ - 精准的持续定时器回调

visual-studio-2010 - boost 库 1.47.1 构建 'lib' 前缀导致 LNK1104 错误

c# - 使用 C# 确定文件是否存在并解析 UNC 路径

linux - 在 Linux 上查找一个目录中的文件数的快速方法

c++ - 从 C++ priority_queue 释放

c++ - reheapify的STL实现

python - python目录校验和?

C++ Shader矩阵问题

c++ - 在没有所有格量词的情况下 boost 正则表达式