sco*_*ttm 58 c++ filesystems boost
我想迭代匹配类似的目录中的所有文件somefiles*.txt
.
有boost::filesystem
没有内置的东西,或者我需要一个正则表达式或每个东西leaf()
?
Jul*_*n-L 74
编辑:如评论中所述,以下代码适用于boost::filesystem
v3之前的版本.对于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
.)
有一种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)