我正在 Visual Studio 2012 中开发 C++ 应用程序(32 位)。当我使用 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。
usedBlocks
是一个 boost::int32
。 boost::int32
实际上是一个 int
,而不是一个结构。即使将它们更改为 int 也会得到相同的结果。
最佳答案
如果您在调试器中查看 pos
的值,由于优化,它们可能是错误的。
尝试将 pos
的值打印到标准输出中。
关于C++ fstream 告诉行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17586307/