gpt4 book ai didi

c - read() 用于从标准输入读取流

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:56 32 4
gpt4 key购买 nike

我正在尝试编写一个 C 代码(在 Ubuntu Linux 操作系统上运行),它连续从标准输入读取,并且每次接收不同长度的字节。每当接收缓冲区每次达到或超过 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

关于c - read() 用于从标准输入读取流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391925/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com