I have a struct similar to the usually used student struct and I am storing multiple records in a file. I want to be able to update the fields inside the file but I am not sure which way is the best.
Load all records in memory,make changes and then just rewrite the file with the changes?
Or make a tmp file, find the data to update copy all the data to the tmp file delete the old file and rename the tmp to the original name?
Any other opinions are welcome!
Thanks!
The first was risks file corruption if something goes wrong with the write.
The second is safest but involves two copies of the data on disk. It also requires more file permissions (delete the file, create a new one, rename, etc). BTW, on systems that support it, you probably want to let the rename operation delete the original file for you, without the separate delete step.
Both methods are impractical if the file is very large. In that case you probably need to update the data in place. Dealing with possible corruption is more complicated–perhaps maintaining a journal.