#include <stdio.h>
int main()
{
int c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
return 0;
}
The problem is distinguishing the end of input from valid data. The solution is that getchar returns a distinctive value when there is no more input, a value that cannot be confused with any real character. This value is called EOF, for ``end of file''. We must declare c to be a type big enough to hold any value that getchar returns. We can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we use int.
From 'The C Programming Language' book. I have three questions.
Firstly, why do I get the output ^\Quit (core dumped)
when I press the keys ctrl
and 4
simultaneously while the above program runs? I'm using a GNU/Linux machine.
Secondly, I wrote a program like this :
#include <stdio.h>
int main()
{
printf("The part before EOF\n");
putchar(EOF);
printf("The part after EOF\n");
}
Then compiled this as 'eof.out' and changed int c = getchar();
in the program from the book into char c = getchar();
, saved it and then compiler the program as 'copy.out'.
When I run the command ./eof.out | ./copy.out
in the terminal the output I get is :
The part before EOF
Meaning the program 'copy.out' worked correctly since it didn't print the second printf but the passage above from the book indicates that there should've been some kind of failure since I changed the int
into char
so what happened?
Thirdly, when I change the char c = getchar();
into double c = getchar();
and run the command ./eof.out | ./copy.out
the output I get is :
The part before EOF
�The part after EOF
Why didn't putchar(EOF);
stop copy.out ? Doesn't a double
have more bytes than both int
and char
? what is happening?