Reputation: 2206
I've been reading The C Programming Language by Kernighan and Ritchie and very early own I came across a program that didn't work, even though I copied it directly from the book. Here is a screen cap of the description - https://i.sstatic.net/OjbtJ.png
It gets stuck in an infinite loop because anything I enter is obviously a keyboard entry, and it's checking in against EOF which is clearly not a keyboard entry.
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
Surely an authority book on C like this can't have an error, am I missing something?
Upvotes: 2
Views: 145
Reputation: 30136
You would run it and use ctrl + d
to signal the EOF (end of file) when reading from the command line.
If you were reading a stream of bytes from a file then it would have that in there automatically. However, since you are reading from the command line, one needs to signal the end of file manually by using the key sequence above.
How it actually works
EOF usually represents -1 in (glibc at least) which is why you can't just say while(c) { do work; }
because any non-zero value is true -- hence EOF is true, just like any other positive number character returned by the call to getchar()
. This is why you have to directly check to see if c matches EOF (-1) with the code c != EOF
which appears in the stream when you send the EOF signal with ctrl + d
.
Upvotes: 4