C++ fstream 告诉行为

标签 c++ fstream

我正在 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::int32boost::int32 实际上是一个 int,而不是一个结构。即使将它们更改为 int 也会得到相同的结果。

最佳答案

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

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

关于C++ fstream 告诉行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17586307/

相关文章:

c++ - 在我的 cpp 或头文件中找不到错误,类构造失败

C++ 在 std::list<> 中存储大数据 ..我应该使用引用计数吗?

c++ - 函数和/或类的包可访问性

c++ - 如何在 C++ 中的 ifstream 函数生成的文件中搜索特定单词

c++ - 更改 DDX_Text() 的 MessageBox 的标题

c++ - 线程安全持有人

c++ - 无法在 C++ 中创建文本文件

c++ - 从文件中读取值并使用类

c++ - 数组定位、fstream、char比较

c++ - C++ 中的 is_open() 函数始终返回 0 值,而 getLine(myFile, line) 不返回任何内容