I have this code
#include <stdio.h>
int main(void)
{
char c ;
while((c = getchar()) != EOF)
printf("the value in int is %dn",c);
}
Does the getchar function block if there is nothing in stdin , and when something appears the system raise a interrupt and then the process continues?
thanks
4
In fact getchar
asks the underlying IO system for one character. Neither more nor less.
And the underlying IO has different possible behaviours:
- when reading from a file all the data is immediately available, so the underlying system immediately returns one character of (still immediately) returns the integer value
EOF
when the end of file has been reached - when reading from a simple character stream like a pipe, a socket or a terminal in character mode, it blocks if nothing is available, returns a character if one is available, and returns
EOF
if the stream has been closed (or if the socket has been shut down) - when reading from a terminal in line mode, it blocks until a full line has been entered: either a newline character or a special character signaling an end of file, CtrlD on a Unix-like system or CtrlZ on Windows. Then each call to
getchar()
returns the characters from the line, one at a time.
In any case, a read error causes an immediate return with an EOF
integer value.
BTW, the EOF
constant is guaranteed to be distinct from any char
or unsigned char
value. That is the reason why getchar
is declared to return an int
and why while ((char c=getchar()) != EOF) ...
gives an infinite loop…