Counting the number of files in a directory is a common task that can be accomplished by iterating through the directory entries and incrementing a counter for each file.
Here’s an example that counts regular files in a directory:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
int file_count = 0; // Initialize counter
for (auto iter{start}; iter != end; ++iter) {
if (iter->is_regular_file()) {
++file_count;
}
}
std::cout << "Number of files: " << file_count;
}
Number of files: 3
std::filesystem::directory_iterator
for the target directory.You can also count files and directories separately:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
int file_count = 0;
int dir_count = 0;
for (auto iter{start}; iter != end; ++iter) {
if (iter->is_regular_file()) {
++file_count;
} else if (iter->is_directory()) {
++dir_count;
}
}
std::cout << "Number of files: "
<< file_count << '\n';
std::cout << "Number of directories: "
<< dir_count << '\n';
}
Number of files: 3
Number of directories: 1
You can also use range-based algorithms to count files:
#include <filesystem>
#include <iostream>
#include <ranges>
namespace fs = std::filesystem;
int main() {
auto entries = std::ranges::subrange{
fs::directory_iterator{R"(c:\test)"},
fs::directory_iterator{}
};
auto file_count = std::ranges::count_if(
entries,
[](const fs::directory_entry& entry) {
return entry.is_regular_file();
}
);
std::cout << "Number of files: " << file_count;
}
Number of files: 3
If you want to count files in a directory and its subdirectories, use std::filesystem::recursive_directory_iterator
:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::recursive_directory_iterator start{
R"(c:\test)"};
fs::recursive_directory_iterator end{};
int file_count = 0;
for (auto iter{start}; iter != end; ++iter) {
if (iter->is_regular_file()) {
++file_count;
}
}
std::cout << "Number of files: " << file_count;
}
Number of files: 3
Counting files is a fundamental operation that can be easily implemented using the techniques shown above, whether for flat or recursive directory structures.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to iterating through the file system, using directory iterators and recursive directory iterators