I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system()
function, but that will jus
C++ stream implemention of waqas's answer:
#include
#include
#include
#include
#include
#include
#include
class execbuf : public std::streambuf {
protected:
std::string output;
int_type underflow(int_type character) {
if (gptr() < egptr()) return traits_type::to_int_type(*gptr());
return traits_type::eof();
}
public:
execbuf(const char* command) {
std::array buffer;
std::unique_ptr pipe(popen(command, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
this->output += buffer.data();
}
setg((char*)this->output.data(), (char*)this->output.data(), (char*)(this->output.data() + this->output.size()));
}
};
class exec : public std::istream {
protected:
execbuf buffer;
public:
exec(char* command) : std::istream(nullptr), buffer(command, fd) {
this->rdbuf(&buffer);
}
};
This code catches all output through stdout
. If you want to catch only stderr
then pass your command like this:
sh -c '' 2>&1 > /dev/null
If you want to catch both stdout
and stderr
then the command should be like this:
sh -c '' 2>&1