How to count the number of files in a directory using standard?

半腔热情 提交于 2019-11-30 01:32:04

问题


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?

I know we can do:

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?


回答1:


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{});
}

You can get number of only actual files or apply any other filter by using count_if instead:

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);
}



回答2:


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

There is no function to find out how many files are in a directory, only functions to iterate over it. The OS only has functions like readdir(), ftw(), FindFirstFileW() so the standard cannot offer a better way.

(On the plus side that allows you to decide whether to, or how deep into, recurse into subdirectories)




回答3:


If you are using Visual Studio 17 you need to use the following namespace.

namespace fs = std::experimental::filesystem;

Then you could probably use a function like this one.

int Count() {
int count=0;
for (auto& p : fs::directory_iterator(beatmapDir)) {
    count++;

}
    return count;
}


来源:https://stackoverflow.com/questions/41304891/how-to-count-the-number-of-files-in-a-directory-using-standard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!