I have trouble understanding getchar()
and EOF
.
I was trying to run this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char c;
int a = 0; //no. of characters
while (1) {
c = getchar();
if (c == EOF) {
// printf("%i",c);
break;
}
putchar(c);
a;
}
printf("%i", a);
int b;
while ((b = getchar()) != EOF) {
putchar(b);
}
printf("here"); // to check wether the code written after the loop is executed
}
I terminated the first loop by pressing Ctrl-D twice, I found many posts explaining the reason for this. But whenever I try to call the getchar()
function after the first loop it keeps returning EOF
, even though that would have been already read by the last call in the first loop.
Code editor - VSCode
OS - macOS
CodePudding user response:
You must define c
as an int
to accommodate for the full range of possible return values from getchar()
, namely all values of type unsigned char
and the special negative value EOF
(usually defined as (-1)
).
On most unix systems, when Ctrl-D is typed in the terminal in canonical mode, whatever input has been buffered by the terminal is sent to the process. In your case, it causes the input to be echoed. If there is no such input pending, the terminal sends zero bytes to the process, which is interpreted by the OS as the end of file. Hitting Ctrl-D twice in a row, or more precisely at the beginning of a read request, does not enter an EOF
byte, it signals the end of file to the reading process, hence any further attempt at reading from the stream will return EOF
immediately without requesting more user input from the terminal.