atomic file saves

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I have an embedded system that will save configuration files based on  
user input.  This device will be used in areas that have uncertain  
power, and a battery backup is not a realistic option.

It is not critical that the user's latest changes be saved, but it is  
critical that the system have a valid configuration file, so I want to  
minimize the chances of having a corrupt config file.

I've come up with this:

        $oldConfFile = $confFile . ".bak";
        $newConfFile = $confFile . ".new";
             $fp = fopen($newConfFile, "w");
// FIXME error message here
             if ($fp == false ) return array();
             fputs($fp, $newConfig);

which is about as atomic as I can think of....  And I can do some  
checking on boot and (possibly) copy either the .bak or the .new file  
over to the config file if it is valid and the main config file is not.

Can anyone offer any comments or suggestions for making this more robust?

Re: atomic file saves

Quoted text here. Click to load it

if (!$fp = fopen($newConfFile, 'w')) {
    return array();
if (fwrite($fp, $newConfig) === FALSE) {
      return array();
//ofc if you have rights to rename files

or / and you can use try{
    ... your code...
}catch(Exception e){
    return array();

Ikciu  |  gg: 718845  |  www:

2be || !2be $this => mysql_query();  

Site Timeline