繁体   English   中英

在另一个程序中将cat输出与C中的管道一起使用

[英]Use cat output in another program with pipe in C

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

我看过很多东西,例如管道,使用popen,dup2等。 我搞不清楚了。

基本代码应为:

  • 使用program读取cat产生的任何输出并做一些魔术,然后将数据输出到outputText中。

有什么建议吗?

PS这些文件是二进制文件。

更新:

我发现此代码可与上面的指定命令一起使用...但是它可以做我不想要的事情。

  1. 我该如何摆脱sort 我尝试擦除东西,但随后出现错误,程序无法运行。
  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);
    }
}

为了能够读取cat的输出(stdout),您不需要传递我发现的任何东西,谢谢大家! 我被管道缠住了...

因此,如果您运行“ cat somefile | program ”,其中somefile包含二进制数据...,您将只看到somefile包含的内容,并在终端上重新打印。

谢谢! 现在我可以完成编写program

/*program.c*/

int main()
{
    int i, num;

    unsigned char block[2];

    while ((num = fread(block, 1, 2, stdin)) == 2)
    {
        for(i = 0; i < 2; i++)
        {
            printf("%02x", block[i]);
        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM