How to save the output of a call to system ()?

I use system(3) for Linux in C ++ programs. Now I need to save the output of system(3) in an array or sequence. How to save the output of system(3) .

I am using the following:

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

which gives the result:

 changin fdjgjkds dglfvk dxkfjl 

I need to save this output to an array of strings or a sequence of strings.

Thanks in advance

+6
c ++ linux
source share
3 answers

system spawns a new shell process that is not connected to the parent through a pipe or something else.

Instead, you need to use the popen library function. Then read the output and push each line into your array when 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); 
+6
source share

You must use popen to read the output of the command from stdin. so you would do something like:

 FILE *pPipe; pPipe = popen("grep -A1 \"\" file_name | grep \"name\" | grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 ", "rt") 

to open it in text reading mode and then use fgets or something similar to reading from a channel:

 fgets(psBuffer, 128, pPipe) 
+6
source share
 The esier way: std::stringstream result_stream; std::streambuf *backup = std::cout.rdbuf( result_stream.rdbuf() ); int res = system("grep -A1 \"<weakObject>\" file_name | grep \"name\" | grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 "); std::cout.rdbuf(backup); std::cout << result_stream.str(); 
0
source share

All Articles