2013-07-11 84 views
0

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

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,然后将正的值是0,4和8

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

+0

reservedSize是什么类型? – Alexis

+2

我不熟悉'open'函数的重载。我很确定这不是标准。无论如何,这不是你把'ios :: binary'的地方。您需要在第二个参数中将它与'ios :: in'一起按位或运算。即'file.open(filename,std :: ios :: in | std :: ios :: binary);' - 第三个参数用于其他内容(文件保护规范),你甚至可能不应该使用它。 –

+0

谢谢。我错误地把逗号放在那里。 我应该使用| – Haunted

回答

1

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

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

+0

我的确看过调试器的价值。谢谢你指出它可能是错的。 – Haunted