【发布时间】:2013-07-11 06:16:43
【问题描述】:
我正在使用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。
usedBlocks 是 boost::int32。 boost::int32 实际上是 int,而不是结构。即使将它们更改为 int 也会得到相同的结果。
【问题讨论】:
-
reservedSize 的类型是什么?
-
我不熟悉
open函数的重载。我很确定这不是标准的。无论如何,这不是您放置ios::binary的地方。您需要在第二个参数中将它与ios::in一起按位或。即file.open(filename, std::ios::in | std::ios::binary);-- 第三个参数用于其他内容(文件保护规范),您可能甚至不应该使用它。 -
谢谢。我错误地把逗号放在那里。我应该使用 |