2016-02-05 113 views
-1

...我試圖將system(char* command)函數的輸出加載/捕獲到變量,vector。我可以有任何可能的方法將輸出推送到我的矢量?我不想將輸出寫入文件並再次讀取。 示例代碼:將系統(char *命令)的輸出加載到變量,C++

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <fstream> 
#include <iostream> 
#include <string> 
#include <cstring> 
#include <sstream> 
#include <vector> 


using namespace std; 

int main() 
{ 
    vector <string> dir; 
    system("pwd");//here i used this to print the current directory, and i want to store this out put to my vector. something like...(below) 
    output=output of system("pwd");//this is not a real code,just to notice i want to put the out put to other var and push. 
    dir.push_back(output); 
return 0; 
} 

我能有任何情況下做這個任務,謝謝。

+0

你試過['getcwd'](http://man7.org/linux/man-pages/man2/getcwd.2.html)嗎? –

+0

你不能得到'system'執行的進程的輸出。你可以用'popen'執行一個命令來獲得一個'FILE *',你可以從中讀取輸出。 – molbdnilo

+0

hello:@BoPersson,感謝您的回放,但getcwd用於捕獲當前工作目錄,這是我的問題的特定答案。但是如果我有其他shell命令被System()函數檢查和執行會怎樣。例如。系統(「任何命令」)? –

回答

1

我建議你做這樣的:

FILE *fp = popen("fortune","r"); 
char line[200]; 
while(!feof(fp)) { 
fgets(line,200,fp); 
// process here 
} 
pclose(fp); 

如果它真的表現的關鍵,它可能更好地 使用fork()和管道爲孩子 進程的標準輸入/輸出,以創建子進程寫或讀。 如果您被構建,可以在這裏找到一個例子(http://www.microhowto.info/howto/capture_the_output_of_a_child_process_in_c.html#idp21888)。但popen方法可能是您的案例中最簡單直接的方法。