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.
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.
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.
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).
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;
Read the output from the FILE*
into a string using the usual stdio
routines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With