How does this code work from the "C programming language"?

I am reading The C Programming Language (2nd ed.) And at the beginning, it has examples like this:

while((c = getchar()) != EOF)
    if(c == '\n'){
        ++n1;

      

I can see how this would work when reading from a file, and I understand this syntax ... But this is just reading from the console - how does one signal end up with a file when typing characters from the console? I'm using Windows XP ... MinGW compiler ... Anyway, was this book written for earlier systems with the EOF button or something else?

Update

Well I have another question related only to how the end of file works under Windows.

If I am simple while(getchar()!=EOF);

, then I can just type characters until I signal EOF through ^ Z. But, I have to write a newline, then press ^ Z, then another newline ... Why should it be in on a separate line?

+1


a source to share


4 answers


Windows uses Ctrl-Z for EOF and UNIX uses Ctrl-D. See http://bytes.com/groups/c/217873-eof-windows and a great selection of books. :)



+7


a source


^ Z - EOF.



+4


a source


The correct answer has already been given, but it is typical to use file redirection to standard output:

program.exe < samplefile.txt

      

samplefile.txt

"writes" to the standard version and program.exe

reads this from the standard until EOF is reached.

+3


a source


As for your question about ^ Z, the reason is that it behaves like this, because it is not a character, it is a signal from the operating system to the C input system. So it relies heavily on the interaction between the OS and the C input system buffering What a fancy way of saying this is how things work, for Windows and for your particular C implementation.

+1


a source







All Articles