I have a class called Person
Then I have an array of Person's called db[100]. How do I write the entire array to a binary file, and then read it back in?
I'm currently using to write: sFile.write((char *) db, (sizeof(Person) * 100));
And to read: theFile.read((char *) db, (sizeof(Person) * 100));
It's writing stuff to the file and it's also reading stuff back in but if I try to display the list of Person's after reading it back in, it only shows up to Person 25 and then complete garbage after that.
No, it is because he is trying to dump a class to file.
Google around "C++ serialization" for more help.
Specifically, your class should know how to read and write itself from and to file. I would make a method that does that. C++ provides you with the iostream operator overloads for that this very purpose:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Person
{
...
friend ostream& operator << ( ostream&, const Person& );
};
ostream& operator << ( ostream& outs, const Person& person )
{
// This method presumes a textual file. See the notes that follow.
outs << "Person\n";
outs << person.surname << "\n";
outs << person.givenname << "\n";
outs << person.age << "\n";
outs << endl;
return outs;
}
As in this snippit, I recommend you stay away from binary files for schoolwork simply because they are more grief to handle than you think. (Unless you are required to manipulate a binary file.) The above would work with a file like:
Smith
Will
41
Andrews
Julie
74
Cusack
Sinéad
61
In order to write such a file, simply use a loop:
1 2
for (unsigned n = 0; n < 100; n++)
sFile << people[ n ];
Likewise, to read such a file, use a loop. Here it is using a std::vector instead of an array:
1 2 3 4
vector <Person> people;
Person person;
while (sFile >> person)
people.push_back( person );