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?

3
  • have a look here stackoverflow.com/questions/9610064/read-stdin-in-c Commented Jan 31, 2013 at 21:57
  • Why don't you want to use scanf? Commented Jan 31, 2013 at 21:59
  • @lxop Probably because it's not always appropriate. (In fact, it does what we want it to do in least cases.) Commented Jan 31, 2013 at 22:01

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

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);
  }
}

2 Comments

Be careful, this will wait until the user types 100 characters before read(2) returns.
No, it doesn't, it also returns after \n

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.