EOF considered harmful

Andrew Koenig ark at alice.UUCP
Tue Oct 24 06:39:40 AEST 1989


In article <266 at m1.cs.man.ac.uk>, ian at r6.uucp (Ian Cottam) writes:

> Some observations on the little program below (following some recent
> discussions in this group):
> 
> #include <stdio.h>

> int
> main()
> {
> 	char ch;
> 	while ( ! feof(stdin) ) {
> 		ch= getchar();
> 		putchar(ch);
> 	}
> 	return 0;
> }

[several reasons that this program is a better way
 of testing for end of file than  ((ch=getchar()) != EOF),
 ending in the following:]

> 5) Although, to my mind, the above is a compelling argument to abandon the
>    explicit test for EOF, everyone reading this newsgroup (except me of
>    course :-) ) will ignore it!


The trouble, of course, is that this program doesn't work!

The feof() test determines whether a call to getc() has already returned
EOF, not whether the next call to getc() will.  Thus the last time
through the loop, the feof() test will return `false,' the getchar()
call will return EOF, and the call to putchar() will write out a
single extra character whose value is the truncation of EOF.


I agree that the above is a compelling argument, but I suspect we
may not have quite the same view of its direction.
-- 
				--Andrew Koenig
				  ark at europa.att.com



More information about the Comp.lang.c mailing list