In C++17 it became easy to iterate over the items in some directory dir
:
for ( auto& dirEntry: std::filesystem::directory_iterator(dir) )
{
if ( !dirEntry.is_regular_file() ) continue;
...
Unfortunately this way may throw exceptions, which I want to avoid in my program.
The iteration without throwing exceptions is also possible:
std::error_code ec;
const std::filesystem::directory_iterator dirEnd;
for ( auto it = std::filesystem::directory_iterator( dir, ec ); !ec && it != dirEnd; it.increment( ec ) )
{
if ( !it->is_regular_file( ec ) ) continue;
...
but it is much wordier in C++. For example, I cannot use range based for. And this larger code size is really significant for me since I have a lot of places with iteration. Is there a way to simplify the code iterating directory items and still avoid exceptions?