Verzeichnis rekursiv mit C++17-filesystem-Bibliothek auflisten
English
Deutsch
Note: To find out how to list a directory non-recursively, just replace recursive_directory_iterator by directory_iterator or see our full post How to list a directory using C++17 filesystem library.
To recursively list a directory using the C++17 filesystem library use this snippet:
recursive_list_example.cpp
#include <experimental/filesystem>
using namespace std::experimental::filesystem;
for(const directory_entry& entry : recursive_directory_iterator("my-directory")) {
const auto& path = entry.path();
// ...
}Vollständiges Beispiel:
recursive_list_full.cpp
#include <iostream>
#include <string>
#include <experimental/filesystem>
using namespace std;
using namespace std::experimental::filesystem;
int main() {
for(const directory_entry& entry : recursive_directory_iterator("my-directory")) {
// Ist es eine Datei / ein Verzeichnis?
bool isNormalFile = is_regular_file(entry);
bool isDirectory = is_directory(entry);
auto path = entry.path();
// Pfad: my-directory/test.txt
string pathString = path.string();
// Dateiname: test.txt
string filenameString = path.filename().string();
// Erweiterung: txt
string extensionString = path.extension().string();
// HINWEIS: Du kannst auch direkt "cout << path" verwenden
}
}Kompiliere so:
build_filesystem_example.sh
g++ -o filesystem-example filesystem-example.cpp -lstdc++fsFür dieses Verzeichnis:
test-directory-structure.txt
my-directory
├── subdirectory
│ └── subdir-test.txt
└── test.txtdies wird subdirectory, subdirectory/subdir-test.txt und test.txt auflisten.
Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow