如何在C++的recursive_directory_operator中停止递归?含文档检索代码
recursive_directory_iterator Hey there! Let's break down how to halt recursion when using std::experimental::filesystem::recursive_directory_iterator in your document-search code. There are a couple of straightforward ways to do this, depending on your specific needs.
1. Skip Specific Directories with skip()
If your goal is to avoid recursing into certain directories (like your ignoredirs list), the skip() method is exactly what you need. Calling this on the iterator tells it not to dive into the current directory at all.
Here's how to integrate this with your existing code structure:
#include <iostream> #include <experimental/filesystem> #include <string> #include <vector> namespace fs = std::experimental::filesystem; int main() { // Use vectors for more flexible list management std::vector<std::string> target_extensions = { ".doc", ".docx", ".txt" }; std::vector<std::string> ignored_directories = { "Windows", "Program Files" }; for (fs::recursive_directory_iterator it("your_root_directory"), end; it != end; ++it) { // Check if we're looking at a directory to ignore if (fs::is_directory(it->status())) { std::string dir_name = it->path().filename().string(); for (const auto& ignore_dir : ignored_directories) { if (dir_name == ignore_dir) { it.skip(); // Stop recursing into this directory break; } } } else { // Check if the file has a target extension std::string file_ext = it->path().extension().string(); for (const auto& ext : target_extensions) { if (file_ext == ext) { std::cout << "Found document: " << it->path() << std::endl; break; } } } } return 0; }
I swapped your fixed arrays for std::vector here—it's easier to add/remove entries later without adjusting array sizes manually.
2. Stop the Entire Traversal Immediately
If you need to end the whole recursive search (not just skip one directory), you can simply break out of the loop when your condition is met. For example, stopping as soon as you find the first matching file:
for (fs::recursive_directory_iterator it("your_root_directory"), end; it != end; ++it) { if (fs::is_regular_file(it->status())) { std::string file_ext = it->path().extension().string(); if (file_ext == ".docx") { std::cout << "Found target file: " << it->path() << std::endl; break; // Halts all recursion right away } } }
3. Limit Recursion Depth
If you only want to search a certain number of levels deep (e.g., don't go past subfolders of subfolders), you can use the iterator's depth() method to track how far down you are, then skip deeper directories:
const int MAX_RECURSION_DEPTH = 2; // Only search root + 1 level of subfolders for (fs::recursive_directory_iterator it("your_root_directory"), end; it != end; ++it) { if (it.depth() >= MAX_RECURSION_DEPTH) { it.skip(); // Don't go beyond the max depth continue; } // Your file-checking logic here... }
内容的提问来源于stack exchange,提问作者newboi

