使用boost::filesystem递归地列出目录文件

list directory files recursively with boost::filesystem

本文关键字:文件 boost filesystem 递归 使用      更新时间:2023-10-16

我使用新的boost, v1.5.3,像下面这样执行这个任务,这要归功于类recursive_directory_iterator(我不必编写递归代码):

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

我几乎想不出这个错误的原因。有人能试试吗?赶上帮助吗?提前感谢您的帮助

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

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

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

你可以尝试这样做:

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