如何将数据传递给在Linux中调用scanf()和read()的程序
发布时间:2020-12-14 01:01:58 所属栏目:Linux 来源:网络整理
导读:我有一个C程序,看起来像这样: #include stdio.h#include unistd.hint main(){ int n; char str[16]; scanf("%d",n); printf("n: %dn",n); int count = read(STDIN_FILENO,str,16); printf("str: %sn",str); printf("read %d bytesn",count);} 如果我使用
我有一个C程序,看起来像这样:
#include <stdio.h> #include <unistd.h> int main() { int n; char str[16]; scanf("%d",&n); printf("n: %dn",n); int count = read(STDIN_FILENO,str,16); printf("str: %sn",str); printf("read %d bytesn",count); } 如果我使用类似命令将数据传输到此程序中 (echo -en '45n'; echo -en 'textn') | ./program 只有scanf()实际读取数据. read()只读取0个字节. 换句话说,程序输出 n: 45 str: read 0 bytes 如何将数据传输到scanf()和read()? 编辑:对不起,我应该澄清:我正在寻找一种方法来做到这一点,而无需修改源代码.感谢那些回答和评论的人. 解决方法
根本不建议对同一文件描述符使用文件描述符函数(读取)和流函数(scanf).使用FILE *的函数(即fread / fprintf / scanf / …)是缓冲数据,而使用文件描述符(即读/写/ …)的函数不使用那些缓冲区.在您的情况下,修复程序的最简单方法是使用fread而不是read.该计划可能如下所示:
#include <stdio.h> #include <unistd.h> int main() { int n; char str[16]; scanf("%d",&n); printf("n: %dn",n); int count = fread(str,16,1,stdin); printf("str: %sn",str); printf("read %d bytesn",count); } 在您的原始示例中,scanf已经读取了前面的输入并将其存储在其缓冲区中.因为输入很短并且可以立即使用,所以它完全被读取到缓冲区并且您的读取调用没有更多要阅读. 直接从终端输入输入时不会发生这种情况,因为从终端设备读取时,scanf不会将数据缓冲超过一行.如果您通过命令在管道输入中创建时间暂停,也不会发生这种情况: (echo -en '45n'; sleep 1; echo -en 'textn') | ./program (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- linux – fork()copy-on-write是否可以用来实现只读共享内存
- redhat – 如何在Red Hat Enterprise Linux上配置永久arp条
- SElinux 错误的查看处理 ,开启SElinux使用zabbix
- linux – 为什么Docker容器无法相互通信?
- linux – 在使用ioctl / SIOCGIFADDR / SIOCGIFCONF找出如何
- Barebones Linux服务器安装
- actionscript-3 – `root`在不同的地方发生变化
- Linux上哪个版本的C库符合“ISO C 11”标准?
- LINUX学习:抓包工具tcpdump使用详解
- 修复Linux TCP的窗口缩放问题