2

I saved some data in a binary file using C++. Two minutes after the data was saved, the power to the computer was suddenly cut off. When I restarted the computer the data was corrupted. When I read the binary file, all of the values were 0, which is certainly not what I had written to the file.

Is it possible that the sudden computer power down corrupted the data in my files? Or is it so that this cannot be the case because data once written and saved to disk does not corrupt, even in the event of sudden power down.? If it is the latter, then I will have to start a detailed investigation of the issue, but I really don't suspect anything else could have gone wrong. The program is very simple and has been in use for 2 years, and this is the first time I am seeing any data corruption of files written using the program.

P.S. The file had indeed finished saving. The program that saved the file manages file i/o correctly - it closes the file after it is finished writing it. Also, the program was not even running when the power down happened. This happened On Windows 8.1.

1 Answer 1

2

Simplified, when your create a file of data the operating system must do these three things:

  1. Allocate the blocks necessary to contain the data.
  2. Write zeros into those blocks or otherwise cause zeroes to be presented if you attempt to read them.
  3. Write your data to the allocated blocks.

Step 2 is a requirement because of system security. The allocated blocks might have previously contained someone else's data and it would be a security breach for the system to allow you to read their old data. So you get zeroes instead. If the power was cut between steps 2 and 3 you would see zeroes instead of your data.

Depending on the underlying operating system and filesystem, unless you explicitly sync your data to disk within your program, step 3 could occur an arbitrarily long time after step 2.

On POSIX compliant systems, call fsync() to ensure your data has reached permanent storage.

4
  • Is this also the case for Windows? This happened on Windows 8.1. Commented Sep 14, 2015 at 17:32
  • 1
    Those steps are necessary for any multiuser OS, but the time you'll have to wait for your data to hit disk varies between filesystems. I don't know what Windows and NTFS do specifically, but they certainly buffer disk writes, so I'd expect similar behavior.
    – Kyle Jones
    Commented Sep 14, 2015 at 18:06
  • Is this kind of data corruption possible from a normal restart of the computer? I mean one where I click the restart button as opposed to abruptly killing the power. Commented Sep 14, 2015 at 18:25
  • 1
    In that case the kernel would complete step 3 before initiating a reboot, so no, a normal restart shouldn't cause this problem.
    – Kyle Jones
    Commented Sep 14, 2015 at 18:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .