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

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

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)

Tags:

C++

C++17