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