C ++ popen () output to string

C ++ popen() returns a file descriptor containing the output after the process has completed. Instead of FILE * I need char *, i.e. the line will be my output. What am I doing? Please help me.

+6
source share
3 answers

I suppose I would do something in 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 detailed information, you can allocate space dynamically and try to increase it as necessary in order to keep the volume of the result you output. This will be the best route if you have at least some idea of ​​how much a child can produce.

Edit: given that you are using C ++, the result with dynamic size is actually quite simple:

 char line[line_size]; std::string result; while (fgets(line, line_size, your_pipe)) result += line; 
+5
source

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

+2
source

See fooobar.com/questions/21128 / ...

You can do this in two lines (three include 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 will take care of all memory allocations and closing the stream again when you are done with it.

+1
source

Source: https://habr.com/ru/post/916167/


All Articles