fgets() returns NULL at EOF??
Guy Harris
guy at sun.uucp
Fri Aug 22 18:44:07 AEST 1986
> Why is it that fgets() returns NULL when it reaches end of file,
> whereas all the other standard i/o functions seem to return EOF
> at that point?
Because "fgets" returns a value of type "char *" while most of the other
functions and macros return a value of type "int". EOF is not a valid value
of type "char *", so "fgets" can't return EOF. NULL is a valid value of
type "char *", and doesn't refer to any object, so it's the proper choice
for an "out-of-band" value for "fgets" to return on error.
Now, you can ask "why does 'fgets' return a value of type 'char *'?" at
this point. It returns a pointer to the buffer that it just filled in;
obviously *somebody* found this useful, although I don't find it so. If
"fgets" didn't return that pointer, it could have been defined as returning
a value of type "int" instead, and that value would have been 0 on success
and EOF on failure. It's too late to change it, though.
BTW: "fgets()" returns NULL on end-of-file OR error; don't write code that
assumes that "fgets()" returning NULL means that the end of the file was
found, use "ferror" or "feof" to disambiguate these cases.
--
Guy Harris
{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
guy at sun.com (or guy at sun.arpa)
More information about the Comp.lang.c
mailing list