I'm currently trying to implement a function that deletes a specific struct which is already saved in a binary file. I'm a little confused on how to do it. I have a solution that will work but isn't particularly elegant: I could read the entire file of structs to a vector of structs, delete the old file, delete the struct I want to remove from the vector, then save the vector of structs as a file again. I'm pretty confident this would work but if the file is large it seems like a lengthy and perhaps unnecessary solution. I know how to find the struct I want to delete, and I know how to change the values in it (by overwriting it) but how exactly can I delete it?
This is how I save my struct:
std::fstream binary_file(fileLocation.c_str(), std::ios::out | std::ios::binary | std::ios::app);
binary_file.write(reinterpret_cast<char *>(&myStruct), sizeof(myStruct));
binary_file.close();
each struct has an integer with its unique ID, I use that to find the appropriate struct like so:
myStream.open(fileLocation.c_str(), std::ios::in | std::ios::out | std::ios::binary);
while (!myStream.eof())
{
myStream.read(reinterpret_cast<char*>(&myStruct), sizeof(myStruct));
if (myStruct.ID == given_ID)
{
temp_fstream.seekg(-(sizeof(myStruct), std::ios::cur);
//delete struct
return;
}
}
I'm at a loss at what to do here, is it even possible? I've toyed around with the idea of just flagging the struct as invalid so even though my program will read it it won't use it for anything, but again, seems like a poor idea.
Any suggestions?