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

这将负责所有内存分配,并在完成后关闭流。