protect against cache loss if program is halted mid-write

http://stackoverflow.com/questions/1812115/how-to-safely-write-to-a-file