executing a command and getting o/p to a variable
popen
stores o/p of the specified command into a file. How can I get similar functionality but o/p in开发者_如何转开发to a variable (i.e. in a char*) ?
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.
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.
you can replace STDOUT and STDERR for the launched command with a stream that you control
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.
精彩评论