[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: ctrl+d (EOF) and the standard input.
moshec@netvision.net.il (Moshe Cohen) wrote:
|>2)I tried to run the following program:
|>
|>#include <stdio.h>
|>
|>int main(void)
|>{
|> int input_char, num_of_EOFs = 0;
|>
|> do
|> {
|> if ((input_char = getchar()) == EOF)
|> printf("%d EOF signs were detected so far\n", ++num_of_EOFs);
|> } while (input_char != 'q');
|> exit(0);
|>}
|>
|>The results were that if I type ctrl+d after a return key, it
|>immediately detects the EOF sign. But otherwise I had to press ctrl+d
|>twice to make the program understands that I want it to detect an EOF.
|>Why is that ?
|>
|
|Amos Shapira already sent you an elaborate answer.
|I just wanted to add that the above code segment for counting EOFs will
|never work because a file can be ended only once.
Hmmmm, were is that switch?.... Ah! Here it is:
BZZZZT - wrong answer :-)
|Once the EOF is detected, all subsequent getchar()'s will also
|return EOF. EOF is not another name for the ^D character. Rather,
|it is a state of the input stream. There is no sense in counting
|EOFs.
Try the code first. Your answer is wrong:
|birnam| ./x
adsad
1 EOF signs were detected so far
ajkfakfjsdfk
2 EOF signs were detected so far
lafjkdlksjfsdklf
3 EOF signs were detected so far
4 EOF signs were detected so far
5 EOF signs were detected so far
6 EOF signs were detected so far
7 EOF signs were detected so far
8 EOF signs were detected so far
9 EOF signs were detected so far
(was eventually terminated with an interrupt (^C)). This program will
loop forever upon hitting a "disk file" end-of-file, or devices like
/dev/null.
If you read my answer entirely, and have a vague idea how you would
expect stdio to use this interface, then you shouldn't have come up
with this answer.
Cheers,
--Amos
--Amos Shapira | "Of course Australia was marked for
133 Shlomo Ben-Yosef st. | glory, for its people had been chosen
Jerusalem 93 805 | by the finest judges in England."
ISRAEL amos@dsi.co.il | -- Anonymous
References: