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?
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;
}
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.
directory_iterator begin(the_path), end;
int n = count_if(begin, end,
[](const directory_entry & d) {
return !is_directory(d.path());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With