0

Eventhough there are similar questions like here or here, I have a question about a different case.

By using C/C++, I want to write some bytes to a file. Initially file has data. Simply, I update the content of file : I open, write and close. However, if it fails during write and if we are unable to handle the failure (for example, application crash, interrupt, electricity shutdown etc.), what is guaranteed in output file between the list below? Which situation can happen, which cannot?

  1. File may be empty (Deleted existing values and couldn't write new ones)
  2. File stays locked
  3. File may contain both old values and new values (i.e. first 5 lines are new values, last 5 lines are old values)
  4. File may contain old value.
  5. Anything other that I don't expect?

If you can give me OS independent approaches, I would be glad

Thanks

Community
  • 1
  • 1
Deniz Beker
  • 1,984
  • 1
  • 18
  • 22
  • 2
    What mode are you using to open the output file (write, append, etc.)? – Fred Larson Jan 31 '14 at 19:29
  • I am using write mode. – Deniz Beker Jan 31 '14 at 20:00
  • What is it that you want to achieve? Append data to the file so that either the file remains as it was or is securely updated? – Martin James Jan 31 '14 at 20:18
  • I want to be sure that case 3 never happens. The other cases can be detected and can be taken care of easily. However, if the file contains both old & new values, I will need more control to detect it. – Deniz Beker Jan 31 '14 at 20:23
  • For each Open/Write/Close operation, are you overwriting the entire contents of the old file? If so, how about wrapping your data with some matching meta-data at the beginning and end of the file. Something that would be unique for each Open/Write/Close operation, and that could be verified to match later. If the meta-data didn't match, you know you hit case 3. – David LaPorte Jan 31 '14 at 20:48
  • Thanks David. It is a nice solution. However I cannot touch file content. That's why I question about file write handling on OS. – Deniz Beker Jan 31 '14 at 21:15

1 Answers1

3

Write the new data to a file with the same name, but with a 'tmp' extension. Flush and close the tmp file. Delete the original file. Rename the tmp file to the original file name.

On startup, scan the folder for all files. Delete all tmp files whose name part matches an existing 'source' file, (ie. system was interrupted during the tmp file write). Rename any tmp file whose name part does not match an existing source file, (the tmp file was written, the original file was deleted but the system was interrupted before the rename).

This system depends upon the atomicity of deleting the original file. If it succeeds, you get the new data, if it fails, you get the old data. You should never get bits of each.

Martin James
  • 24,453
  • 3
  • 36
  • 60