我在c ++程序中使用Linux system(3)
。 现在我需要将system(3)
的输出存储为数组或序列。 我如何可以存储system(3)
的输出。
我正在使用以下内容:
system("grep -A1 \"<weakObject>\" file_name | grep \"name\" | grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 ");
这给出了输出:
changin fdjgjkds dglfvk dxkfjl
我需要将这个输出存储到一个string数组或string序列。
提前致谢
system
产生了一个新的shell进程,没有通过管道或其他东西连接到父进程。
您需要使用popen
库函数。 然后读取输出,并在遇到换行符时将每个字符串推送到数组中。
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);
你应该使用popen来读取stdin的命令输出。 所以,你会做这样的事情:
FILE *pPipe; pPipe = popen("grep -A1 \"\" file_name | grep \"name\" | grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 ", "rt")
以读文本模式打开它,然后使用fgets或类似的东西从管道中读取:
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();