如何在 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