开发者

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 du开发者_StackOverflow社区ring 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.


Flush the file as often as possible, or get a 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜