writeFile: close the file on error