Directory_iterator - 复制到“倒带”?
所以我写了一个小程序来尝试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
但是我得到以下输出(为了简洁起见,省略了整个路径):
$程序.exe
文件总数:3
[..]/program.pdb
断言失败:m_imp->m_handle != 0 && “内部程序错误”,文件 c:\program files\boost\boost_1_44\boost\filesystem\v2\operations.hpp,第 1001 行
如果我执行一个新的directory_iterator,则它工作正常:
di = start;
// .. becomes ..
di = directory_iterator(current_path());
我注意到 类似问题相关Directory_iterators 但我不知道他们指的是什么或者是否是同一个问题。
问题是: 为什么我不能保存启动迭代器,然后使用它来倒回迭代器?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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).