How do I execute a command and get the output of the command within C++ using POSIX?

前端 未结 11 1159
我在风中等你
我在风中等你 2020-11-21 05:39

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

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 06:16

    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
    

提交回复
热议问题