【问题标题】:use read() to take user input instead of scanf使用 read() 获取用户输入而不是 scanf
【发布时间】:2013-01-16 03:32:06
【问题描述】:

我正在尝试使用 read() 函数来获取用户输入,但我在文档中唯一能找到的是关于从文件中读取的内容,这是用 Linux c 语言编写的。我还想使用 write() 向控制台显示一些东西。

有人知道这是怎么做到的吗?

【问题讨论】:

标签: c linux io low-level-code


【解决方案1】:

但我在文档中唯一能找到的是关于从文件中读取

别担心,标准输入是一个文件。

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

我还想使用 write() 向控制台显示一些东西。

让我不再重复。

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

【讨论】:

  • 非常感谢,我试试看
【解决方案2】:

这里应该给你一个印象如何去做(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);
  }
}

【讨论】:

  • 小心,这将等到用户输入 100 个字符后 read(2) 返回。
  • 不,它没有,它也在\n之后返回
猜你喜欢
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 2015-03-23
  • 2011-01-09
  • 2022-01-22
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多