2012-05-19 8 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); 
} 

あなたがより精巧な取得したい場合は、動的に領域を割り当て、および出力の量を保持するために、必要に応じて、それを増やすしようとする可能性がありあなたは得る。子供がどのくらいのアウトプットを生み出すかについて少なくともいくらか考えなければ、それはより良いルートになるでしょう。

編集:

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

がへのtypedefを含むhttps://stackoverflow.com/a/10702464/981959

次の2つのラインでそれを行うことができます(3を参照してください:あなたがCを使用していることを考えると++、動的なサイズの結果は、実際にはかなり簡単です。可読性を向上させます)。

#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()); 
} 

これは、すべてのメモリ割り当てを処理し、ストリームの終了時に再びストリームを閉じます。