This works fine:
Code:
Book test; //Book is my custom class
ifstream inbook("book.dat", ios::in);
ofstream outbook "book.dat", ios::ate);
inbook.read(reinterpret_cast< char* >(&test), sizeof(Book));
while (!inbook.eof()){
if (strcmp(test.getTitle(), title) == 0){
test.setTitle(newTitle);
outbook.seekp(inbook.tellg() - sizeof(Book));
outbook.write(reinterpret_cast< char* >(&test), sizeof(Book));
}
inbook.read(reinterpret_cast< char* >(&test), sizeof(Book));
}
but this doesn't:
Code:
Book test; //Book is my custom class
fstream fbook("book.dat", ios::binary|ios::in|ios::out);
fbook.read(reinterpret_cast< char* >(&test), sizeof(Book));
while (!fbook.eof()){
if (strcmp(test.getTitle(), title) == 0){
test.setTitle(newTitle);
fbook.write(reinterpret_cast< char* >(&test), sizeof(Book));
}
fbook.read(reinterpret_cast< char* >(&test), sizeof(Book));
}
As you can see, the blocks of code are quite similar. The second block either skips over some of the records or corrupts the entire file. I have have since abandoned the use of fstream as it's performance seems to be inconsistent. Sometimes it works beautifully, but most times it doesn't. Even when there is no change in the code, and I have no idea why.