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

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

    Getting both stdout and stderr (and also writing to stdin, not shown here) is easy peasy with my pstreams header, which defines iostream classes that work like popen:

    #include 
    #include 
    #include 
    
    int main()
    {
      // run a process and create a streambuf that reads its stdout and stderr
      redi::ipstream proc("./some_command", redi::pstreams::pstdout | redi::pstreams::pstderr);
      std::string line;
      // read child's stdout
      while (std::getline(proc.out(), line))
        std::cout << "stdout: " << line << '\n';
      # if reading stdout stopped at EOF then reset the state:
      if (proc.eof() && proc.fail())
        proc.clear();
      // read child's stderr
      while (std::getline(proc.err(), line))
        std::cout << "stderr: " << line << '\n';
    } 
    

提交回复
热议问题