Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the number of files in a directory using boost::filesystem?

Tags:

c++

boost

I am given a boost::filesystem::path. Is there a fast way to get the number of files in the directory pointed to by the path?

like image 390
May Oakes Avatar asked May 18 '11 19:05

May Oakes


3 Answers

Here's one-liner in Standard C++:

#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/lambda/bind.hpp>

int main()
{
    using namespace boost::filesystem;
    using namespace boost::lambda;

    path the_path( "/home/myhome" );

    int cnt = std::count_if(
        directory_iterator(the_path),
        directory_iterator(),
        static_cast<bool(*)(const path&)>(is_regular_file) );

    // a little explanation is required here,
    // we need to use static_cast to specify which version of
    // `is_regular_file` function we intend to use
    // and implicit conversion from `directory_entry` to the
    // `filesystem::path` will occur

    std::cout << cnt << std::endl;

    return 0;
}
like image 96
Kirill V. Lyadvinsky Avatar answered Nov 17 '22 16:11

Kirill V. Lyadvinsky


You can iterate over files in a directory with:

for(directory_iterator it(YourPath); it != directory_iterator(); ++it)
{
   // increment variable here
}

Or recursively:

for(recursive_directory_iterator it(YourPath); it != recursive_directory_iterator(); ++it)
{
   // increment variable here
} 

You can find some simple examples here.

like image 44
Adrian Avatar answered Nov 17 '22 17:11

Adrian


directory_iterator begin(the_path), end;
int n = count_if(begin, end,
    [](const directory_entry & d) {
        return !is_directory(d.path());
});
like image 7
Benjamin Lindley Avatar answered Nov 17 '22 17:11

Benjamin Lindley