如何存储system()调用的输出? [英] how to store the output of system() call?

查看:94
本文介绍了如何存储system()调用的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

我使用以下命令:

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

其中输出:

changin 
fdjgjkds 
dglfvk
dxkfjl



<

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

提前感谢

推荐答案

系统生成一个未通过管道或其他东西连接到父进程的新shell进程。

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

您需要使用 popen 库函数。然后读取输出,并在遇到换行符时将每个字符串推入数组。

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);

这篇关于如何存储system()调用的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆