Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Does boost::filesystem have something built in to do that, or do I need a regex or something against each leaf()?

like image 938
scottm Avatar asked Aug 10 '09 23:08

scottm


1 Answers

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.)

like image 107
Julien-L Avatar answered Oct 18 '22 00:10

Julien-L