C++ popen()输出到一个字符串

Tab*_*med 7 c++ string file popen

popen()在执行进程后,C++ 将返回包含输出的文件描述符.而不是FILE*,我需要一个char*,即.一个字符串作为我的输出.我该怎么办?请帮我.

Jer*_*fin 6

我想我会对这个一般订单做点什么:

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);
}
Run Code Online (Sandbox Code Playgroud)

如果您想要更精细,可以动态分配空间,并尝试根据需要增加空间以保持您获得的输出量.这将是一条更好的路线,除非你至少知道孩子可能产生多少输出.

编辑:鉴于您使用的是C++,动态大小的结果实际上非常简单:

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

while (fgets(line, line_size, your_pipe))
     result += line;
Run Code Online (Sandbox Code Playgroud)