繁体   English   中英

C ++ fstream提示行为

[英]C++ fstream tellg behaviour

我正在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::int32 boost::int32实际上是一个int ,而不是一个结构。 即使将它们更改为int也会得到相同的结果。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM