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:
- Read whatever output
cat
produces usingprogram
and do some magic, an then output the data into outputText.
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.
- How do I get rid of the
sort
? I tried erasing things, but then I get errors and the program doesn't run. - Read data by
cat
as binary - 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;
}
cat
to pipe into it when you can just set thestdin
ofprogram
tosomefile
? i.e.,program < somefile > outputText
cat somefile | program > output
, then you're on the wrong track. Running the command like that makes the shell pipe the output fromcat
to the input ofprogram
. That's not the same as setting up a pipe inside your program. en.wikipedia.org/wiki/Redirection_(computing)#Piping