C语言 从标准输入读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15883568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading from stdin
提问by Bunny Bunny
What are the possible ways for reading user input using read()system call in Unix. How can we read from stdin byte by byte using read()?
read()在 Unix 中使用系统调用读取用户输入的可能方法有哪些。我们如何使用 逐字节读取标准输入read()?
回答by Johnny Mnemonic
You can do something like this to read 10 bytes:
您可以执行以下操作来读取 10 个字节:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
remember read()doesn't add '\0'to terminate to make it string (just gives raw buffer).
请记住read()不会添加'\0'到终止以使其成为字符串(仅提供原始缓冲区)。
To read 1 byte at a time:
一次读取 1 个字节:
char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
//do stuff
}
and don't forget to #include <unistd.h>, STDIN_FILENOdefined as macro in this file.
并且不要忘记#include <unistd.h>,STDIN_FILENO在此文件中定义为宏。
There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:
有三个标准 POSIX 文件描述符,对应于三个标准流,大概每个进程都应该期望拥有:
Integer value Name
0 Standard input (stdin)
1 Standard output (stdout)
2 Standard error (stderr)
So instead STDIN_FILENOyou can use 0.
因此,STDIN_FILENO您可以使用 0。
Edit:
In Linux System you can find this using following command:
编辑:
在 Linux 系统中,您可以使用以下命令找到它:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
Notice the comment /* Standard input. */
注意评论 /* Standard input. */
回答by MOHAMED
From the man read:
从男人那里读到:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
输入参数:
int fdfile descriptor is an integer and not a file pointer. The file descriptor forstdinis0void *bufpointer to buffer to store characters read by thereadfunctionsize_t countmaximum number of characters to read
int fd文件描述符是一个整数而不是文件指针。的文件描述符stdin是0void *buf指向缓冲区的指针,用于存储read函数读取的字符size_t count要读取的最大字符数
So you can read character by character with the following code:
因此,您可以使用以下代码逐个读取:
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()
....
}

