简体   繁体   中英

C++ fstream tellg behaviour

I am working on a C++ application in Visual Studio 2012 (32-bit). When I read a file using fstream and read four bytes twice, I get confusing values from tellg. I was expecting 0, 4 and 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.

usedBlocks is a boost::int32 . boost::int32 is actually an int , not a struct. Even changing them to int gives the same result.

If you are looking at the values of pos in the debugger, they may be wrong due to optimization.

Try printing the values of pos into the standard output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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