Close file only if opened successfully