c++ - 在 C++ 程序中处理 "system"调用的结果

标签 c++ linux shell console

假设我在 C++ 程序中执行了一些命令以在终端中运行。例如:

int main(){
std::system("./myprog");
return 0;
}

假设 myprog 产生一些打印到控制台的输出。我可以在我的 C++ 程序中使用这个输出吗?例如:

int main(){
some_var = std::system("./myprog");

if (some_var == "something")
  // Do something.

return 0;
}

如有任何帮助,我们将不胜感激。再次感谢。

最佳答案

您需要使用 popen功能:

FILE *fp = popen("./myprog", "r");

char buffer[128];
while (fgets(buffer, sizeof(buffer), fp))
{
    std::cout << "Output from program: " << buffer << '\n';
}

pclose(fp);

关于c++ - 在 C++ 程序中处理 "system"调用的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246460/

相关文章:

c++ - 尽管有 IP_MULTICAST_LOOP(Linux、C++、UDP),IP_ADD_MEMBERSHIP 结果为 "No device found"

c++ - Visual C++,没有试图添加 .dll 的引用

C++:对微不足道的包装方法进行优化

linux - 通过 execlp 执行带有特定输出的命令 ps

linux - "No Output"返回代码 Shell 脚本

bash - 在 bash 中检查 isatty

c++ - x64 转换后指针截断

linux - 当使用 ssh 作为 oracle 用户连接时以 root 身份运行脚本

c - 在 gcc 中初始化数组,未定义对 `memcpy' 的引用

linux - 使用 Linux 在第 2 列中查找第 1 列中每个不同值的平均值