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

14,622

Solution 1

I suppose I'd do something on this general order:

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);
}

If you want to get more elaborate, you could allocate space dynamically, and attempt to increase it as necessary to hold the amount of output you get. That would be a better route unless you have at least some idea of how much output the child might produce.

Edit: Given that you're using C++, a result with dynamic size is actually pretty easy:

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

while (fgets(line, line_size, your_pipe))
     result += line;

Solution 2

Read the output from the FILE* into a string using the usual stdio routines.

Solution 3

See https://stackoverflow.com/a/10702464/981959

You can do it in two lines (three including a typedef to improve readability):

#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());
}

This takes care of all memory allocation and closing the stream again when you're finished with it.

Share:
14,622
Tabrez Ahmed
Author by

Tabrez Ahmed

Updated on June 23, 2022

Comments

  • Tabrez Ahmed
    Tabrez Ahmed almost 2 years

    C++'s popen() returns a file descriptor that contains the output, after executing a process. Instead of a FILE*, I need a char*, ie. a string to be my output. What do I do? Please help me.