#include <string>
#include <iostream>
#include <stdio.h>
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
Replace popen and pclose with _popen and _pclose for Windows.
本文介绍了如何在C程序中调用shell脚本的三种方法,包括直接使用系统调用,通过execlp系列函数,以及利用system函数。示例代码展示了如何在同层目录下创建C文件并执行shell脚本,同时也提供了StackOverflow上的相关问题链接作为更深入学习的资源。

1834







result += buffer, so the pipe might not be properly closed. – larsmans May 19 '12 at 20:27bad_alloc. – larsmans Mar 14 at 22:00