从标准输入读(Reading from stdin)

2019-08-20 08:21发布

问:使用读取用户输入的可能途径read()在Unix系统中调用。 我们怎样才能从标准输入逐字节读取使用read()

Answer 1:

你可以做这样的事情来读取10个字节:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

记得阅读()不加'\0'终止使它字符串(只是给原始缓冲区)。

要一次读取1个字节:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

和不要忘记#include <unistd.h>STDIN_FILENO定义为在该文件中的宏。

有三个标准POSIX文件描述符,对应于三个标准流,这大概每一道工序都要准备好:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

所以不是STDIN_FILENO你可以使用0。

编辑:
在Linux的系统,你可以找到这个使用下面的命令:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

注意注释/* Standard input. */ /* Standard input. */



Answer 2:

从男人读 :

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

输入参数:

  • int fd文件描述符是一个整数,而不是一个文件指针。 对于文件描述符stdin0

  • void *buf指针缓冲器,用于存储由所述读取字符read功能

  • size_t count的最大字符数读

所以,你可以用下面的代码字符读取字符:

char buf[1];

while(read(0, buf, sizeof(buf))>0) {
   // read() here read from stdin charachter by character
   // the buf[0] contains the character got by read()
   ....
}


文章来源: Reading from stdin
标签: c unix stdin