简体   繁体   English

C ++ fstream提示行为

[英]C++ fstream tellg behaviour

I am working on a C++ application in Visual Studio 2012 (32-bit). 我正在Visual Studio 2012 (32位)中使用C ++应用程序。 When I read a file using fstream and read four bytes twice, I get confusing values from tellg. 当我使用fstream读取文件并读取四个字节两次时,我从Tellg中得到了令人困惑的值。 I was expecting 0, 4 and 8. 我期待的是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

Why does this happen? 为什么会这样?

I have changed the code to use fopen, fread, and ftell, and then the pos values are 0, 4 and 8. 我将代码更改为使用fopen,fread和ftell,然后pos值为0、4和8。

usedBlocks is a boost::int32 . usedBlocksboost::int32 boost::int32 is actually an int , not a struct. boost::int32实际上是一个int ,而不是一个结构。 Even changing them to int gives the same result. 即使将它们更改为int也会得到相同的结果。

If you are looking at the values of pos in the debugger, they may be wrong due to optimization. 如果在调试器中查看pos的值,由于优化,它们可能是错误的。

Try printing the values of pos into the standard output. 尝试将pos的值打印到标准输出中。

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

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