如何在 C++ 中使用 POSIX 执行命令并获取其输出?
您可以使用 popen 和 pclose 函数从进程处接收或向进程发送数据。popen() 函数创建一个进程,方法是创建一个管道、一个 fork 和一个 shell,然后调用 shell。我们可以使用一个缓冲区来读取 stdout 的内容,并将其附加到一个结果字符串中,然后当进程退出时返回该字符串。
示例
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;
string exec(string command) {
char buffer[128];
string result = "";
// Open pipe to file
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) {
return "popen failed!";
}
// read till end of process:
while (!feof(pipe)) {
// use buffer to read and add to result
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main() {
string ls = exec("ls");
cout << ls;
}输出
这将生成以下输出 -
a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP