test1.c
#include <stdio.h>
int main(void)
{
int ch;
FILE *fp;
fp = fopen("file1.txt", "w");
while ((ch = fgetc(stdin)) != EOF)
{
fputc(ch, fp);
}
printf("\n");
return 0;
}
test2.c
#include <stdio.h>
int main(void)
{
int ch;
while ((ch = fgetc(stdin)) != EOF)
{
fputc(ch, stdout);
}
printf("\n");
return 0;
}
The difference between the two files is the expression inside the while loop(one outputs to a file while another outputs to stdout).
The behavior of two program confuses me.
test1.c: I should type twice ctrl+D to complete my input. For example I type "123 ctrl+D ctrl+D", the first fgetc return and while loop run and finally ch can get EOF to run out of while loop.
test2.c: The fgetc return when I type ctrl+D just once. For example "123 ctrl+D", The fgetc return and while loop run but ch can not get EOF so it's blocked by the last fgetc.
Why?
My environment:
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Linux ubuntu 4.15.0-76-generic #86-Ubuntu SMP x86_64 GNU/Linux