Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 868
Tabrez Ahmed Avatar asked May 19 '12 18:05

Tabrez Ahmed


People also ask

What does Popen return?

The popen() function executes the command specified by the string command. It creates a pipe between the calling program and the executed command, and returns a pointer to a stream that can be used to either read from or write to the pipe.

What does the popen () return on success?

popen(): on success, returns a pointer to an open stream that can be used to read or write to the pipe; if the fork(2) or pipe(2) calls fail, or if the function cannot allocate memory, NULL is returned.

What is the difference between Popen and system?

popen() gives you control over the process's input or output file streams. system() doesn't. If you don't need to access the process's I/O, you can use system() for simplicity. system() is in C89 and C99; popen() is Posix only (though the Windows API also has one).


2 Answers

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;
like image 99
Jerry Coffin Avatar answered Sep 20 '22 02:09

Jerry Coffin


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

like image 44
Fred Foo Avatar answered Sep 21 '22 02:09

Fred Foo