我一直在尝试使用fstream将一些数据写入c ++中的二进制文件,大多数示例都是这样的:
#include <fstream>
class Person{
public:
int age;
char name[50];
}
int main(){
Person joe;
joe.age = 50;
strncpy(joe.name, "Joe Jones");
fstream file("filename.dat", ios_base::binary);
file.write((char*)joe, sizeof(joe));
file.close();
}
这与预期的一样,但是当我尝试编写一个更复杂的结构时出现问题,主要是一个带有指针而不是实际数据的结构。
class Person{
public:
int age;
int *friendsAges;
Person(int friends){
friendsAges = new int[friends];
}
}
当我像之前那样写数据时
Person joe(10);
/* Initialize rest of joe */
file.write((char*)joe, sizeof(joe));
生成的文件包含8个字节的数据,4个用于age
,4个用于friendsAges
数组的地址,或者似乎是这样。
我怎样才能编写存储在数组中的实际数据?当我的类有其他类作为成员时,我也遇到了这个问题,例如Person
有一个Car
或类似的东西。
答案 0 :(得分:1)
对于初学者,在您的类中添加一个将执行文件I / O的方法,然后您可以像这样调用它:
Person joe();
Person sally();
fstream file("filename.dat", ios_base::out | ios_base::binary);
joe.serialize(file, true);//writes itself to the file being passed in
sally.serialize(file, true); //write another class to file after joe
file.close();
然后你可以读取同一个文件来填充类实例:
fstream file("filename.dat", ios_base::in | ios_base::binary);
joe.serialize(file, false); //reads from file and fills in info
sally.serialize(file, false); //reads from file too
file.close();
类中的方法看起来像这样:
Person::serialize(fstream &fs, bool bWrite)
{
int ages_length;
if (bWrite) {
fs.write(&age, sizeof(age));
ages_length = ...; //you need to know how long the friendsAges array is
fs.write(&ages_length, sizeof(ages_length)); //write the length to file
fs.write(&friendsAges[0], sizeof(int)*ages_length); //write the variable-sized array to file
fs.write(&name[0], sizeof(char)*50); //write a string of length 50 to file
}
else {
fs.read(&age, sizeof(age));
fs.read(&ages_length, sizeof(ages_length)); //read length of array from file
//TODO: you will need to malloc some space for *friendsAges here
fs.read(&friendsAges[0], sizeof(int)*ages_length); //read-in the variable length array
fs.read(&name[0], sizeof(char)*50); //this only works if string length is always fixed at 50
}
}