从C 中的二进制文件获取整数值时
Garbage value when getting integer value from binary file in c++
我正在研究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的答案已经有了问题的答案,即您的代码为何行为的方式。
这是解决问题的两种方法。
-
使用
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();
-
正确使用
while
循环。readFile.open("file.dat", ios::binary); while (readFile.read((char*)(&temp), sizeof(temp))) { cout << "temp: " << temp << endl; } readFile.close();
相关文章:
- 如何获取矢量循环的整数位置
- 获取我的基类以递增派生类对象整数
- 从两个 4x64 位整数数组中获取取模
- 如何获取进程的整数PID?
- 从 stdio 获取一行空格分隔的整数,而不知道它们是多少 (C++)
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何在 c++ 中正确从正整数中获取偶数和奇数?
- 快速扫描标准以获取整数不起作用
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 只要用户输入,如何从用户那里获取整数?
- 如何交替从文件中获取一行数据和一个整数?
- 获取两个无符号整数 C++ 乘积的高 32 位的有效方法
- 如何从另一个类动态获取整数?
- 如何使用字符串和整数获取汽车类的整数结果
- 控制台在获取整数后暂停
- C++一次从文本文件中获取每 2 个整数作为对
- 在某些范围更新后获取整数数组的最终状态的有效算法是什么?
- 如何从从 MPU 陀螺仪发送的字节数组中获取整数
- 获取所有方式以两个整数的产品表示数字
- 如何在C 中获取整数数组的元素