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

前端 未结 3 1525
时光说笑
时光说笑 2021-01-01 21:30

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 kno

3条回答
  •  一整个雨季
    2021-01-01 22:02

    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)

提交回复
热议问题