[英]read() for reading stream from stdin
我正在尝试编写一个 C 代码(在 Ubuntu Linux 操作系统上运行),它连续从 stdin 读取,并且每次接收不同长度的字节。 当每次接收缓冲区达到或超过 15 时,它需要以 15 字节长的数组发送回标准输出。
代码草案
#include <stdio.h>
#include <unistd.h>
int main()
{
char buff[100];
// Round 1
read(STDIN_FILENO, buff, 15);
printf("Part 1:%s", buff);
// Round 2
read(STDIN_FILENO, buff, 15);
printf("Part 2:%s", buff);
return 0;
}
举一个场景的例子。 我们正在接收 30 个字节,分 3 个批次,每次 10 个字节。 我在下面的示例场景中使用了 3 个 echo 命令来表示这一点。
还添加了当前草稿代码的预期输出和实际输出。 任何获得预期输出的评论或建议(可能是另一个函数而不是 read 和 printf ?),将不胜感激。
设想
1号航站楼:
mkfifo /tmp/MyPipe
tail -f /tmp/MyPipe | ./StreamProcess
2 号航站楼:
echo -ne '1234567890' >> /tmp/MyPipe
echo -ne 'abcdefghij' >> /tmp/MyPipe
echo -ne 'qwertyuiop' >> /tmp/MyPipe
终端 1 的预期输出
第一次回声后:不打印任何内容
第二次回声后:
Part 1:1234567890abcde
第三次回声后:
Part 1:1234567890abcdePart 2:fghijqwertyuiop
端子 1 上的电流输出(带草稿代码)
第一次回声后:不打印任何内容
第二次回声后:
Part 1:1234567890s· s·Part 2:abcdefghijs· s·
第三次回显后:(仅打印 $ 提示)
Part 1:1234567890s· s·Part 2:abcdefghijs· s·$
鉴于问题中列出的条件,以下代码将执行所需的操作。
编辑:将评论纳入问题。
编辑:添加错误检查
#include <stdio.h> // printf(), STDIN_FILENO. perror()
#include <unistd.h> // read(), exit(), EXIT_FAILURE
#define MAX_READ_LEN 15
int main( void)
{
char buff[ MAX_READ_LEN+1 ];
int partNum = 0;
while( 1 )
{
// Round 1
ssize_t bytesRead = read( STDIN_FILENO, buff, MAX_READ_LEN );
if( 0 > bytesRead )
{
perror( "read failed" );
exit( EXIT_FAILURE );
}
// implied else, read successful
buff[ bytesRead ] = '\0';
partNum++;
printf("Part %d:%s\n", partNum, buff);
}
return 0;
} // end function: main
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.