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

更新日期:12-2-2020

12K+ 次瀏覽

開啟你的 職業 生涯

透過完成課程獲得證書

開始
廣告
© . All rights reserved.