If the directory path provided to std::filesystem::directory_iterator
does not exist, the iterator will fail to initialize properly and may throw an exception. It is important to handle such scenarios gracefully in your code.
Here’s how you can handle a missing directory path:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
const fs::path dir_path{R"(c:\nonexistent)"};
if (fs::exists(dir_path)) {
fs::directory_iterator start{dir_path};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
std::cout << iter->path().string() << '\n';
}
} else {
std::cerr << "Directory does not exist: "
<< dir_path.string();
}
}
Directory does not exist: c:\nonexistent
std::filesystem::exists()
to check if the directory path exists.std::filesystem::directory_iterator
if the directory exists.Alternatively, you can use exception handling to catch errors:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
try {
fs::directory_iterator start{
R"(c:\nonexistent)"};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
std::cout << iter->path().string() << '\n';
}
} catch (const fs::filesystem_error& e) {
std::cerr << "Filesystem error: "
<< e.what();
}
}
Filesystem error: directory_iterator: The system cannot find the path specified.: "c:\nonexistent"
Using these techniques ensures your program can handle missing directory paths gracefully, improving robustness and user experience.
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