So I wrote a small program to try out Boost Filesystem. My program will write how many files there is in the current path and then the file names.
Here’s my program:
#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;
}
files existing are program.exe, .ilk and .pdb
However I get the following output (whole path left out for brevity):
$ program.exe
total number of files: 3
[..]/program.pdb
Assertion failed: m_imp->m_handle != 0 && “internal program error”, file c:\program files\boost\boost_1_44\boost\filesystem\v2\operations.hpp, line 1001
If I do a new directory_iterator instead it works fine:
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?
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).