TurnsCoffeeIntoScripts
TurnsCoffeeIntoScripts

Reputation: 3918

Can't get output result from 'g++' call

I'm doing a system call in c++:

system( "g++ file1.cpp -o test" );

And I'm trying to get the result in the command line into a std::string object. The reason I'm doing that is to analyze the output of g++ in the case where g++ fails because there is an error in the cpp. Here's the method I've built for that:

std::string CmdLineCall( std::string cmd )
{
    FILE* pipe = _popen( cmd.c_str(), "r");
    if( pipe == NULL )
    {
        return "error";
    }

    char* buffer;
    long bufferSize = cmd.size();
    size_t code;
    std::string result;

    buffer = ( char* )malloc( sizeof( char ) * bufferSize );
    if( buffer == NULL )
    {
        return "error";
    }

    code = fread( buffer, 1, sizeof( buffer ), pipe );
    if( code != bufferSize )
    {
        return "error";
    }

    result = buffer;
    return result;
}

I've debugged it and it goes all the way to the end but result = "".

I've tried with a simple system( "pause" ) command and it works, but it doesn't work. Can it have something to do with the fact that the g++ call fails because my cpp file is flawed?

Thanks

Upvotes: 0

Views: 60

Answers (1)

mah
mah

Reputation: 39807

Using system() is probably not the best choice for this. You might have better results with popen(), since that lets you read the standard output of your command -- but I suspect that won't be enough here either (as I assume the compiler may also print to stderr and popen() doesn't give you that).

Your best bet is to provide your own variant of popen that includes support for both stdout and stderr (and if you search for "popen source" I'm sure you'll have a good starting point).

Edit: on a re-read of your post, I see you are using popen()… so I'm a bit confused about where system() comes into play since you wouldn't use both of them. Regardless, I still feel the problem is that stderr is important and popen() isn't giving that to you, so you'll need to go get it yourself; you could do that by rewriting popen() or you could just redirect your own stderr to the input channel of a pipe before you call popen().

Upvotes: 2

Related Questions