В следующем коде я строю использование API std::filesystem
, чтобы получить то, что вы просите. Пожалуйста, дайте мне знать, если я неправильно понял ваш вопрос.
Я объясняю код в комментариях.
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
/** Print each file in the directory, separate files in different directories
* with a horizontal line.
*/
void example1() {
for (auto &p : fs::recursive_directory_iterator(".")) {
if (p.is_directory()) { // We could do something fancy and stop if the
// p.path() is what we are looking for.
std::cout << "--------\n";
continue;
}
std::cout << p.path() << '\n';
}
}
/** Let's recurse until we went down the first path along the Depth-First path.
*
* The easy way to do this, is to stop as soon as the first file is found. (See
* <TODO>)
*
* But with a custom loop, we can potentially do more.
*/
void example2() {
auto it = fs::recursive_directory_iterator(".");
while (it != end(it)) { // Note: fs::end(...) argument is ignored.
std::cout << it->path() << "\t" << it.depth() << "\n";
/* 1. it++: This moves to the next entry. That's the default thing to do.
* 2. it.pop(). "moves the iterator one level up in the directory hierarchy"
* This might be useful if we are looking for specific files, and want to
* continue in the next directory.
* 3. it.disable_recursion_pending(): It means that it won't go into
* subdirectories.
*/
it++; // Code style: If we always just increment it, for(it; it!=end(it);
// it++) is better than a while loop.
}
}
/** If I understood this correctly, you want to stop as soon you hit a directory
* named 'anothersub'.
*/
void example3() {
for (auto it = fs::recursive_directory_iterator("."); it != end(it); it++) {
const auto p = it->path();
if (it->is_directory() and p.filename() == "anothersub") {
break;
}
std::cout << p << "\n";
}
}
int main() {
example1();
example2();
example3();
}
https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator
https://en.cppreference.com/w/cpp/filesystem/directory_entry