4

所以我写了一个小程序来试试Boost Filesystem。我的程序将写入当前路径中有多少个文件,然后是文件名。这是我的程序:

#include <iostream>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

int main(){
    directory_iterator start = directory_iterator(current_path());
    directory_iterator di = start;
    int count;
    for (count = 0; di != directory_iterator(); ++di, ++count);
    std::cout << std::endl << "total number of files: " << count << std::endl;
    di = start;
    for (; di != directory_iterator(); ++di){
        std::cout << *di << std::endl;
    }
    return 0;
}

现有文件是 program.exe、.ilk 和 .pdb
但是我得到以下输出(为简洁起见,省略了整个路径):

$ program.exe
文件总数:3
[..]/program.pdb
断言失败:m_imp->m_handle != 0 && "internal program error", file c:\program files\boost\boost_1_44\boost\filesystem\ v2\operations.hpp,第 1001 行

如果我做一个新的 directory_iterator 代替它工作正常:

di = start;
// .. becomes ..
di = directory_iterator(current_path());

I noticed a similar question related to directory_iterators but I have no idea what they are referring to or if it's the same issue.

Question is: Why can't I save a startiterator and then use that to rewind my iterator?

4

1 回答 1

1

It is the same issue.

The directory iterator is a one pass iterator. You cannot save a copy and go a second pass. Each time you increment the iterator you get the next entry, but you cannot decrement it and you cannot go back and start over, not even if you have saved a copy of the starting point.

If you want to traverse twice, you need to create another iterator (and risk that the number of files has changed).

于 2011-07-04T13:01:12.137 回答