在Unix中使用read()
系统调用读取用户输入的可能方法是什么?我们如何使用read()
来从字节读取字节?从stdin读取
从stdin读取
回答
你可以做这样的事情来读取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. */
为什么在联机帮助页中,它使用“将尝试”一词。是否有任何情况下读取不会完全读取由第三个参数指定的字节数?https://linux.die.net/man/3/read – weefwefwqg3 2017-11-13 01:08:28
从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()
....
}
嗯。 'stdin'是一个文件! – 2013-04-08 15:54:16
您可以使用'int fileno(FILE * stream)'首先 – 2013-04-08 15:57:17
谢谢您的评论。答案已更新 – MOHAMED 2013-04-08 15:58:45
- 1. 从stdin反复读取EOF
- 2. 从stdin与monkeyrunner读取
- 3. 从Stdin读取字符串
- 4. Ruby - 从STDIN读取CSV
- 5. 从STDIN读取的脚本
- 6. 从stdin读取单行
- 7. Python PIL从STDIN读取PNG
- 8. 从stdin停止读取
- 9. 从文件读取或STDIN
- 10. 读线从STDIN
- 11. 从python重定向stdin读取文件
- 12. 如何从yii命令读取stdin
- 13. 从stdin中读取stderr中的Python
- 14. 从STDIN读取文件并写入STDOUT
- 15. 从stderr而不是stdin读取
- 16. 使用scanf从stdin C读取文件
- 17. 从ifstream中读取stdin/cin安全吗?
- 18. PHP:从套接字或STDIN中读取
- 19. 设计:从stdin读取密码
- 20. 使用proc_open从STDIN管道读取
- 21. 可选择从STDIN读取C
- 22. 如何从stdin读取一行
- 23. 如何让rsync从STDIN读取SRC?
- 24. 从STDIN逐行读取,无阻塞
- 25. 如何从stdin多次读取stdin中的数据
- 26. 如何使用读取功能从终端输入(stdin)读取?
- 27. 逐行读取stdin - php
- 28. c等待stdin读取?
- 29. 如何异步读取stdin?
- 30. 无法正确读取STDIN
你的笑(读)手册 – 2013-04-08 15:50:48
阅读将做到这一点很好,但根据你想要做什么,你可能会发现,你必须做的不仅仅是调用读 - 你可以发布你的代码,并准确解释哪一部分你有问题? – 2013-04-08 15:53:27
我同意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