#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Person{
private :
string name;
int age;
public :
Person(string name, int age){
this->name = name;
this->age = age;
}
void show(){
cout << "Name : " + name + "\n" << "Age : " << age << \n####################\n";
}
~Person(){
cout << "object " + name + " deleted\n";
}
};
int main(){
ifstream file("./files/C63.bin", ios::binary | ios::in);
if (!file.is_open()){
cout << "Error opening the file..\n";
} else {
cout << "successfully opened the file..\nThe contents of the binary file are :\n";
Person *p;
while (file.good()){
file.read((char *)p, sizeof(Person));
cout << "hi\n";
p->show();
}
file.close();
}
return 0;
}
At the code line - "file.read((char *)p, sizeof(Person));", segmentation fault occurs. The binary file exists at the specified location with a few person objects. What could have gone wrong?
You've created a pointer to Person, without initialising it. It's just a pointer pointing to God knows where. So when you try to read from the file to it it tries to access invalid memory, that's the segfault.
That's why you got a segfault, but as PaulMcKenzie points out, reading files like this can only read bytes, you can read one byte, or 16 bytes, but you still couldn't construct a Person object by reading just raw data. Let's just say that you had allocated memory for your Person objects, with either malloc or placement new or something, it's only doing a shallow copy. Classes like std::string have a pointer to data, and you'd only be copying pointers to data, but not the data.