You did not show us the most important code part: The definition of your
Node
class.
This indicates that
Node.data
is of type
Person
:
file.write((char*)&root->data,sizeof(Person));
When the
Person
class contains any members that are pointers to allocated memory, writing and reading the way you are doing it will not work.
If it looks for example like
struct Person
{
int id;
char name[MAX_NAME_LEN];
};
all should be fine. Then do what
OriginalGriff suggested.
But if it looks for example like
struct Person
{
int id;
std::string name;
};
you have to write the content of the
name
member. Your code would only write the memory address (32 or 64 bit value). Reading that later from file will then point to invalid memory.
In the case of strings you can write the length of the string first followed by the content:
file.write((char*)&root->data.id, sizeof(Node.data.id));
size_t len = root->data.name.length();
file.write((char*)&len, sizeof(len));
file.write(root->data.name.c_str(), len);
When reading you have to do it the same way:
Node *newNode = new Node;
file.read((char*)&newNode->data.id, sizeof(Node.data.id));
size_t len;
file.read((char*)&len, sizeof(len));
char name = new char[len];
file.read(name, len);
newNode->data.name.assign(name, len);
delete [] name;
Alternatively you may also write strings with a NULL terminator. But that requires reading character by character until the NULL byte is read.