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

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

    Take note that you can get output by redirecting output to the file and then reading it

    It was shown in documentation of std::system

    You can receive exit code by calling WEXITSTATUS macro.

        int status = std::system("ls -l >test.txt"); // execute the UNIX command "ls -l >test.txt"
        std::cout << std::ifstream("test.txt").rdbuf();
        std::cout << "Exit code: " << WEXITSTATUS(status) << std::endl;
    

提交回复
热议问题