在ifstreams中使用seekg保持有效位置

发布于 2024-08-15 11:40:41 字数 282 浏览 2 评论 0原文

我正在努力使我的文件解析更加强大。使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风渺 2024-08-22 11:40:41

不,没有办法做到这一点,除非找到文件末尾的偏移量并确保您不会超出它,这会导致未定义的行为 - 您当然可以通过写入来增加文件的大小。

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.

梦言归人 2024-08-22 11:40:41

如果当您到达错误位置时出现错误(例如,它不应该发生),您可以尝试设置 流异常掩码,并在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文