【问题标题】:list directory files recursively with boost::filesystem使用 boost::filesystem 递归地列出目录文件
【发布时间】:2013-03-03 06:11:14
【问题描述】:

感谢 recursive_directory_iterator 类(我不必编写递归代码),我正在使用新的 boost v1.5.3 来执行如下任务:

void ListDirRec(const char *Dir, vector<string>& DirFileList, const char* ext)
{    
recursive_directory_iterator rdi(Dir);  
recursive_directory_iterator end_rdi;

DirFileList.empty();

string ext_str0(ext);   
for (; rdi != end_rdi; rdi++)
{
    rdi++;
    //cout << (*di).path().string() << endl;
    cout << (*rdi).path().string() << endl;

    //cout << " <----- " << (*rdi).path().extension() << endl;

    //string ext_str1 = (*rdi).path().extension().string();
    if (ext_str0.compare((*rdi).path().extension().string()) == 0)
    {
        DirFileList.push_back((*rdi).path().string());
    }
}

具有特定扩展名的函数列表文件。此函数适用于某些情况,但经常返回“断言失败错误”,例如:

**** Internal program error - .... assertion (m_imp.get()) ... operations.hpp(952): dereference of end recursive_directory_iterator

我几乎没有弄清楚这个错误的原因。任何尝试..赶上帮助? 在此先感谢您的帮助

【问题讨论】:

  • 我根本没有使用 boost::filesystem 但你不应该为 end_rdi 分配任何东西吗?
  • @dutt 不,没关系,默认构造函数最后返回迭代器(docs),就像std::istream_iterator&lt;T&gt;一样
  • @ShawnLe - 感谢您提供此代码。我稍微修改了它以满足我的需要,但这对于帮助递归查找目录中与扩展名匹配的文件非常有用。
  • DirFileList.empty(); 什么都不做。如果 DirFileList 为空,则返回 true。如果要擦除所有元素,请使用clear()

标签: c++ boost runtime-error boost-filesystem


【解决方案1】:

您在循环内以及 for 声明中递增 rdi

for (; rdi != end_rdi; rdi++)
{
    rdi++;

这意味着rdi 可能是循环中的end_rdi(结束迭代器,表示经过最后一个元素)。你这样做有什么理由吗? (如果这是故意的,你应该在增加它之后再次检查以确保rdi != end_rdi。)

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    recursive_directory_iterator dir(path(Dir));
    for(auto&& i : dir) {
        if (is_directory(i)) {
            //Do whatever you want
            cout << i << endl;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-11
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多