如何存储system()调用的输出?

bal*_*aji 6 c++ linux

system(3)在Linux上用于c ++程序.现在我需要将输出存储system(3)在数组或序列中.我如何存储输出system(3).

我使用以下:

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

给出输出:

changin 
fdjgjkds 
dglfvk
dxkfjl
Run Code Online (Sandbox Code Playgroud)

我需要将此输出存储到字符串数组或字符串序列.

提前致谢

Bla*_*iev 6

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);
Run Code Online (Sandbox Code Playgroud)

  • @balaji:有一段时间你将不得不阅读这些手册......但是马林现在已经饶了你;-P (3认同)

Mar*_*rin 6

您应该使用popen从stdin读取命令输出.所以,你会做类似的事情:

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

在阅读文本模式下打开它然后使用fgets或类似的东西从管道读取:

fgets(psBuffer, 128, pPipe)
Run Code Online (Sandbox Code Playgroud)