Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store the output of system() call?

Tags:

c++

linux

I am using system(3) on Linux in c++ programs. Now I need to store the output of system(3) in an array or sequence. How I can store the output of system(3).

I am using following:

system("grep -A1 \"<weakObject>\" file_name | grep \"name\" |
    grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 ");  

which gives output:

changin 
fdjgjkds 
dglfvk
dxkfjl

I need to store this output to an array of strings or Sequence of string.

Thanks in advance

like image 378
balaji Avatar asked Apr 05 '11 08:04

balaji


1 Answers

system spawns a new shell process that isn't connected to the parent through a pipe or something else.

You need to use the popen library function instead. Then read the output and push each string into your array as you encounter newline characters.

FILE *fp = popen("grep -A1 \"<weakObject>\" file_name | grep \"name\" |
grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 ", "r");
char buf[1024];

while (fgets(buf, 1024, fp)) {
  /* do something with buf */
}

fclose(fp);
like image 87
Blagovest Buyukliev Avatar answered Sep 23 '22 17:09

Blagovest Buyukliev