1

I have two programs (Prog1.c and Prog2.c) written in C and each of them take one command line argument.

Prog1.c takes a file name as argument , reads content from file and outputs it on the STDOUT (standard output) screen. Prog2.c takes data as argument and does some operation. I want to redirect output of Prog1.c to Prog2.c as input.

I have tried following bash script which gives me error

#!/bin/bash
prog2 "`prog1 file.txt`"  

I have also tried without quotes and in both cases, it gives me following error.

Prog2:: argument list too long.
Junaid
  • 1,668
  • 7
  • 30
  • 51
  • There seems to be a confusion for Prog2 between 'takes data as arguments' and what seems more correct to me 'reads data on STDIN', because you WILL run out of command line buffer space pretty fast if Prog1's output is large enough. – SirDarius Dec 03 '12 at 09:32
  • Visit [This Link][1] , It may help you. Same questions like yours. [1]: http://stackoverflow.com/questions/8593939/redirecting-output-of-a-c-program-to-another-c-program-with-a-bash-script-under – Shahzeb Khan Dec 03 '12 at 09:35
  • I have read that whole thread and it does not solve that problem. Hope you understood the difference between questions of two threads. – Junaid Dec 03 '12 at 09:37
  • I have tried accepted solution of that thread, it does not work, that's why I posted another question. – Junaid Dec 03 '12 at 09:38
  • 1
    and why -2? Whats wrong with the question? – Junaid Dec 03 '12 at 09:41

3 Answers3

3

To get the output of a command as a parameter for another command you can use backticks:

prog2 "`prog1 file.txt`"

or use $() (I believe this is a more preferred way for bash):

prog2 "$(prog1 file.txt)"

If you want to use the STDOUT of prog1 as STDIN for prog2 use the | (pipe) operator:

prog1 | prog2

Note: When you want to use pipes, you need to modify the code of prog2, as it needs to read from STDIN instead of the command arguments (argv of the main() function). See How to read a line from the console in C? for an example on how to do this.

Community
  • 1
  • 1
Veger
  • 37,240
  • 11
  • 105
  • 116
2

PIPES!!!!!

On the command line (or in your script) do prog1 file.txt | prog2

parker.sikand
  • 1,371
  • 2
  • 15
  • 32
1

You must use backticks in both places before and after prog1

prog2 "`prog1 file.txt`"

When you get "argument list too long", you have reached the system limit for the command line. You must then find another way to send the data to prog2. You can read from stdin instead, and pipe the output of prog1 to prog2

prog1 file.txt | prog2

When you pipe the data from prog1 to prog2, you must change prog2 and read from stdin instead of using argv.

Example reading line by line:

char buf[1024];
while (fgets(buf, 1024, stdin)) {
    /* process line in buf */
}

Example reading white space delimited words

char buf[1024];
while (scanf("%s", buf) != EOF) {
    /* process word in buf */
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198