recursive_directory_iterator引发异常 [英] recursive_directory_iterator throws exception

查看:144
本文介绍了recursive_directory_iterator引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用boost迭代器"recursive_directory_iterator"来递归扫描目录.但是,当迭代器运行到我的应用程序无法访问的目录中时,将引发类型为"boost :: filesystem3 :: filesystem_error"的异常,这将终止迭代器,并且程序将中止.无论如何,我可以指示迭代器跳过此类目录.

I am using the boost iterator "recursive_directory_iterator" to recursively scan through a directory. However, when the iterator runs into a directory for which my application does not have access, exception of type "boost::filesystem3::filesystem_error" is thrown, which halts the iterator and the program aborts. Is there anyway I can instruct the iterator to skip over such directories.

我尝试了建议使用的代码遍历带有boost:的目录:文件系统而不会引发异常但是,它对我没有用.我正在使用Boost 1.49.

I tried the code suggested at Traversing a directory with boost::filesystem without throwing exceptions However, it did nor work for me. I am using boost version 1.49.

遵循建议(我能提出的最好建议)后,我的代码如下:

My code after following the suggestion (the best I could come up with), looks as follows:

void scand()
{
    boost::system::error_code ec, no_err;

    // Read dir contents recurs
    for (recursive_directory_iterator end, _path("/tmp", ec);
         _path != end; _path.increment(ec)) {

        if (ec != no_err) {
            _path.pop();
            continue;
        }
        cout << _path->path() << endl;
    }
}

谢谢你,艾哈迈德.

推荐答案

这是boost :: filesystem(V3)中的一个已知错误:

This is a known bug in boost::filesystem (V3): https://svn.boost.org/trac/boost/ticket/4494. Depending on your needs you could use V2 of the library instead (it may even come with your compiler in the form of std::tr2::filesystem). Another option is to implement the recursive part yourself.

boost::system::error_code ec;
std::deque<boost::filesystem::path> directories {initialDir};
while(!directories.empty())
{
  boost::filesystem::directory_iterator dit(directories.front(), ec);
  directories.pop_front();
  while(dit != boost::filesystem::directory_iterator())
  {
    if(boost::filesystem::is_directory(dit->path(), ec))
    {
      directories.push_back(dit->path());
    }
    HandleFile(dit->path()); // <-- do something with the file
    ++dit;
  }
}

上面的代码只是为了提供一个总体思路,缺少错误检查以及其他功能.

The above code is just to give a general idea, error checking among other things are missing.

这篇关于recursive_directory_iterator引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆