2013-04-08 134 views
17

在Unix中使用read()系统调用读取用户输入的可能方法是什么?我们如何使用read()来从字节读取字节?从stdin读取

+1

你的笑(读)手册 – 2013-04-08 15:50:48

+0

阅读将做到这一点很好,但根据你想要做什么,你可能会发现,你必须做的不仅仅是调用读 - 你可以发布你的代码,并准确解释哪一部分你有问题? – 2013-04-08 15:53:27

+0

我同意Mats,你在这里寻找什么* excatly *?哪里有问题? [有](http://stackoverflow.com/questions/9610064/read-stdin-in-c)也有很多不同的[示例](http://stackoverflow.com/questions/7503399/reading-from- stdin-using-read-and-fi-out-the-size-of-the-buffer)如何做到这一点[this on this](http://stackoverflow.com/questions/1237329/read-from-stdin- doesnt-ignore-newline),你在问这个问题之前做了什么搜索? – Mike 2013-04-08 16:09:40

回答

20

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

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

记得read()不添加'\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. */

+0

为什么在联机帮助页中,它使用“将尝试”一词。是否有任何情况下读取不会完全读取由第三个参数指定的字节数?https://linux.die.net/man/3/read – weefwefwqg3 2017-11-13 01:08:28

5

man read

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

输入参数:

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

  • 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() 
    .... 
} 
+7

嗯。 'stdin'是一个文件! – 2013-04-08 15:54:16

+0

您可以使用'int fileno(FILE * stream)'首先 – 2013-04-08 15:57:17

+0

谢谢您的评论。答案已更新 – MOHAMED 2013-04-08 15:58:45