The safer way to do this sort of thing is to write to a new file and then rename over the file you want to replace. This is what you do when handling mbox files for instance.
The rename is an atomic operation. It's guaranteed to succeed completely or not at all (on Unix-like boxes), so you can never lose data as a result of a power failure.
This is a similar trick to perl -i, but I think that does a rename of the original file and then writes back into the original file, which still leaves open the case that you could have bad (partially written) data in the original file on power failure.