#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
std::string executeCommand(const char* command) {
std::string result;
FILE* pipe = popen(command, "r");
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
char buffer[128];
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != nullptr) {
result += buffer;
}
}
pclose(pipe);
return result;
}
int main() {
std::string output = executeCommand("ls -l");
std::cout << "Command output:\n" << output << std::endl;
return 0;
}
方法及原理
- 方法:使用
popen
函数来执行系统命令,并将命令的输出通过管道读入程序。popen
函数会创建一个管道,连接到一个新的进程,该进程执行指定的命令。
- 原理:
popen
函数第一个参数是要执行的系统命令,第二个参数指定打开管道的模式,这里使用"r"
表示以读模式打开,意味着可以从命令的标准输出读取数据。
- 使用
fgets
函数从管道中逐行读取数据,并将读取到的内容追加到字符串变量result
中。
- 最后使用
pclose
函数关闭管道,释放相关资源。