Fixed error checking for fgets().

The correct way to check for error is to inspect either errno or
ferror(). Before we tried to rely on breaking out of the loop using
feof(), but this is incorrect for directories, which can be opened,
but will never return feof() == true, nor a successful read.

Fixes issue 2451. The original issue is only in one place, but error
checking was improved in many places.