Trouble at EOF

Blair P. Houghton bhoughto at pima.intel.com
Mon Jun 17 10:10:24 AEST 1991


In article <12847 at pucc.Princeton.EDU> EGNILGES at pucc.Princeton.EDU writes:
>According to the description of the standard fgets library function
>(reference 1), you are not guaranteed newline at the end of every
>line...that is, you'll get one at the end of the LAST line (or is
>it the last-1th line, such that the last line is zero length?
>enquiring minds want to know) only if it's there in the file.
>I guess it's the old IBMer in me, who wants the end of a line to
>be the Edge of the World, but this seems a tad bogus, especially
>if one is writing a lexical analyser where such issues are
>important.  Is there a true line reader in C? One that would
>slap on an end of line at the end of the last line if it needed
>it?

As confusing as that was, I think I got it.

Yes, fgets at eof may get a line with no newline.

Hence:

    while ( fgets(s, sizeof s, stream) )
	/* not eof */
	process(s);

    /* reached iff eof */
    if ( strlen(s) != 0 ) {
	/* there's something left to process */
	if ( s[strlen(s) - 1] != '\n' )
	    /* it has no newline */
	    strcat(s,"\n");
	process(s);
    }

But notice also that the size of the gotten string is
limited to the number of chars specified in the second
argument to fgets.  I.e., fgets may also get a line with no
newline when that line is longer than the length you
desire.  If the line is actually longer than that, the
balance will be read on the next call to fgets (possibly
also without a newline).

Why?  Because fgets' responsibility is to fill an array
with bytes, not to alter them.  It should be the
programmer's responsibility to maintain the semantics of
input data.

				--Blair
				  "process("what next?")"



More information about the Comp.lang.c mailing list