如何使用 boost::文件系统计算目录中的文件数

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

本文关键字:文件 计算 何使用 boost 文件系统      更新时间:2023-10-16

我得到了一个提升::文件系统::p ath。有没有一种快速的方法可以获取路径指向的目录中的文件数?

这是标准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;
}

您可以使用以下命令循环访问目录中的文件:

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

或递归:

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

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

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