gpt4 book ai didi

c - 在 C 中使用管道在另一个程序中使用 cat 输出

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:27 25 4
gpt4 key购买 nike

我想运行:cat somefile | program > UNIX 系统中的 outputText。

我看过很多东西,例如管道、使​​用 popen、dup2 等;我迷路了。

基本代码应该是:

  • 读取 cat 使用 program 产生的任何输出并施展魔法,然后将数据输出到 outputText。

有什么建议吗?

附言这些文件是二进制文件。

更新:

我发现这段代码适用于上面规定的命令......但是 它会做我不想做的事情。

  1. 如何去掉排序?我尝试删除内容,但随后出现错误,程序无法运行。
  2. 通过cat读取二进制数据
  3. 将数据以二进制形式输出到终端

有什么建议吗?

int main(void)
{
pid_t p;
int status;
int fds[2];
FILE *writeToChild;
char word[50];

if (pipe(fds) == -1)
{
perror("Error creating pipes");
exit(EXIT_FAILURE);
}

switch (p = fork())
{
case 0: //this is the child process
close(fds[1]); //close the write end of the pipe
dup2(fds[0], 0);
close(fds[0]);
execl("/usr/bin/sort", "sort", (char *) 0);
fprintf(stderr, "Failed to exec sort\n");
exit(EXIT_FAILURE);

case -1: //failure to fork case
perror("Could not create child");
exit(EXIT_FAILURE);

default: //this is the parent process
close(fds[0]); //close the read end of the pipe
writeToChild = fdopen(fds[1], "w");
break;
}

if (writeToChild != 0)
{
while (fscanf(stdin, "%49s", word) != EOF)
{
//the below isn't being printed. Why?
fprintf(writeToChild, "%s end of sentence\n", word);
}
fclose(writeToChild);
}

wait(&status);

return 0;
}

最佳答案

这是我的建议,因为你想要读写二进制文件:

#include <stdio.h>

int main (void) {
if (!freopen(NULL, "rb", stdin)) {
return 1;
}
if (!freopen(NULL, "wb", stdout)) {
return 1;
}

char buf[4];
while (!feof(stdin)) {
size_t numbytes = fread(buf, 1, 4, stdin);

// Do something with the bytes here...

fwrite(buf, 1, numbytes, stdout);
}
}

关于c - 在 C 中使用管道在另一个程序中使用 cat 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25925250/

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