use ferror() instead of (incorrectly) errno to catch stdio error