1

I want to pass command line to my c program by reading another file using cat command as follows:

cat data | ./file

contents of the file data are

abc def ghi jkl mno pqr stu vwx yz

and code of the file.c is

#include <stdio.h>

int main( int args, char * argv[] )
{
     int i = 0;
     for( i; i < args; i++ )
     {
         printf(argv[i]);
         printf("\n");
     }
}

when the code is run as follows

cat a | ./file

it just display the file name and don't display the a contents. Am I doing it right?

HAMAD MAHMOOD
  • 295
  • 1
  • 2
  • 7

3 Answers3

2

You should try something like:

./file $(cat a)
SMA
  • 36,381
  • 8
  • 49
  • 73
2

The pipe is treated as STDIN fd instead of command line arguments.

You may need cat a | xargs ./file.

leetom@leetoms-MBP:~$ cat aa.txt
aaa bbb cc
leetom@leetoms-MBP:~$ cat aa.txt | xargs ./a.out
./a.out
aaa
bbb
cc
leetom
  • 723
  • 1
  • 6
  • 27
0

You need to read piped input from the standard input stream with cin as shown in this answer. Your file would become:

#include <iostream>
#include <string>

int main( int args, char ** argv )
{

    std::string lineInput;
    while (std::cin >> lineInput) {
        std::cout << lineInput << std::endl;
    }

}

Then your approach will work directly:

$ cat data | ./file
abc
def
ghi
jkl
mno
pqr
stu
vwx
yz
Community
  • 1
  • 1
mattsilver
  • 4,386
  • 5
  • 23
  • 37