Backup configuration files
I need to be able to store configuration files on machines that gets disconnected by plugging off the electricity ;), I'm using basic WinApi to store configuration data (WriteFile), this works unless the machine is plugged off ;), sometimes file isn't saved at all.
I was thinking of 2 solutions:
1) Transactional NTFS API (eg. CreateFileTransacted() ), but this thing works only on Vista and NTFS has to be present and I can't use it in most cases
2) To create a backup copy of configuration file in %APPDATA% directory, say 20 backup copies and restore them on application startup when damaged configuration file is detected
If you know of any other solution to my problem (the main problem is turning off the machine by plugging it out), plea开发者_运维知识库se let me know. Thank you.
You don't really need 20 backup copies. You only need 1 - the last copy. Now, if your client actually asks for a basic versioning system for config files that is another story. But just to have a good config file you only need 1 backup.
Now, here's what I used to do for my embedded projects:
Calculate a hash of the config file and store it in the file. The easiest is to append it to the end of file as a comment. I used to use crc32 for this but these days I would use SHA1. This can even be done automatically by a config-uploader tool just prior to transmitting/storing the config file.
When opening the config file, extract the hash and compare it with the value calculated from the file (obviously calculated after the hash is removed from the file). If the hash is not there then the file is incomplete. If the hash is not the same then the file is corrupted. In either case use the older file.
Now that a valid & correct config file is verified it can replace the older config file. Use the OS's rename operation for this. It is usually atomic on most modern filesystems so a failed rename will not clobber up the old file.
This is the most robust system I've used in my years of experience. It's basically what bittorrent does.
精彩评论