c++ - 在循环内删除文件时 boost recursive_directory_iterator 失效

标签 c++ boost

我发现 boost::recursive_directory_iterator 与 boost::directory_iterator 有不同的行为

所以我有两个结构:

struct directory_range
{
    typedef bfs::directory_iterator iterator;

    directory_range(bfs::path p) : m_p(p) {}

    iterator begin() { return bfs::directory_iterator(m_p); }

    iterator end() { return bfs::directory_iterator(); }

    bfs::path m_p;
};

一个具有directory_iterator 并且具有与recursive_directory_iterator 相同的结构作为iterator recursive_directory_range

我像这样在循环中使用它们:

for (const auto &it : directory_range(folder)) {
  if(expression){
    std::cout << "\n :clean: removing file : " << it.path();
    bfs::remove(it.path());
  }
} 

当我使用 directory_range 时,一切都很好。 当我在第一次删除后切换到 recursive_directory_range 时,我得到了

filesystem::recursive_directory_iterator directory error: No such file or directory

我不知道为什么,因为在文档中有关于这两个迭代器的相同声明,即在循环中删除时它们不会失效。

最佳答案

来自文档 ( reference ):

If a file is removed from or added to a directory after the construction of a directory_iterator for the directory, it is unspecified whether or not subsequent incrementing of the iterator will ever result in an iterator whose value is the removed or added directory entry.

还有:

The order of the path entries returned by dereferencing successive increments of a directory_iterator is unspecified.

原因:这里最有可能发生的情况是您正在删除一个尚未递归迭代的目录,因此您得到了错误。

解决方案:可能有多种解决方案,例如,您可以编写自己的递归函数,该函数仅使用非递归目录迭代器,首先下降到子目录,然后删除文件在所有子路径都返回之后。

关于c++ - 在循环内删除文件时 boost recursive_directory_iterator 失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41714427/

相关文章:

c++ - 如何使用 `requires` 和 `-> return_type` 声明成员函数

c++ - Boost 是否因为不像 Boost 那样有罪?

c++ - BOOST 版本 1.46.1 与 Visual Studio 2010 P.E

c++ - 如何通过 boost spirit 提取 std::string 对象

c++ - 即使没有建立连接,绑定(bind)也会返回正在使用的地址

c++ - 返回 &const 或 *const? (c++)

c++ - Boost 程序选项中的 vector 参数

c++ - boost::unordered_map 中的运算符 []

c++ - 反转由空格分隔的字符串的元素返回比原始字符串更大的字符串

c++ - Linux 上的守护程序监控/日志记录(应用程序计数器)