Boost.Filesystem崩溃了

时间:2011-06-09 07:41:02

标签: c++ boost boost-filesystem

有没有人有这个问题?使用recursive_directory_iterator搜索分区时,当它到达结尾时崩溃 我在Visual Studio 2008中使用boost 1.39获得此功能,但在家中使用MinGW并使用boost 1.46。我不认为我做错了什么:

#include "stdafx.h"
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;




int _tmain(int argc, _TCHAR* argv[])
{
    boost::filesystem::path musicPaths("d:\\");
    for(boost::filesystem::recursive_directory_iterator it(musicPaths); it != boost::filesystem::recursive_directory_iterator(); ++it)
    {
        string strToFind = ".mp3";
        boost::filesystem::path dummypath = it->path().filename();
        string str = dummypath.string();
        if(str.find(strToFind) != -1)
        {
            cout << str << endl;
        }
    }
    return 0;
}

编辑:
我发现它最终没有崩溃但是当它达到系统卷信息时

3 个答案:

答案 0 :(得分:3)

Windows不允许您查看“系统卷信息”目录。 因此,在“系统卷信息”上释放recursive_directory_iterator是一个坏主意。

编辑:您可以使用recursive_directory_iterator :: no_push()解决问题。来自The Boost docs:

void no_push(bool value=true);

    Requires: *this != recursive_directory_iterator().

    Postcondition: no_push_pending() == value.

    Throws: Nothing.

    [Note: no_push() is used to prevent unwanted recursion into a directory. --end note]

答案 1 :(得分:1)

在移动到下一个迭代器之前,你应该调用no_push()。

伪代码:

if(*它是我想要跳过的目录)     it.no_push(); ++它;

答案 2 :(得分:0)

定义HDIR_DEEP_ITERATOR_BASE boost :: filesystem :: recursive_directory_iterator

class dir_deep_iterator:public HDIR_DEEP_ITERATOR_BASE

{

公共:

.....

dir_deep_iterator & operator ++()

{

    try

    {

        return (dir_deep_iterator &)HDIR_DEEP_ITERATOR_BASE::operator ++();

    }

    catch(...)

    {

        //有些特殊的目录无法打开,比如"System Volume Information",导致抛出异常

        no_push(true);

        return (dir_deep_iterator &)HDIR_DEEP_ITERATOR_BASE::operator ++();

    }

}

....

}