Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using read system call after a scanf

Tags:

c

scanf

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:

  1. scanf should place 10 in data
  2. and abcd will still be on the stdin buffer
  3. when read tries to read the stdin (already abcd is there) it should place the abcd into the buf
  4. so printf should print abcd

but it is not happening: printf showing no output

am I missing something here?

like image 720
Deepak Avatar asked Jul 31 '26 14:07

Deepak


1 Answers

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.

like image 181
wallyk Avatar answered Aug 03 '26 03:08

wallyk