Link to home
Start Free TrialLog in
Avatar of Risky101
Risky101Flag for United States of America

asked on

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.
Avatar of pYrania
pYrania

$ sync
you might want to put it somewhere in your shutdown scripts.
Avatar of Risky101

ASKER

The problem only occurs when the computer is switched off at the wall.

I tried of.fflush(), but it still doesnt work.
ASKER CERTIFIED SOLUTION
Avatar of de2Zotjes
de2Zotjes
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Thanks - this worked.