Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

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?

like image 564
Boiethios Avatar asked Dec 23 '16 16:12

Boiethios


People also ask

How do we get the count of number of files in a directory?

Browse to the folder containing the files you want to count. Highlight one of the files in that folder and press the keyboard shortcut Ctrl + A to highlight all files and folders in that folder. In the Explorer status bar, you'll see how many files and folders are highlighted, as shown in the picture below.

How do I count the number of files in a directory in powershell?

To get count files in the folder using PowerShell, Use the Get-ChildItem command to get total files in directory and use measure-object to get count files in a folder.

How do I count the number of files in a UNIX zip file?

Hi, You need to use zcat command and then you can count the lines. >how to get line count on zipped file...


2 Answers

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);
}
like image 101
Revolver_Ocelot Avatar answered Oct 13 '22 09:10

Revolver_Ocelot


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)

like image 35
user45891 Avatar answered Oct 13 '22 07:10

user45891