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

标签 c++ string file popen

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/

相关文章:

c++ - 我的文件输出到屏幕两次 C++?

c++ - 来自 Xcode 编写的 C++ 程序的 Linux Makefile

c++ - 绘制线程上下文切换的工具

java - 在 Java 中使用变量创建正则表达式

string - 如何在golang中椭圆截断文本?

php - 使用 PHP/MySQL 安全地存储和服务用户文件

c++ - 如何将字符串变量名转换为变量的值

c++ - 如何简洁、便携和彻底地播种 mt19937 PRNG?

asp.net - 如何更改 ASP.NET 配置工具连接字符串

linux - 如何在/mnt/中创建文件读/写权限?