fgets() returns NULL at EOF??

karl at haddock karl at haddock
Tue Sep 9 06:36:00 AEST 1986


sun!guy (Guy Harris) writes:
>[haddock!karl writes:]
>>Better yet, return the number of characters read (so 0 on failure).

>Better still, return the number of characters read, or EOF;

One could argue that zero is the number of chars read, and that there is no
failure return as such (cf. fread()).  But see below.

>1) this is what "fputs" does

The successful result of fputs/puts is not mentioned in my manual; all one
can conclude is that it differs from the failure result (EOF).  X3J11 says
that the successful result is zero.

>and 2) this encourages you to distinguish between EOF and error.

Are you suggesting that the result should be EOF if end-of-file was reached,
but 0 if a read error occurred?  This is workable for gets()/puts() (except
for fputs() of an empty string), but not (e.g.) scanf(), and is probably a
bad idea in general.

My revised opinion: functions other than system calls should return NULL for
an out-of-band pointer, EOF for an OOB character, or ERROR (which should be
defined someplace) for an OOB int.  ERROR and EOF are logically different,
even if they have the same value.  Physical end-of-file, read-error, and a
legitimate result of -1 can (and should) be distinguished with feof, ferror,
and/or errno.

The ngets() function (if it gets written) should return ERROR on failure.
It can return zero only if passed a zero-length buffer.  Similarly, nputs()
should return the number of characters written, or ERROR.  (This one could
be called "puts", except that on an implementation that uses zero for puts()
success it may break programs that depend on this.)

>distinguish between EOF and error, something that several UNIX utilities,
>to their everlasting shame, do not do.

Programs should always check for failure returns, and distinguish the types
of failure when it matters (as it usually does when end-of-file is one type).
But that's a more general problem, and although there are some fairly nice
ways to solve it, they would break a lot of existing code.

Karl W. Z. Heuer (ima!haddock!karl; karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list