Reputation:
The following output seems to suggest that when read () is called after a getchar() it clears all the stdin. Let's say that I typed "Hello\n" :
char buff;
int c;
c=getchar();
printf("%c\n",c); //output H
int res;
res=read(0,&buff,1); //no output, it prompts !!
printf("%c\n",buff);
However if I invert the functions the behaviour is different. Let's say I type "Hello\n" again :
char buff;
int res;
res=read(0,&buff,1);
printf("%c\n",buff); output H
int c;
c=getchar();
printf("%c\n",c); output e
Could someone explain what's going on here ? I'm using Mac OS
Upvotes: 1
Views: 695
Reputation: 12698
The following output seems to suggest that when read () is called after a getchar() it clears all the stdin. Let's say that I typed "Hello\n" :
Nope. You are intermixing calls to getchar() (a high level routine that is buffer based) and read() (a low level system call that is the one that reads everything)
This is what is happening:
If you want to intermix calls, use fread() (which knows and uses the stdio buffer as getchar()) after getchar(), but not read().
When you invert the sequence, the read() call gives you all that has been read (no buffering in read()). when you do the getchar() a second read() is made (as the buffer is empty) to fill the buffer. So you get all data (you should have got it in the first case, if you had done more getchar()s after the first read, but in the wrong order, of course)
Upvotes: 2
Reputation: 142
if you still enter Hello\n with this code you will see :
1st getchar reads 1 char from stdin where Hello\n is buffered so it remain ello\n
2nd you ask read (which is a blocking function) to read from stdin so it wait for you to input some text (lets say you type "a\n") it will give you back the 'a'
then the last getchar will read from the buffered entry in 1st step output :
H
a
a
e
int main() {
char buff;
int c;
c=getchar();
printf("%c\n",c); //output 'H'
int res;
res=read(0,&buff,1); //it prompts the lettre you just entered here 'a'
printf("%c\n",buff);
c=getchar();
printf("%c\n",c); //output the rest of the buffered stdin 'e'
return 0;
}
Upvotes: 0