在ifstreams中使用seekg保持有效位置
我正在努力使我的文件解析更加强大。使用 ifstream,如何确保 seekg
将我保持在文件中的有效位置?
这是行不通的:
while(m_File.good() && m_File.peek() != EOF)
{ ...a seekg operation moves file position past end of file... }
我假设当前迭代器已经被推到了结束迭代器之后,所以 peek() 永远不会成立。
I am trying to make my file parsing more robust. Using an ifstream, how can I ensure seekg
keeps me in a valid position within the file?
This does not work:
while(m_File.good() && m_File.peek() != EOF)
{ ...a seekg operation moves file position past end of file... }
I assume the current iterator has been pushed way past the end iterator, so the peek() is never true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有办法做到这一点,除非找到文件末尾的偏移量并确保您不会超出它,这会导致未定义的行为 - 您当然可以通过写入来增加文件的大小。
No, there is no way of doing this, short of finding the offset of the end of file and making sure you don't seek beyond it, which causes undefined behaviour - you can of course increase the size of the file by writing.
如果当您到达错误位置时出现错误(例如,它不应该发生),您可以尝试设置 流异常掩码,并在 while 循环之外捕获适当的异常。在这种情况下,这将是“最干净”的解决方案。
If it's an error when you reach a bad position (e.g. it shouldn't happen) you may try to set the stream exception mask, and catch the appropriate exception outside of the while loop. In that case it'd be the "cleanest" solution.