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
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);
You should use popen to read the command output from stdin. so, you'd do something like:
FILE *pPipe;
pPipe = popen("grep -A1 \"\" file_name | grep \"name\" | grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 ", "rt")
to open it in read text mode and then use fgets or something similar to read from the pipe:
fgets(psBuffer, 128, pPipe)
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();