In my program I am creating a class instance then writing it to a binary file. I do this several times so I have several instances of this class in my file. Then I want to access them individually, read them back into an instance in the program, change its contents and write it back into its place in the file.
I have most of it working fine, however there's one problem. When I edit the contents of the class and try to write it back to the file in its correct spot by using seekp(offset)
where offset is basically an index number of the record I'm interacting with, it writes it in the correct spot but it's deleting every record before and after it. So say if I've read in the 5th record in the file, changed its contents and write it back after using seekp(offset*sizeof(A))
it writes it back in at the desired location but before it is filled with null data and after it there is nothing (end of file). I tried fiddling with the ios flags to make sure it wasn't truncating it, using reinterpret_cast<char*> instead of (char*), and I just can't figure out what's wrong.
Here's the simplified code:
class A {
private:
char array[10];
public:
void writeToFile(int);
void readFromFile(int);
};
void A::writeToFile(int offset)
{
ofstream outFile("data.bin", ios::out | ios::binary);
outFile.seekp(offset*sizeof(A));
outFile.write((char*)this, sizeof(A));
outFile.close();
}
// readFromFile is the same except ifstream, ios::in, seekg and read are used.
Any help would be appreciated!