Can I use a mask to iterate files in a directory with Boost?

后端 未结 7 1050
既然无缘
既然无缘 2020-11-27 03:51

I want to iterate over all files in a directory matching something like somefiles*.txt.

Does boost::filesystem have something built in to

相关标签:
7条回答
  • 2020-11-27 04:35

    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 does not have wildcard search, you have to filter files yourself.

    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() );
    }
    

    (If you are looking for a ready-to-use class with builtin directory filtering, have a look at Qt's QDir.)

    0 讨论(0)
提交回复
热议问题