从标准输入读取 [英] Reading from stdin
问题描述
什么是阅读使用阅读()
系统调用在UNIX用户输入的可能途径。我们怎样才能用从标准输入字节读取字节阅读()
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()
推荐答案
您可以做这样的事情来读取10个字节:
You can do something like this to read 10 bytes:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
()不添加'\\ 0
终止使它字符串(只是给原始缓冲区)。
remember read() doesn't add '\0'
to terminate to make it string (just gives raw buffer).
要一次读取1个字节:
char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
//do stuff
}
和不要忘了的#include<&unistd.h中GT;
, STDIN_FILENO
在这个定义的宏文件。
and don't forget to #include <unistd.h>
, STDIN_FILENO
defined as macro in this file.
有三种标准的POSIX文件描述符,对应于三个标准流,其中presumably每一道工序应该期望有:
There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:
Integer value Name
0 Standard input (stdin)
1 Standard output (stdout)
2 Standard error (stderr)
所以不是 STDIN_FILENO
可以使用0。
编辑:结果
在Linux的系统,你可以找到这个使用下面的命令:
In Linux System you can find this using following command:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
注意注释 / *标准输入。 * /
这篇关于从标准输入读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!