Do this after the error check. Often if there is a error and you try and close the allocated file, you will cause a segfault.