Loss of data if there is a power outage

16 Feb 2012

I have a question about the code below:

FILE *fp = fopen("/local/filename.txt", "w");
while (on) {
    wait(1);
    fprintf(fp, "hi\n");
}
fclose(fp);

This code works like it should. But suppose there is a power outage while the while-loop was still running. This means the file isn't properly closed. If I check the file afterwards, it's empty.

What's the right way to overcome the loss of data if there is a power outage while the file was still open? I already tried carriage return and fflush, but without succes.

16 Feb 2012

IMO closing after each fprintf and reopen with append mode should do it