Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Glob in C++

Tags:

c++

file

glob

perl

What's the C++ way of Perl's idiom:

my @files = glob("file*.txt");
foreach my $file (@files) {

   # process $file
}
like image 739
neversaint Avatar asked May 07 '10 00:05

neversaint


2 Answers

The POSIX API specifies the glob() and globfree() functions for this. See the man page. wordexp() and wordfree(), also specified by POSIX, support other kinds of expansions as well.

like image 153
Ken Bloom Avatar answered Oct 12 '22 06:10

Ken Bloom


There's no standard C++ way to emulate this because there is no standard C++ functionality of reading the contents of a directory. What you can do is use Boost.Filesystem:

#include <boost/filesystem.hpp> // plus iostream,algorithm,string,iterator
using namespace boost::filesystem; // and std

struct pathname_of {
    string operator()(const directory_entry& p) const {
        return p.path().filename(); // or your creativity here
    }
};

int main(int argc, char* argv[])
{
    transform(directory_iterator("."), directory_iterator(),
              ostream_iterator<string>(cout, "\n"),
              pathname_of());
    return 0;
}
like image 35
wilhelmtell Avatar answered Oct 12 '22 08:10

wilhelmtell