【问题标题】:C++ fstream tellg behaviourC++ fstream 告诉行为
【发布时间】:2013-07-11 06:16:43
【问题描述】:

我正在使用Visual Studio 2012(32 位)开发 C++ 应用程序。当我使用 fstream 读取一个文件并读取四个字节两次时,我从 tellg 得到了令人困惑的值。我期待的是 0、4 和 8。

std::fstream file;
file.open(filename, std::ios::in , std::ios::binary);
if ( !file.is_open())
{
    throw exception("Error opening file for reading");
}
int pos = file.tellg();  // pos is 0
boost::int32_t usedBlocks;
int size = sizeof (usedBlocks);
file.read(reinterpret_cast<char*>(&usedBlocks),sizeof(usedBlocks));
pos = file.tellg();      //pos is 3588
//Read reserved size
file.read(reinterpret_cast<char*>(&reservedSize),sizeof(reservedSize));
pos = file.tellg();     //pos is 3592

为什么会这样?

我已将代码改成使用fopen、fread和ftell,然后pos值为0、4和8。

usedBlocksboost::int32boost::int32 实际上是 int,而不是结构。即使将它们更改为 int 也会得到相同的结果。

【问题讨论】:

  • reservedSize 的类型是什么?
  • 我不熟悉 open 函数的重载。我很确定这不是标准的。无论如何,这不是您放置ios::binary 的地方。您需要在第二个参数中将它与ios::in 一起按位或。即file.open(filename, std::ios::in | std::ios::binary); -- 第三个参数用于其他内容(文件保护规范),您可能甚至不应该使用它。
  • 谢谢。我错误地把逗号放在那里。我应该使用 |

标签: c++ fstream


【解决方案1】:

如果您在调试器中查看pos 的值,它们可能由于优化而出错。

尝试将pos 的值打印到标准输出中。

【讨论】:

  • 我确实从调试器中查看了值。感谢您指出它可能是错误的。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2014-08-08
  • 2023-03-02
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
相关资源
最近更新 更多