Continuing from my earlier comment, there is really little difference between reading and writing to stdin
using read
and write
and using higher level functions like fgets
and printf
. The primary difference is you cannot rely on the format string provided by the variadic printf
, and with read
, you are responsible for making use of the return to know how many characters were actually read.
Below is a short example showing the basics of reading input from stdin
with read
and then writing that information back with write
(note: there are additional checks you should add like checking that the number of characters read is less than the size of the buffer to know if more characters remain to be read, etc...) You can always put much of the prompt and read
into a function to ease repetitive use.
With write
, just remember, the order you write things to stdout
is the format string. So simply make logical calls to write
to accomplish the formatting you desire. While you are free to use the STDIN_FILENO
defines, you can also simply use 0 - stdin
, 1 - stdout
and 2 - stderr
:
#include <unistd.h>
#define MAXC 256
int main (void) {
char buf[MAXC] = {0};
ssize_t nchr = 0;
/* write the prompt to stdout requesting input */
write (1, "\n enter text : ", sizeof ("\n enter text : "));
/* read up to MAXC characters from stdin */
if ((nchr = read (0, buf, MAXC)) == -1) {
write (2, "error: read failure.\n", sizeof ("error: read failure.\n"));
return 1;
}
/* test if additional characters remain unread in stdin */
if (nchr == MAXC && buf[nchr - 1] != '\n')
write (2, "warning: additional chars remain unread.\n",
sizeof ("warning: additional chars remain unread.\n"));
/* write the contents of buf to stdout */
write (1, "\n text entered: ", sizeof ("\n text entered: "));
write (1, buf, nchr-1);
write (1, "\n\n", sizeof ("\n\n"));
return 0;
}
Compile
gcc -Wall -Wextra -o bin/read_write_stdin read_write_stdin.c
Output
$ ./bin/read_write_stdin
enter text : The quick brown fox jumps over the lazy dog!
text entered: The quick brown fox jumps over the lazy dog!