简体   繁体   中英

How to restore data on Power Failure using C++ programming on windows

In my program I am writing a file of my programs states. I am writing the file many times to the file during the program run, because the program changes some variables that that i need to store very frequently.

Now, if , for some reasons my power fails. Then most of the time I loose data in that file.

Please, tell me any mechanism which can protect data even if the power fails. (I have written C++ program on windows).

Thank you

Use a transactional database such as SQL Server. Commit your changes regularly to the database. It is very unlikely that your data will become corrupted when the power fails for the database server, but it's wise to regularly take backups just in case.

尽可能频繁地刷新文件,或者获得UPS ;)

As suggested, you can use a transactional database to track state. If for a variety of reasons you wish to stick with a normal file:

I would suggest using a transaction based data file that is always appended to rather than one that you constantly rewrite. In other words, when you first create the file write the full data set as a starting state. Then for each change your program writes, retain the existing file and only append the change (for example, record that variable B changed to 42) rather than rewriting the entire file. When the file reaches a certain size you'll close it, start a new file with the current full state, and repeat.

Recovery will be slightly more complicated as you'll have to recover the whole state file but you shouldn't lose much if any data (flush often).

SQLite is a good choice if you are currently using one flat file per installation. It is a public domain single-file database designed to be ACID-compliant , including resilience to power failure during data write. There are a variety of C++ APIs for it.

You need to use FlushFileBuffers (win32 API) or POSIX fsync (for POSIX OS) to ensure that the data is written to disk physically. Once you called it you may be sure that the data is persistent. It is like poor-mans D of ACID.

But note this functions is very slow... use with care.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM