C++ popen() 的输出到字符串

C++ popen()'s output to a string

本文关键字:输出 字符串 popen C++      更新时间:2023-10-16

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

我想

我会按照这个一般顺序做点什么:

char big_buffer[BIG_SIZE];
char small_buffer[LINE_SIZE];
unsigned used = 0;
big_buffer[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;

使用通常的stdio例程将FILE*的输出读入字符串。

请参阅 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());
}

这将处理所有内存分配,并在完成流后再次关闭流。