• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 227
  • Last Modified:

How to flush a file to disc to guard against data loss

Hi,

I've got a counter in a file that is regularly updated. Unfortunately, if the system is powered off, the counter is a few behind what it should be, and data is getting overwritten when the system starts up again.

What is the linux call to flush the file to disc, for the code below? I've tried fflush(), but it doesnt work with ofstream.

        string countFileName = cfg.getDataDirectory() + "NOISE_COUNTER";
        ofstream of(countFileName.c_str(), ios::out);
        of << ++vm.imgCount_;
      #warning THIS FILE IS NOT BEEN FLUSHED TO DISC - ON POWER FAILURE THE COUNT GOES BACK A FEW STEPS
        of.close();

Best regards,
Shane.
0
Risky101
Asked:
Risky101
  • 3
1 Solution
 
pYraniaCommented:
$ sync
you might want to put it somewhere in your shutdown scripts.
0
 
Risky101Author Commented:
The problem only occurs when the computer is switched off at the wall.

I tried of.fflush(), but it still doesnt work.
0
 
de2ZotjesCommented:
I see you are using c++ so my advice is a bit of, but I imagine that there is an ios equivalent for it.

The open call accepts a flag O_DIRECT to minimize the effects of buffering. It is bad for io-performance (for obvious reasons) but if the amounts of data are small it is quite acceptable

Hmm.. just had a quick look around the net.. maybe there is no O_DIRECT equivalent in ios::stream. Would also make sense, it is a stream interface, buffers will be part of that.

Damn, you might have to recode this bit to talk to a file directly instead of a stream...
0
 
Risky101Author Commented:
It wouldn't be too hard to recode it - I will try that.

Also, function calls like fsync() would work with a file handle too. Thanks, I'll let you know how it goes.
0
 
Risky101Author Commented:
Thanks - this worked.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now