reading k&r(c book) and confusing 1st chapter code
#include <stdio.h>
/* copy input to output; 2nd version*/
main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
this is very confusing... since you never escape the while loop. I've learned that EOF is -开发者_JS百科1. i type -1 but it just reprints it. It's a never ending loop. Over time did the library get changed and differs from what the book intended it to be? when i say library i mean the putchar()/getchar() that's in the library... sorry.
How EOF(end of file ) works?
EOF is simply a macro designating a negative value. It doesn't have to be -1. You can signal end-of-file from the command line with a control character, usually a combination of ctrl+z for Windows systems or ctrl+d for POSIX systems.
when you write '-1', you do not write the VALUE -1, but the character string { '-', '1' }
take a look here.
EOF
is not a character
This is important. Remember it.
When you try to get a character, several things may happen. The usual is to effectively read a character: your program receives that character and goes on its way ...
int ch = getchar();
but, what happens is the disk crashes? or there's a bad sector just at that point? or the network goes down? or there is no more data?
Well, then there must be a way to differentiate these conditions from plain characters. The way chosen by C
is to return a value that can NEVER be interpreted as a real character. That value is EOF
, which is a negative value (all real characters are returned with their value converted to unsigned char
even if your implementation uses signed char
for char
). That is also why it is very important to use int
for characters (not char
as would be expected).
So EOF
means that it was impossible to read a character. You can try to figure out why (network down? bad sector? end of file? ...) or simply assume it was end-of-file and go from there.
So, in
while ((c = getchar()) != EOF)
there are two things: an assignment and a comparison
c = getchar()
will put a value of 0 or more in c for real characters or EOF
if there's an error, therefore
while ((c = getchar()) != EOF)
means "while there is no error getting characters into variable c
"
Important thing to remember:
EOF
is not a character. Define characters with int
.
After entering text, hit the Enter key for a new line. Then hold down Ctrl and press the letter D.
I'm working on the same book. I think you should be able to just hit Ctrl+D to exit, but I had to hit Enter first (I think there is something wrong with my shell).
That's in the chapter text, by the way.
精彩评论