としたにあんの左脳

備忘録です.

C++でglobっぽいの

参考:c++ - Can I use a mask to iterate files in a directory with Boost? - Stack Overflow

boost使う

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <boost/foreach.hpp>

void re_glob(boost::filesystem::path& target_path, std::string& re, std::vector< std::string >& results)
{
    const boost::regex my_filter(re);
    BOOST_FOREACH(
        const boost::filesystem::path &path,
        std::make_pair(
            boost::filesystem::directory_iterator(target_path),
            boost::filesystem::directory_iterator()))
    {
        if( !boost::filesystem::is_regular_file( path ) ) continue;
        boost::smatch what;
        // Skip if no match
        if( !boost::regex_match( path.string(), what, my_filter ) ) continue;

        results.push_back(path.string());
    }
}

int main(){
    std::vector< std::string > results;
    boost::filesystem::path path("/home/ubuntu/someproject");
    std::string re(".*py");
    re_glob(path, re, results);
    for(auto e: results){
        std::cout << e << std::endl;
    }
}