I have the following code:
for (const auto& x : std::filesystem::directory_iterator(dir)) {
// do stuff with x
}
dir
might not exist, and I want to treat this case as if the dir is empty. I can't seem to come up with a nice option.
try
/catch
, then I'll be catching the iteration code exceptions as well, I don't want that.std::filesystem::directory_iterator
construction up and guard it with try
/catch
, it becomes verbose, and I'll have to re-throw all other exceptions (won't it screw up stack traces and such?).directory_iterator
, I'll have to throw std::error_code
for other errors. I'm not sure how to do that.According to std::filesystem::directory_iterator
's documentation it has both default and move constructors. So:
std::filesystem::directory_iterator iter;
try {
iter=std::filesystem::directory_iterator{dir};
} catch(...)
{
// catch it
}
for (const auto& x : iter) {
// do stuff with x
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With