short fread(), but no ferror/feof

Peter Astrand
Mon Dec 13 19:55:00 GMT 2004

Dave Korn wrote:

>  The fix and the problem Peter is seeing are orthogonal.
>  The fix referred to above fixes this problem:
>"Hence, one can see that fread() in unbuffered mode always returns the
>specified count instead of the number of elements actually read."
>  That is why, as Peter has observed, fread() returns the number of
>actually read.  Without the patch, it would have been returning the entire
>number requested, which would have been even wronger.

Ah, thanks for clarifying this.

>  However Peter's problem is that when fread() does a partial read, it doesn't
>set either the EOF mark or the error indication on the file stream.  A strict
>reading of the fread() specification suggests that it should have set one of

IMO, there's no room for intepretation in this situation: As I stated
in my original post, IEEE Std 1003.1 is very clear:

"fread() shall return the number of elements successfully read which is
less than nitems only if a read error or end-of-file is encountered."

>OTOH, there isn't actually any error or EOF here.  It could possibly
>be argued from the specified behaviour of read() and pipes that the
>error mark should be set and that errno should be EAGAIN.  It may well
>be in practice that errno does indeed have the value EAGAIN but
>fread() can't return -1 because otherwise the application wouldn't
>know how much data it _had_ read.

I've discussed this issue with some local gurus, and the consensus is that
fread() should do as many read() calls as it takes. This is what glibc
does, for example (if I understand the source correctly). Basically,
fread() means "read everything". It's just plain wrong to return a partial
result, unless EOF or an error occured.

>  Of course, Peter can always detect when this situation has
>occurred, precisely because fread() returns a value that, while >= 0,
>is < the number of elements requested, and when feof() and ferror()
>both return zero, his code could deduce that it's a short read from a
>pipe and try again.

If you can convince the Python developers to add these checks to the
already-complicated fread() invocation in fileobject.c, I will stop
complaining... But fread() shouldn't behave like that.

(Please CC me on replies.)

/Peter Åstrand <>

More information about the Newlib mailing list