Home > OS >  How to continue to next item in iterator using recursive_directory_iterator
How to continue to next item in iterator using recursive_directory_iterator

Time:11-25

I am currently iterating through a filesystem. I want to capture any errors that occur and then just continue iterating. The current behavior if an error occurs it will set the current iterator to the end and then the for loop exits. I would like for this to skip that path and continue.

    try {
        for (const auto& dirEntry : recursive_directory_iterator(myPath)) {
            std::cout << dirEntry << std::endl;
        }
    } catch (...) {
        std::cout << "ERROR" << std::endl;
        //continue iteration
    }

EDIT: This is my little sample that I am working with. The error occurs on the recursive_directory_iterator. Specifically it errors out when accessing a folder it does not have access to. I know I can add std::filesystem::directory_options::skip_permission_denied and it will skip those folders, but what about just errors in general? I am not sure if that would ever occur so maybe I am overthinking it? Would permissions be the only reason this would error?

CodePudding user response:

You can't recover from errors in recursive_directory_iterator.

If the recursive_directory_iterator reports an error or is advanced past the last directory entry of the top-level directory, it becomes equal to the default-constructed iterator, also known as the end iterator.

From cppreference

CodePudding user response:

Just put the try/catch inside the for loop:

for (const auto& dirEntry : recursive_directory_iterator(myPath)) {
    try {
        std::cout << dirEntry << std::endl;
    } catch (...) {
        std::cout << "ERROR" << std::endl;
        //continue iteration
    }
}

CodePudding user response:

Instead of having the iterator throw exceptions, you can pass in a reference to an error code when constructing the iterator, which will be used to store any errors found during iteration. The error code can then be inspected in the loop to check whether any errors occurred during iteration:

std::error_code ec{};
for (const auto& entry : std::filesystem::recursive_directory_iterator(..., ec)) 
{
   if (ec)
   {
     // handle error...
     ec = std::error_code{};
     continue;
   }
}
  • Related