we started topic of low level functions in c , part of assignment have ask user input. use printf() , scanf() assignment allowed use read(), write(), open(), close(), , lseek().
my question how read input keyboard after printing screen? understand have use read, file descriptor stdin_fileno, how determine size count? how keep track of user inputted? have create char array that?
also if reference reading material or tutorials programming low level functions lot.
continuing earlier comment, there little difference between reading , writing stdin
using read
, write
, using higher level functions fgets
, printf
. primary difference cannot rely on format string provided variadic printf
, , read
, responsible making use of return know how many characters read.
below short example showing basics of reading input stdin
read
, writing information write
(note: there additional checks should add checking number of characters read less size of buffer know if more characters remain read, etc...) can put of prompt , read
function ease repetitive use.
with write
, remember, order write things stdout
is format string. make logical calls write
accomplish formatting desire. while free use stdin_fileno
defines, can use 0 - stdin
, 1 - stdout
, 2 - stderr
:
#include <unistd.h> #define maxc 256 int main (void) { char buf[maxc] = {0}; ssize_t nchr = 0; /* write prompt stdout requesting input */ write (1, "\n enter text : ", sizeof ("\n enter text : ")); /* read maxc characters 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 contents of buf 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 : quick brown fox jumps on lazy dog! text entered: quick brown fox jumps on lazy dog!
Comments
Post a Comment