Write an array to binary file and read it back in

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.

Any Ideas?
it only shows up to Person 25 and then complete garbage after that.
i think because you're multiply the size by 100.

post your code..
i think because you're multiply the size by 100.
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 );

Hope this helps.
hmmm.. can you guess what type is db? he's trying to cast it as char *
The ostream::write() method takes a char* as its first argument.

Having no other information that what he has given us, we can only presume that db is an array of Person:
    Person db[100];.

Again, I recommend that you stay away from direct arrays, and use a vector or a deque instead:
    deque <Person> db;
@Duoas
i see.. thanks, i'll read about vectors tomorrow. it's already 1 am here. my head going to crack now.

@cartpauj
have you figured it out already? post it here.

Topic archived. No new replies allowed.