ceofgetcharputchar

I'm trying to understand getchar() != EOF


I'm reading The C Programming Language and have understood everything so far. However when I came across the getchar() and putchar(), I failed to understand what is their use, and more specifically, what the following code does.

main()
{
    int c;
    while ((c = getchar()) != EOF)
       putchar(c);
}

I understand the main() function, the declaration of the integer c and the while loop. Yet I'm confused about the condition inside of the while loop. What is the input in this C code, and what is the output.


Solution

  • This code can be written more clearly as:

    main()
    {
        int c;
        while (1) {
            c = getchar();            // Get one character from the input
            if (c == EOF) { break; }  // Exit the loop if we receive EOF ("end of file")
            putchar(c);               // Put the character to the output
        }
    }
    

    The EOF character is received when there is no more input. The name makes more sense in the case where the input is being read from a real file, rather than user input (which is a special case of a file).


    [As an aside, generally the main function should be written as int main(void).]