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

sco*_*ttm 58 c++ filesystems boost

我想迭代匹配类似的目录中的所有文件somefiles*.txt.

boost::filesystem没有内置的东西,或者我需要一个正则表达式或每个东西leaf()

Jul*_*n-L 74

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


boost::filesystem 没有通配符搜索,您必须自己过滤文件.

这是一个代码示例,使用boost::filesystem's' 提取目录的内容并使用以下内容对其进行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() );
}
Run Code Online (Sandbox Code Playgroud)

(如果您正在寻找具有内置目录过滤功能的即用型课程,请查看Qt QDir.)

  • 感谢非常完整的答案.其他人的两个注意事项:1)leaf在文件系统v3中被弃用(当前默认值),使用path().filename()而不是2)如果过滤条件是扩展名(非常常见),则更容易使用i-> path( ).extension()==".txt"[例如]比正则表达式 (21认同)
  • leaf()现已弃用.i-> leaf()可以替换为i-> path().string()或i-> path().filename().string()如果你只是想要文件名 (18认同)
  • 正则表达式中的反斜杠必须被转义为"somefiles.*\\ .txt"` (5认同)

Ole*_*nko 8

有一种Boost Range Adaptors方法:

#define BOOST_RANGE_ENABLE_CONCEPT_ASSERT 0
#include <boost/filesystem.hpp>
#include <boost/range/adaptors.hpp>

namespace bfs = boost::filesystem;
namespace ba = boost::adaptors;

const std::string target_path( "/my/directory/" );
const boost::regex my_filter( "somefiles.*\.txt" );
boost::smatch what;

for (auto &entry: boost::make_iterator_range(bfs::directory_iterator(target_path), {})
| ba::filtered(static_cast<bool (*)(const bfs::path &)>(&bfs::is_regular_file))
| ba::filtered([&](const bfs::path &path){ return boost::regex_match(path.filename().string(), what, my_filter); })
)
{
  // There are only files matching defined pattern "somefiles*.txt".
  std::cout << entry.path().filename() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)