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?
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.
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.
Hi, You need to use zcat command and then you can count the lines. >how to get line count on zipped file...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With