You can stop the iteration prematurely by using the break
statement within your loop. This allows you to exit the loop based on a specific condition or requirement.
Here’s an example where we stop the iteration after finding a specific file:
#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) {
std::cout << iter->path().string() << '\n';
if (iter->path().filename() == "stop_here.txt") {
break; // Stop iteration
}
}
}
c:\test\file1.txt
c:\test\file2.txt
c:\test\stop_here.txt
Here’s another example where we stop after processing a certain number of files:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
int count = 0;
// Maximum files to process
const int max_files = 5;
for (auto iter{start}; iter != end; ++iter) {
if (count >= max_files) {
break; // Stop after processing max_files
}
std::cout << iter->path().string() << '\n';
++count;
}
}
c:\test\file1.txt
c:\test\file2.txt
c:\test\file3.txt
c:\test\file4.txt
c:\test\file5.txt
For more complex conditions, you can combine multiple checks:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
bool should_stop(const fs::directory_entry& entry) {
// Example condition: stop at specific file
// or if file size exceeds limit
return entry.path().filename() == "stop_here.txt"
|| entry.is_regular_file()
&& entry.file_size() > 1024;
}
int main() {
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
if (should_stop(*iter)) {
break;
}
std::cout << iter->path().string() << '\n';
}
}
c:\test\file1.txt
c:\test\file2.txt
c:\test\file3.txt
Stopping the iteration prematurely is a straightforward process in C++. Use conditions and the break
statement to control the flow of your directory traversal as needed.
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