We just started the topic of low level functions in C and for a part of this assignment we have to ask for user input. Normally I would use printf() and scanf() however for this assignment we are only allowed to use read(), write(), open(), close(), and lseek().
My question is how would you read input from the keyboard after printing to the screen? I understand that I would have to use read, the file descriptor would be STDIN_FILENO, however how would I determine the size count? Also how would I keep track of what the user inputted? Would I have to create an char array just for that?
Also if anyone could reference some good reading material or tutorials for programming with low level functions that would help a lot.
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!