Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from stdin

Tags:

c

unix

stdin

What are the possible ways for reading user input using read() system call in Unix. How can we read from stdin byte by byte using read()?

like image 944
Bunny Bunny Avatar asked Apr 08 '13 15:04

Bunny Bunny


People also ask

What does it mean to read from stdin?

Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java. Below, is an example of how STDIN could be used in Perl.

What is the use of stdin in C?

The stdin is the short form of the “standard input”, in C programming the term “stdin” is used for the inputs which are taken from the keyboard either by the user or from a file. The “stdin” is also known as the pointer because the developers access the data from the users or files and can perform an action on them.

Does scanf read from stdin?

Description. The scanf() function reads data from the standard input stream stdin into the locations given by each entry in argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format-string.


2 Answers

You can do something like this to read 10 bytes:

char buffer[10]; read(STDIN_FILENO, buffer, 10); 

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch; while(read(STDIN_FILENO, &ch, 1) > 0) {  //do stuff } 

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name        0        Standard input (stdin)        1        Standard output (stdout)        2        Standard error (stderr) 

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define' /usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */ 

Notice the comment /* Standard input. */

like image 179
Johnny Mnemonic Avatar answered Sep 22 '22 23:09

Johnny Mnemonic


From the man read:

#include <unistd.h> ssize_t read(int fd, void *buf, size_t count); 

Input parameters:

  • int fd file descriptor is an integer and not a file pointer. The file descriptor for stdin is 0

  • void *buf pointer to buffer to store characters read by the read function

  • size_t count maximum number of characters to read

So you can read character by character with the following code:

char buf[1];  while(read(0, buf, sizeof(buf))>0) {    // read() here read from stdin charachter by character    // the buf[0] contains the character got by read()    .... } 
like image 27
MOHAMED Avatar answered Sep 22 '22 23:09

MOHAMED