Search code examples
c++windowspopen

How do I capture all output of a command launched through _popen, in C++?


I have the following code:

FILE* pipe = _popen(command_.c_str(), "r");
if (!pipe)
{
    throw std::runtime_error{
        "Subprocess::Run: error starting [" + command_ + "]"
    };
}

std::array<char, 512> buffer;
while (!feof(pipe))
    if (fgets(buffer.data(), buffer.size(), pipe) != NULL)
        output_.append(buffer.data());

exit_code_ = _pclose(pipe);

This works to get the standard output and exit code of the executed command;

When I run this code with an invalid command though (something like "dfakjhfasidufha"), an error message appears in my console:

'dfakjhfasidufha' is not recognized as an internal or external command, 
operable program or batch file.

How can I suppress this message?


Solution

  • The message comes from windows (I suppose) so it is default mode to yield to user when something is wrong. Buy you can get rid of this by redirecting to nul. something like yourcommand > nul 2> nul