I am attempting to read and write a vector of structs into a file. Iterating through each struct, first I write the size of the following struct, then I write the structure. I encounter crashes when reading the file.
Structure:
struct Book {
string author;
string title;
string isbn;
int copies;
Status status;
};
Loading from file:
void load_books(vector<Book> *books) {
ifstream readFile;
int read_size;
Book temp;
readFile.open(BOOK_DB_FILE.c_str(), ios::in | ios::binary) ;
while(readFile.read(reinterpret_cast<char*> (&read_size), sizeof(read_size))) {
cout << read_size << endl;
if (!readFile.read(reinterpret_cast<char*> (&temp), read_size)) {
cout << "Failed to read library.dat!" << endl;
}
cout << "Attempting to load book..." << endl;
cout << temp.title << ":" << temp.copies << endl;
(*books).push_back(temp);
}
cout << "Loaded books!" << endl;
}
Writing to file:
void save_books(vector<Book> *books) {
ofstream writeFile;
int write_size;
writeFile.open(BOOK_DB_FILE.c_str(), ios::out | ios::binary);
for (int ind = 0 ; ind < (*books).size(); ind++) {
Book book = (*books)[ind];
write_size = sizeof(book);
cout << "Writing book with size: " << write_size << endl;
cout << book.copies << " of " << book.title << " by " << book.author << endl;
writeFile.write(reinterpret_cast<char*>(&write_size), sizeof(write_size));
writeFile.write(reinterpret_cast<char*>(books + ind), write_size);
}
}
Bookis not a POD type, thus it cannot be written to a binary file in the fashion that you're writing it. You cannot writeBookin just a binary blob like that -- it has to be serialized, meaning you must write the data to the file, not the object. (I see this question or variations of it over and over again, especially from students).