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()
?
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.
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.
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.
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. */
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() .... }
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