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

时间:2022-08-25 23:23:03

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?

我得到了一个boost::文件系统:::path。是否有一种快速的方法来获取路径指向的目录中的文件数量?

3 个解决方案

#1


9  

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

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


10  

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


5  

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

#1


9  

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

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


10  

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


5  

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