raffaello
raffaello

Reputation: 21

Use cat output in another program with pipe in C

I want to run: cat somefile | program > outputText in a UNIX system.

I have looked at many things such as pipe, using popen, dup2, etc; I am lost.

Basic code should be:

Any advice please?

P.S. The files are binary files.

UPDATE:

I found this code that works with the prescribed command above... But it does things I don't want.

  1. How do I get rid of the sort? I tried erasing things, but then I get errors and the program doesn't run.
  2. Read data by cat as binary
  3. Output data to terminal as binary

Any tips please?

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;
}

Upvotes: 2

Views: 3849

Answers (2)

Henrik
Henrik

Reputation: 4314

This is my suggestion, as you wanted read and write binary files:

#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);
    }
}

Upvotes: 1

raffaello
raffaello

Reputation: 21

To be able to read the output (stdout) of cat, you don't need to pipe anything I found thanks to you guys! I got sidetracked with piping...

so if you run " cat somefile | program ", where somefile contains binary data... you will just see whatever somefile contains, reprinted on a terminal.

Thank you! Now I can finish writing my 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]);
        }
    }

}

Upvotes: 0

Related Questions