How do I count the number of files in a directory

2019-02-13 15:46发布

问题:

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?

回答1:

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


回答2:

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.



回答3:

directory_iterator begin(the_path), end;
int n = count_if(begin, end,
    [](const directory_entry & d) {
        return !is_directory(d.path());
});


标签: c++ boost