While std::filesystem::directory_iterator
does not directly support sorting, you can collect the directory entries into a container (like std::vector
), sort the container, and then iterate over it.
Here’s an example of how to sort directory entries by their file names:
#include <filesystem>
#include <iostream>
#include <vector>
#include <algorithm>
namespace fs = std::filesystem;
int main() {
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
std::vector<fs::directory_entry> entries;
for (auto iter{start}; iter != end; ++iter) {
entries.push_back(*iter);
}
std::sort(entries.begin(), entries.end(),
[](const fs::directory_entry& a,
const fs::directory_entry& b) {
return a.path().filename()
< b.path().filename();
});
for (const auto& entry : entries) {
std::cout << entry.path().string() << '\n';
}
}
c:\test\another_directory
c:\test\file1.txt
c:\test\file2.txt
std::vector
.std::sort()
with a custom comparator to sort the entries based on desired criteria (e.g., filename).You can sort by other criteria, such as file size or modification time:
std::sort(entries.begin(), entries.end(),
[](const fs::directory_entry& a,
const fs::directory_entry& b) {
return fs::file_size(a) < fs::file_size(b);
});
You can also leverage std::ranges
for a more modern approach:
#include <filesystem>
#include <iostream>
#include <vector>
#include <ranges>
namespace fs = std::filesystem;
int main() {
auto entries = std::ranges::subrange{
fs::directory_iterator{R"(c:\test)"},
fs::directory_iterator{}
} | std::ranges::to<std::vector>();
std::ranges::sort(
entries, {}, &fs::directory_entry::path);
for (const auto& entry : entries) {
std::cout << entry.path().string() << '\n';
}
}
Sorting directory entries provides greater flexibility and control over how you process files and directories. By collecting entries into a container and sorting them, you can achieve any custom order needed for your application.
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