5

I am logging some data into a .txt file during a program execution. The problem is that sometimes I need to cut the power to the system, but I would still like to save the written data.

Here is the code I use to write on the txt file:

std::ofstream file; // placed inside the header file

file.open("filename.txt"); // placed in the class constructor

file << "data " << std::endl; // repeatedly called inside a loop

The data is flushed during the execution, since I open the file while the program is running and I see the updates. But if I cut the power, the result is an empty file, or only one line written on it. I've also tried to manually flush(), but that didn't work either. The OS is Linux Yocto Poky.

charles
  • 713
  • 1
  • 6
  • 16
  • 1
    Have you tried manually closing and re-opening the file periodically? While `endl` should flush the stream, which should make it send its content to the underlying file, I'm not sure if it makes it actually *save* the file. – KABoissonneault Jun 27 '16 at 13:58
  • Where on disk are you storing the file? Beware that some filesystems, such as `/tmp`, are cleared on reboot. – Steve Lorimer Jun 27 '16 at 14:00
  • maybe [fsync](http://pubs.opengroup.org/onlinepubs/7908799/xsh/fsync.html) can help? – Dimitri Podborski Jun 27 '16 at 14:01
  • [file.fflush](http://en.cppreference.com/w/cpp/io/basic_ostream/flush) *should* give you the behaviour you are looking for. – Steve Lorimer Jun 27 '16 at 14:01
  • @KABoissonneault yes, I tried. And the file is updated with the latest data every time I open it. The problem is only after the power loss – charles Jun 27 '16 at 14:07
  • Are you doing any signal handling? Are you using a UPS? – pacmaninbw Jun 27 '16 at 14:07
  • @SteveLorimer I am storing the files at the path /logs, that is an existing folder. Does fflush work for ofstream? – charles Jun 27 '16 at 14:08
  • @incBrain Does fsync work for ofstream? – charles Jun 27 '16 at 14:08
  • @pacmaninbw nothing of that. – charles Jun 27 '16 at 14:08
  • 6
    The problem is that the OS also needs to commit the file to disk. Typically, the file is cached in memory for performance reasons. You need a solution that allows you to tell the OS to flush as well. – MicroVirus Jun 27 '16 at 14:09
  • @charles seems like you need a file descriptor for this and referring to [this](http://stackoverflow.com/questions/11558447/retrieving-file-descriptor-from-a-stdfstream) there is no easy way to do it. But maybe you can try to use c-like file writing to figure out if fsync works or not. – Dimitri Podborski Jun 27 '16 at 14:25
  • @MicroVirus any hint? – charles Jun 27 '16 at 18:43
  • 1
    @charles Not very familiar with that part of Linux myself, but this SO answer seems to be what you want: http://stackoverflow.com/questions/13358431/force-write-of-a-file-to-disk – MicroVirus Jun 27 '16 at 18:45

0 Answers0