Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!panda!talcott!harvard!cmcl2!seismo!vrdxhq!rlgvax!hadron!jsdy From: jsdy@hadron.UUCP (Joseph S. D. Yao) Newsgroups: net.lang.c Subject: Re: fgets Message-ID: <372@hadron.UUCP> Date: Tue, 15-Apr-86 17:52:25 EST Article-I.D.: hadron.372 Posted: Tue Apr 15 17:52:25 1986 Date-Received: Sat, 19-Apr-86 03:19:16 EST References: <2476@brl-smoke.ARPA> <2524@utcsri.UUCP> Reply-To: jsdy@hadron.UUCP (Joseph S. D. Yao) Organization: Hadron, Inc., Fairfax, VA Lines: 30 Summary: Check return values. That's what they're for! In article <2524@utcsri.UUCP> greg@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@seismo.{CSS.GOV,ARPA,UUCP}