[英]Reading from stdin
What are the possible ways for reading user input using read()
system call in Unix. 在Unix中使用
read()
系统调用读取用户输入的可能方法有哪些。 How can we read from stdin byte by byte using read()
? 我们如何使用
read()
逐字节read()
stdin?
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_FILENO
defined 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_FILENO
you 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. */
/* Standard input. */
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters: 输入参数:
int fd
file descriptor is an integer and not a file pointer. int fd
文件描述符是一个整数而不是文件指针。 The file descriptor for stdin
is 0
stdin
文件描述符是0
void *buf
pointer to buffer to store characters read by the read
function void *buf
指向void *buf
指针,用于存储read
函数读取的字符
size_t count
maximum number of characters to 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()
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.