如何使用boost :: filesystem计算目录中的文件数?

Bry*_*man 9 c++ boost

我得到了一个boost :: filesystem :: path.有没有一种快速的方法来获取路径指向的目录中的文件数?

Adr*_*ian 9

您可以使用以下命令迭代目录中的文件:

for(directory_iterator it(YourPath); it != directory_iterator(); ++it)
{
   // increment variable here
}
Run Code Online (Sandbox Code Playgroud)

或递归:

for(recursive_directory_iterator it(YourPath); it != recursive_directory_iterator(); ++it)
{
   // increment variable here
} 
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到一些简单的例子.


Kir*_*sky 9

这是标准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;
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*ley 5

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