Check for errors on close.
Use a temporary file and atomically rename.