从C 中的二进制文件获取整数值时

Garbage value when getting integer value from binary file in c++

本文关键字:整数 获取 二进制文件      更新时间:2023-10-16

我正在研究C 的二进制文件。我为此制作了示例代码,但是它运行不佳。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream writeFile;
    ifstream readFile;
    int temp = 1;
    writeFile.open("file.dat", ios::binary);
    for (int i = 5; i <= 10 ; i++) // range 5 to 10
        writeFile.write((char*)(&i), sizeof(i));
    writeFile.close();
    readFile.open("file.dat", ios::binary);
    readFile.seekg(0);
    while (!readFile.eof()) {
        readFile.read((char*)(&temp), sizeof(temp));
        cout << "temp: " << temp << endl;
        readFile >> ws;
    }
    readFile.close();
    system("pause");
    return 0;
}

这是结果:

temp: 5
temp: 6
temp: 7
temp: 8
temp: 167772160
temp: 167772160

当我更改范围不包括9(例如5至8)时,它效果很好。另外,当我使用双重类型制作相同的代码时,它可以很好地工作。因此,我认为整数9是问题。你能告诉我为什么吗?

readFile >> ws;丢弃了白空间,这对于二进制流是无意义的。在这种情况下,角色值9(即't')被跳过,破坏了您的流。只需删除该线即可。

第二个问题是您没有在读取和显示值之间检查流的状态。仅在后才检测到eof 读取将超过文件的末尾。这就是为什么您两次获得无效值的原因,第二次读取失败,而只需将temp留下以前的值。有关更多详细信息,请参见此问题。

françoisAndrieux的答案已经有了问题的答案,即您的代码为何行为的方式。

这是解决问题的两种方法。

  1. 使用for循环读取数字。它反映了用于写入它的循环。

    readFile.open("file.dat", ios::binary);
    for (int i = 5; i <= 10 ; i++)
    {
       readFile.read((char*)(&temp), sizeof(temp));
       cout << "temp: " << temp << endl;
    }
    readFile.close();
    
  2. 正确使用while循环。

    readFile.open("file.dat", ios::binary);
    while (readFile.read((char*)(&temp), sizeof(temp)))
    {
       cout << "temp: " << temp << endl;
    }
    readFile.close();