popen
stores o/p of the specified command into a file. How can I get similar functionality but o/p into a variable (i.e. in a char*) ?

- 9,439
- 27
- 76
- 110
-
Have a look a this question (pretty much, duplicate of yours): http://stackoverflow.com/questions/219138/get-command-output-in-pipe-c-for-linux – Aleks G Jul 07 '11 at 08:03
-
@Aleks: Sorry, its not what I am asking here. – hari Jul 07 '11 at 08:40
4 Answers
No, popen()
does not store output into a file. It specifies a stream, which might represent to a file on disk but which might also be at e.g. a pipe or socket. Streams are more abstract than files.
To have a pipe, you would open the pipe using e.g. pipe()
and then call fdopen()
on the proper end of the resulting pipe.

- 391,730
- 64
- 469
- 606
-
Thanks unwind. What I want to do is to be able to execute a very simple thing i.e. `wc -l filename` and store the o/p in a variable/buffer. Possible? – hari Jul 07 '11 at 08:24
I could not find anything that returns o/p in a variable. It kind of makes sense as some commands' o/p can be large so to make the behavior consistent, o/p is stored in the file. I actually ended up reading from file returned by popen
.
Thanks for all the help.

- 9,439
- 27
- 76
- 110
you can replace STDOUT and STDERR for the launched command with a stream that you control

- 10,632
- 1
- 37
- 47
Do you want to run a unix command from a C program, and store the output?
If so, then the sequence is to call FILE* pipe = popen("wc -l filename", "r");
and then read from the FILE* pipe
just as you would read from a file opened using fopen
. That is, you use functions like fgets
or fscanf
to read the output, just as you would if the output of the command were in a file.

- 11,978
- 2
- 33
- 56