Which is the best way to update a record of a file in c?

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!

Answers


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.


You could memory map the file. The way to do it depends on your architecture but once the file is mapped you can update it just like any other structure only the backing store of the update is a file.


Need Your Help

Change visibility being lost in RTC source control

rtc

When i create a new stream in RTC source control I take a snapshot of the current stream and create a new stream from this snapshot.

Reading programs gives values of 0

java arrays

so whats going on is that im trying to read this PlayerData.txt file: