I am having a confusion regarding the following code,
#include <stdio.h>
int main()
{
char buf[100] = { '\0' };
int data = 0;
scanf("%d", &data);
read(stdin, buf, 4); //attaching to stdin
printf("buffer is %s\n", buf);
return 1;
}
suppose on runtime I provided with the input 10abcd so as per my understanding following should happen:
scanf should place 10 in dataabcd will still be on the stdin bufferread tries to read the stdin (already abcd is there) it should place the abcd into the bufprintf should print abcdbut it is not happening: printf showing no output
am I missing something here?
First of all read (stdin, ...) should give warnings (if you have them enabled) which you would be wise to heed. read() takes an integer as the first parameter specifying which channel to read from. stdin is of type FILE *.
Even if you changed it to read(0,..., this is not recommended practice. scanf is reading from FILE *stdin which is buffered from file handle 0. read (0, ...) reads directly from the underlying file handle and ignore any characters which were buffered. This will cause strange results unless stdin is set unbuffered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With