C++ Prevent System Exit before save completes

84 Views Asked by At

Im having problems with the auto-save process of my system. Here is how my save works:

  1. Create a file with the exact name and add "~" at the end, f.e. text.txt~ if the system wants to save text.txt
  2. Write the content into text.txt~
  3. Copy the content of text.txt~ to text.txt
  4. Delete text.txt~
  5. Done.

The problem here is, that text.txt gets corrupted if the system gets closed during the 3rd process. Can anyone tell me how to ensure that the file gets saved properly? Is there a method to block termination during a process? Do I have to create a thread for that specific phase or does it get closed as well when the system exits? How exactly would that look like. A code example would be very helpful.

Thank you for your help.

Code for copy process:

1    ifstream f1 (tmp_path,fstream::binary);
2    ofstream f2 (path,fstream::trunc|fstream::binary);
3    f2<<f1.rdbuf();
4    f1.close();
5    f2.close();

Goal: Ensure line 3 always finishes

0

There are 0 best solutions below