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
std::filesystem::directory_iterator
pointing to the target directory.is_regular_file()
to check if the current entry is a file.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.
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