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

前端 未结 11 1151
我在风中等你
我在风中等你 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:03

    The following might be a portable solution. It follows standards.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    std::string ssystem (const char *command) {
        char tmpname [L_tmpnam];
        std::tmpnam ( tmpname );
        std::string scommand = command;
        std::string cmd = scommand + " >> " + tmpname;
        std::system(cmd.c_str());
        std::ifstream file(tmpname, std::ios::in | std::ios::binary );
        std::string result;
        if (file) {
            while (!file.eof()) result.push_back(file.get())
                ;
            file.close();
        }
        remove(tmpname);
        return result;
    }
    
    // For Cygwin
    
    int main(int argc, char *argv[])
    {
        std::string bash = "FILETWO=/cygdrive/c/*\nfor f in $FILETWO\ndo\necho \"$f\"\ndone ";
        std::string in;
        std::string s = ssystem(bash.c_str());
        std::istringstream iss(s);
        std::string line;
        while (std::getline(iss, line))
        {
            std::cout << "LINE-> " + line + "  length: " << line.length() << std::endl;
        }
        std::cin >> in;
        return 0;
    }
    

提交回复
热议问题