so I'm learning C by following the book, 'The C Programming Language 2nd Edition' by Dennis Ritchie and Brian Kernighan. In section 1.5.1 File Copying, the following program is shown:
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar()
while (c != EOF) {
putchar(c);
c = getchar();
}
}
and I had a few questions here.
- Why is the variable
cdeclared as anint? Because it's agetchar()function shouldn't it be of typechar? - What is the difference between
putcharandprintf? - I don't get what is the
EOFmentioned in the condition of thewhileloop
Thanks!
getcharcannot return justcharbecause it needs to return either a character (if the operation succeeded) orEOF(if the operation failed).Therefore
getcharreturns anint. If the operation successfully read a character, it returns the character as anunsigned charvalue. (This is one reason that operations with characters ought to prefer to use theunsigned chartype. Avoid usingchar.) If the operation did not read a character, either because there are no more characters in the input stream or because an error occurred, thengetcharreturnsEOF.EOFhas some negative value, so it is always different from anunsigned charvalue.If you assign the result of
getcharto achar, theintvalue will be converted to achar. In a typical C implementation, there are 257 possible return values fromgetchar—256 character values and oneEOFvalue, but acharhas only 256 possible values. Therefore, the conversion will map at least two different values to the same thing, usuallyEOFand some other character. Then it is impossible to tell those two things apart from thecharvalue. You need to use anintto preserve the originalgetcharreturn value.putcharsends a single character to the standard output stream.printfperforms formatting operations and sends the results to the standard output stream. Even in the simplest case whereprintfis given only a format string with no arguments to be converted, it is still given a string, not a single character.EOFstands for “End Of File,” but it is return bygetcharif either the end of the stream is reached or if an error occurs.