在Unix中,使用read()
系统调用读取用户输入的可能方式有哪些?我们如何使用read()
逐字节从标准输入读取数据?
你可以像这样读取10个字节:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
请记住,read()函数不会添加'\0'
作为字符串终止符(只会提供原始缓冲区)。
要逐个字节读取:
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)
因此,您可以使用0而不是STDIN_FILENO
。
编辑:
在Linux系统中,您可以使用以下命令找到它:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
注意注释 /*标准输入。*/
来自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()
....
}
int fileno(FILE *stream)
。 - Grijesh Chauhanstdin
就是 0,所以你只需要 read(0,...
不需要在 *NIX 系统中搜索 stdin
的文件号。 - Mikestdin = 0
,stdout = 1
,stderr = 2
,而且好消息是它在所有操作系统上都是一样的。 - Grijesh Chauhanchar c
; read(0, &c, 1)
来进行读取,(2)read()函数不会像fgets()
一样在输入缓冲区中加上\0
。因此,如果有人想将缓冲区用作字符串,他必须显式地添加null,例如:no_byte = read(0, buffer, sizeof(buffer)-1); buffer[no_bytes] = '\0';
这是新手容易犯错的地方,就像在这个问题中第二个错误一样...请继续,这就是我想要补充的内容。 - Grijesh Chauhan
read()
手册。 - Grijesh Chauhan