|
| 1 | +--- |
| 2 | +Title: Find files recursively |
| 3 | +Description: Find all the files in a directory and subdirectories using a predicate function. |
| 4 | +Author: majvax |
| 5 | +Tags: filesystem,file_search,c++17 |
| 6 | +--- |
| 7 | + |
| 8 | +```cpp |
| 9 | +#include <filesystem> |
| 10 | +#include <vector> |
| 11 | +#include <string> |
| 12 | + |
| 13 | +template <typename P> |
| 14 | +std::vector<std::filesystem::path> find_files_recursive(const std::string& path, P&& predicate) { |
| 15 | + std::vector<std::filesystem::path> files; |
| 16 | + std::error_code ec; |
| 17 | + |
| 18 | + if (!std::filesystem::exists(path, ec) || ec) |
| 19 | + return files; |
| 20 | + if (!std::filesystem::is_directory(path, ec) || ec) |
| 21 | + return files; |
| 22 | + |
| 23 | + auto it = std::filesystem::recursive_directory_iterator(path, ec); |
| 24 | + if (ec) |
| 25 | + return files; |
| 26 | + |
| 27 | + for (const auto& entry : it) |
| 28 | + if (!std::filesystem::is_directory(entry) && predicate(entry.path())) |
| 29 | + files.push_back(entry.path()); |
| 30 | + |
| 31 | + return files; |
| 32 | +} |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | +// Usage: |
| 37 | + |
| 38 | +// Find all files with size greater than 10MB |
| 39 | +auto files = find_files_recursive("Path", [](const auto& p) { |
| 40 | + return std::filesystem::file_size(p) > 10 * 1024 * 1024; |
| 41 | +}); |
| 42 | + |
| 43 | +// Find all files with ".pdf" as extension |
| 44 | +auto files = find_files_recursive("Path", [](const auto& p) { |
| 45 | + return p.extension() == ".pdf"; |
| 46 | +}); |
| 47 | + |
| 48 | +// Find all files writed after The New Year |
| 49 | +#include <chrono> |
| 50 | +// need std=c++20 |
| 51 | +auto jan_1_2025 = std::filesystem::file_time_type::clock::from_sys( |
| 52 | + std::chrono::sys_days{std::chrono::year{2025}/std::chrono::month{1}/std::chrono::day{1}} |
| 53 | +); |
| 54 | +auto files = find_files_recursive("Path", [jan_1_2025](const auto& p) { |
| 55 | + return std::filesystem::last_write_time(p) > jan_1_2025; |
| 56 | +}), |
| 57 | +``` |
0 commit comments