如何使用 recursive_directory_iterator 继续迭代器中的下一个项目

How to continue to next item in iterator using recursive_directory_iterator

我目前正在遍历文件系统。我想捕获发生的任何错误,然后继续迭代。如果发生错误,当前行为会将当前迭代器设置为结束,然后 for 循环退出。我希望它跳过那条路并继续。

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

编辑:这是我正在使用的小样本。错误发生在 recursive_directory_iterator。特别是在访问它无权访问的文件夹时会出错。我知道我可以添加 std::filesystem::directory_options::skip_permission_denied 并且它会跳过那些文件夹,但是一般的错误呢?我不确定这种情况是否会发生,所以也许我想多了?权限是这会出错的唯一原因吗?

只需将 try/catch 放在 for 循环中即可:

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

您无法从 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.

来自cppreference

您可以在构造迭代器时传入对错误代码的引用,而不是让迭代器抛出异常,该引用将用于存储迭代期间发现的任何错误。然后可以在循环中检查错误代码,检查迭代过程中是否发生错误:

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