fgets

Joseph S. D. Yao jsdy at hadron.UUCP
Wed Apr 16 08:52:25 AEST 1986


In article <2524 at utcsri.UUCP> greg at utcsri.UUCP (Gregory Smith) writes:
>I had the following problem with EOF detection:  Suppose that the
>last line in the file is "wombat soup", and this is followed by '\n' and
>EOF, as is the normal case for text files. So my second-to-last call to
>fgets reads "wombat soup\n" and does not set feof(infile). My last call
>to fgets, however, just sets feof(infile) and returns! It didn't write
>anything into the buffer. So the program saw "wombat soup\n" twice.

Good heavens, man.  Do you mean to say they don't teach you to check
your return values?  That's what they're for, after all.  The correct
paradigm is:
	char buf[...];		/* If arg or char*, can't use sizeof */
	extern char *fgets();

	while (fgets(buf, sizeof(buf), file) != (char *) NULL) {
		...
	}
This is why fgets() returns a value: the fact that a non-NULL return
is the value of buf, the usefulness of which was questioned by an
earlier writer, is just to make it something non-NULL.  (If buf is
NULL-valued, you have other problems.)

Once again, apropos another comment in the above note, fgets() is
intended for reading "standard text files," which are strings of
ASCII characters (assumed non-NUL), each "line" of which is termi-
nated by a newline (NL) character.  For anything else, one should
check whether fread() might not be a better routine to use.
-- 

	Joe Yao		hadron!jsdy at seismo.{CSS.GOV,ARPA,UUCP}



More information about the Comp.lang.c mailing list