safer writeToFile (via .tmp + rename)