Close file properly on error
Merge pull request #2210 from asmaloney/fclose_file

Close file properly on error