Artemis_134
Artemis_134

Reputation: 173

How to write contents of file to pipe?

I have this code:

            close(pipefd[0]);

            fp = fopen(argv[1], "r");

            if(fp)
            {
                while((c = getc(fp)) != EOF)
                {
                    if((write(pipefd[1], c, 1)) < 1)
                    {
                        fprintf(stderr, "Write to pipe failed.\n");
                        exit(EXIT_FAILURE);
                    }
                }
            }

            fclose(fp);

            close(pipefd[1]);   
            waitpid(childPID, &status, 0);
            exit(EXIT_SUCCESS);

which, to my understanding, should open a file and write its contents to the pipe. This then becomes the stdin for another program. My testing shows that everything is working except the write, but I have no idea why it's not working.

Am I just doing something stupid?

EDIT: Yes, I was doing something stupid.

I thought the problem was with my write (after I fixed c needing to be &c), but it was actually in my child process, where I was using dup2() to link the read end of the pipe to the stdin of my child process. I had the arguments backwards. Here is the working code, from the fork() onwards:

childPID = fork();
if (childPID == 0)
{
    //child code
    //printf("In the child process.\n");
    dup2(pipefd[0], STDIN_FILENO);
    close(pipefd[1]);

    execv(argv[2], paramList);
    printf("You shouldn't be seeing this.\n");
}
else
{
    //parent code
    //printf("In the parent process\n");
    close(pipefd[0]);

    fp = fopen(argv[1], "r");

    if(fp)
    {
        while((c = getc(fp)) != EOF)
        {
            if((write(pipefd[1], &c, 1)) < 1)
            {
                fprintf(stderr, "Write to pipe failed.\n");
                perror("write");
                exit(EXIT_FAILURE);
            }
        }
    }

    fclose(fp);

    close(pipefd[1]);   
    waitpid(childPID, &status, 0);
    exit(EXIT_SUCCESS);
}

Hopefully this helps someone else not have to bang their head on the desk for four days! And thank you to everyone who to the time to answer.

Upvotes: 2

Views: 11057

Answers (1)

MattJ
MattJ

Reputation: 7924

write() takes a pointer to a buffer of data to write, not a character (which is essentially a number).

The answer is simple, instead of passing c to write(), pass the address of c, ie. &c.

Upvotes: 2

Related Questions