简体   繁体   English

使用read()接受用户输入而不是scanf

[英]use read() to take user input instead of scanf

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. 我试图使用read()函数接受用户输入,但是我只能在文档中找到关于从文件读取的信息,这是Linux c语言。 I also want to use write() do display something to the console. 我也想使用write()在控制台上显示一些内容。

Does anyone have any idea how this is done? 有谁知道如何做到这一点?

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. 我也想使用write()在控制台上显示一些内容。

Let me not repeat myself. 让我不要重复自己。

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

This here should give you an impression how to do it (0 is stdin, 1 is stdout) 这应该给您印象如何操作(0是标准输入,1是标准输出)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM