pipe output from command to string

What is the equivalent in c++ to python's subprocess module in which allows to pipe the output of a command into a string variable?
1
2
3
proc = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
string, error = proc.communicate()
print(string.decode())


system() is the first thing to come to mind, however it just returns the commands success or not.

more specifically, the overall goal of this was to determine whether there was a lone monitor or not connected at the time the program ran. Thus in Linux, to parse xrandr's output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
metulburr@laptop:~$ xrandr
Screen 0: minimum 8 x 8, current 3200 x 1080, maximum 8192 x 8192
VGA-0 disconnected (normal left inverted right x axis y axis)
TV-0 disconnected (normal left inverted right x axis y axis)
LVDS-0 connected 1280x800+0+0 (normal left inverted right x axis y axis) 331mm x 207mm
   1280x800       60.0*+
HDMI-0 connected 1920x1080+1280+0 (normal left inverted right x axis y axis) 886mm x 498mm
   1920x1080      60.0*+   59.9     24.0     30.0     30.0  
   1440x480       30.0  
   1360x768       60.0  
   1360x765       60.0  
   1280x1024      60.0  
   1280x720       60.0     59.9  
   1024x768       60.0  
   800x600        60.3  
   720x480        59.9     30.0  
   640x480        59.9     59.9  
metulburr@laptop:~$ 


EDIT:
The only way i can think of to get the output into a string is to pipe it to a text file via bash command
xrandr > xrandr.txt
but that doesn't seem like the best way to do it programmatically.
Last edited on
Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>

FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);

std::string pipe_to_string( const char* command )
{
    FILE* file = popen( command, "r" ) ;

    if( file )
    {
        std::ostringstream stm ;

        constexpr std::size_t MAX_LINE_SZ = 1024 ;
        char line[MAX_LINE_SZ] ;

        while( fgets( line, MAX_LINE_SZ, file ) ) stm << line << '\n' ;

        pclose(file) ;
        return stm.str() ;
    }

    return "" ;
}

int main()
{
    const std::string result = pipe_to_string( "ls -la" ) ;
    std::cout << result << '\n' ;
    // ...
}

http://coliru.stacked-crooked.com/a/918d46689227bf20
thanks JLBorges
Topic archived. No new replies allowed.