如何在 C++ 中使用 POSIX 執行命令並獲取命令的輸出?


你可以使用 popen 和 pclose 函式在程序中進行管道通訊。popen() 函式透過建立管道、fork 和呼叫 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-Feb-2020

12K+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.