Overwriting an object in a file with another object of same class using c++

193 Views Asked by At

I wrote a code wherein I am saving information into a file for retrieving it later on. There is a task for which i need to overwrite an object in file with new object ( Kinda like updating the saved information). But when I retrieve the information after updating it, the old info is printed. The object was not overwritten. Please verify my error. Here is the piece of code to write into the file:

HeaderInfo rx;   //This is the object which I want to write.
//headers is the pointer to file where all the objects are saved.
headers.read((char*)&rx , sizeof(HeaderInfo)); //First I read the old info from the file
headers.seekp(it->second->getHeaderLocation());  //go back to where the info was read from

//In the lines of code below, I modified the old information.
strcpy(rx.key,new_key.c_str());
rx.headerLocation = headers.tellp();
rx.dataSize = sizeof(HeaderInfo);
rx.freeSpace = 0;
rx.location =   it->second->getLocation();

//Now writing back the updated object to file.
writeEmptyHeader(rx , headers.tellp());

P.S. The pointers from where I read the file and want to write back to are correct. I verified them by printing the pointers. I just don't understand why the new object is not getting saved in file.

//This is the definition of HeaderInfo. It is basically a struct:
struct HeaderInfo{
    char key[MAX_KEY_LEN];
    long location;
    long headerLocation;
    long dataSize;
    long freeSpace;
};

Edited: Here is the writeEmptyHeader function:

void DBManager::writeEmptyHeader(HeaderInfo& r , long fptr){

headers.write((char*)&r , sizeof(HeaderInfo));

}

P.S.: I know the name looks ambiguous. And I realized, it really is. But it just writes the header to file at location fptr. I made this function separately while debugging my code so didn't think much of it. Ignore the name! :P

0

There are 0 best solutions below