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

标签 c unix pipe cat piping

我想运行: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/

相关文章:

c - 从子进程发送信号并在父进程中以这种方式接收是否正确?

bash - 为什么第一个词会丢失?

c++ - CUDA:同步全局内存读写与计算能力 1.1

C 编程 — 获取字符串中的多个单词

c - 矢量化:对齐和未对齐的数组

linux - fullbackup如何提取单表数据?

c - 不同版本操作系统的 OpenMP 性能差异

perl - 有什么方法可以将数据从 Perl 传输到 Unix 命令行实用程序

java - Solaris unix NLWP 限制

bash - 为什么 2>&1 需要在 | 之前出现? (管道)但在 "> myfile"(重定向到文件)之后?