2012-05-19 24 views
6

C++的popen()在執行一個進程後返回一個包含輸出的文件描述符。而不是FILE *,我需要一個char *,即。一個字符串是我的輸出。我該怎麼辦?請幫幫我。將C++ popen()的輸出轉換爲字符串

+3

看一看此主題: http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c 祝你好運! – DCMaxxx

回答

5

我想我會做一些事情這個一般順序:

char big_buffer[BIG_SIZE]; 
char small_buffer[LINE_SIZE]; 
unsigned used = 0; 

big_buffer[0] = '\0'; // initialize the big buffer to an empty string 

// read a line data from the child program 
while (fgets(small_buffer, LINE_SIZE, your_pipe)) { 
    // check that it'll fit: 
    size_t len = strlen(small_buffer); 
    if (used + len >= BIG_SIZE) 
     break; 

    // and add it to the big buffer if it fits 
    strcat(big_buffer, small_buffer); 
    used += strlen(small_buffer); 
} 

如果你想獲得更詳細的,你可以動態地分配空間,並嘗試在必要時提高其保持輸出量你得到。除非你至少有一些關於孩子能產出多少產出的想法,否則這將是一條更好的路線。

編輯:既然你在使用C++,具有動態大小的結果其實是很容易的:

char line[line_size]; 
std::string result; 

while (fgets(line, line_size, your_pipe)) 
    result += line; 
+0

爲什麼不使用'std :: string'作爲最終結果並使用'append'? –

+0

@KerrekSB:主要是因爲我以某種方式認爲它被標記爲C而不是C++。 –

2

使用通常的stdio例程將FILE*的輸出讀取爲字符串。

+3

感謝您的回覆。你能否提供一個示例代碼...... !!! –

1

https://stackoverflow.com/a/10702464/981959

你可以做到這一點兩線(三級包括的typedef提高可讀性):

#include <pstream.h> 
#include <string> 
#include <iterator> 

int main() 
{ 
    redi::ipstream proc("./some_command"); 
    typedef std::istreambuf_iterator<char> iter; 
    std::string output(iter(proc.rdbuf()), iter()); 
} 

這將負責所有內存分配,並在完成後關閉流。