我试图学习如何写入二进制文件,然后将信息读回变量。我试图在c3&中制作信息c4和c1& c2从二进制文件中读取。我已经搜索并尝试了好几个小时,但我无法弄清楚我做错了什么。请帮忙。
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;
struct Cat {
char name[50];
int age;
};
//----- TEXT I/O -----//
void display(Cat& cat) {
cout << cat.name << endl;
cout << cat.age << endl;
}
//----- BINARY I/O -----//
void writeBinaryData(ofstream& binaryFile, Cat& cat) {
binaryFile.write(cat.name, sizeof(char[50]));
binaryFile.write(reinterpret_cast<char*>(&cat.age), sizeof(int));
}
void readBinaryData(ifstream& binaryFile, Cat& cat) {
binaryFile.read(cat.name, sizeof(char[50]));
binaryFile.read(reinterpret_cast<char *>(&cat.age), sizeof(int));
}
int main() {
Cat c1, c2, c3, c4;
// c1's name is Ben and age is 2
strcpy(c1.name, "Ben");
c1.age = 2;
// c2's name is Willard and age is 3
strcpy(c2.name, "Willard");
c2.age = 3;
// display c1 & c2
display(c1);
display(c2);
// read and write c1 & c2 to binary data file
ofstream binOut("catfarm.bin", ios::out | ios::binary);
writeBinaryData(binOut, c1);
writeBinaryData(binOut, c2);
// read from binary file into c3 & c4
ifstream binIn("catfarm.bin", ios::in | ios::binary);
readBinaryData(binIn, c3);
readBinaryData(binIn, c4);
display(c3);
display(c4);
return 0;
}
现在输出如下:
Ben
2
Willard
3
32701
32701
但它应该是这样的:
Ben
2
Willard
3
Ben
2
Willard
3