如何使用标准计数目录中的文件数? [英] How to count the number of files in a directory using standard?

查看:83
本文介绍了如何使用标准计数目录中的文件数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

预计在2017年推出的新标准将添加 std :: filesystem 。使用它,如何计算目录中文件(包括子目录)的数量?

The new standard expected for 2017 adds std::filesystem. Using it, how can I count the number of files (including sub-directories) in a directory?

我知道我们可以做到:

std::size_t number_of_files_in_directory(std::filesystem::path path)
{
    std::size_t number_of_files = 0u;
    for (auto const & file : std::filesystem::directory_iterator(path))
    {
        ++number_of_files;
    }
    return number_of_files;
}

但这似乎有些过分。是否存在更简单,更快速的方法?

But that seems overkill. Does a simpler and faster way exist?

推荐答案

我认为不存在一种轻松获取目录中文件数量的方法,但是您可以使用 std :: distance 而不是手写循环来简化代码:

I do not think that a way to easily get amount of files in directory exist, but you can simplify your code by using std::distance instead of handwritten loop:

std::size_t number_of_files_in_directory(std::filesystem::path path)
{
    using std::filesystem::directory_iterator;
    return std::distance(directory_iterator(path), directory_iterator{});
}

您可以通过使用<获得仅实际文件数或应用任何其他过滤器code> count_if 代替:

std::size_t number_of_files_in_directory(std::filesystem::path path)
{
    using std::filesystem::directory_iterator;
    using fp = bool (*)( const std::filesystem::path&);
    return std::count_if(directory_iterator(path), directory_iterator{}, (fp)std::filesystem::is_regular_file);
}

这篇关于如何使用标准计数目录中的文件数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆