0

Im trying to use the read() function to take user input but the only thing I can find in the documentation is regarding reading from files, this is in Linux c language. I also want to use write() do display something to the console.

Does anyone have any idea how this is done?

Ryan Thompson
  • 61
  • 2
  • 4

2 Answers2

1

but the only thing I can find in the documentation is regarding reading from files

Don't worry, the standard input is a file.

char buf[128];
read(STDIN_FILENO, buf, sizeof(buf));

I also want to use write() do display something to the console.

Let me not repeat myself.

const char *s = "Hello World!\n";
write(STDOUT_FILENO, s, strlen(s));
0

This here should give you an impression how to do it (0 is stdin, 1 is stdout)

#include <unistd.h>
#include <string.h>
int main () {
  char buf[100];
  char *msg="you wrote:";
  while (1) {
    int n;
    n=read (0, buf, sizeof(buf));
    write (1, msg, strlen(msg));
    write (1, buf, n);
  }
}
pbhd
  • 4,384
  • 1
  • 20
  • 26