C++ 的 popen()
在执行进程后返回包含输出的文件描述符。我需要一个 char* 而不是 FILE*,即。一个字符串作为我的输出。我该怎么办?请帮助我。
最佳答案
我想我会按照这个一般顺序做一些事情:
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);
}
如果您想要更精细,您可以动态分配空间,并根据需要尝试增加它以容纳您获得的输出量。除非您至少知道 child 可能产生多少产出,否则那将是更好的途径。
编辑:鉴于您使用的是 C++,动态大小的结果实际上非常简单:
char line[line_size];
std::string result;
while (fgets(line, line_size, your_pipe))
result += line;
关于C++ popen() 的输出到一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10667972/