Filter Directory Entries
How do I filter the directory entries to only show files?
Filtering directory entries to show only files can be achieved using a combination of std::filesystem::directory_iterator
and conditional checks within the iteration loop. Here's an example:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
if (iter->is_regular_file()) {
std::cout << iter->path().string() << '\n';
}
}
}
c:\test\file.txt
c:\test\hello.txt
c:\test\document.pdf
Steps to Filter Entries:
- Initialize the Iterator: Create a
std::filesystem::directory_iterator
pointing to the target directory. - Iterate with a Condition: Within the loop, use
is_regular_file()
to check if the current entry is a file. - Output or Process Files: If the condition is true, process the file (e.g., print its path).
Alternative Approach Using std::ranges
:
You can also use std::ranges::filter()
to streamline the process:
#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 files = entries | std::views::filter(
[](const fs::directory_entry& entry) {
return entry.is_regular_file();
}
);
for (const auto& file : files) {
std::cout << file.path().string() << '\n';
}
}
c:\test\file1.txt
c:\test\file2.txt
c:\test\file3.txt
This approach leverages the power of ranges to filter the entries in a more declarative manner. Both methods are effective for filtering directory entries to show only files.
Directory Iterators
An introduction to iterating through the file system, using directory_iterator
and recursive_directory_iterator
.