James Conrad James Conrad - 27 days ago 15
C++ Question

How do I get output of command in C++?

How do I get the output of a sub process and assign it to a variable. EG: assign the output of

wmic csproduct get uuid
returns a long string of characters in CMD, how would I run that command in C++ and assign it to a variable?

Answer

There are two main options for capturing the output of a process:

  • Redirect it to a file, then read the file later.
  • Use a pipe.

Pipes are not supported by the standard library, other than hidden behind the common stream abstraction. Effectively that means that a process A that creates a process B, can't communicate with B via pipes, unless platform-specific functionality for that is used. In Windows the scripting support, Windows Script Host, has direct functionality for the pipe approach, based on polling for output from B. At a much lower level you can use the CreateProcess API function. But it's not trivial to do.

With a temporary file as communication channel, and using only standard C++ functionality, you simply invoke program B via a command interpreter that can redirect B's output. This command interpreter and its syntax then constitutes the platform specific part. So even this approach is platform specific, but the C++ code as such is portable.


In Windows the standard command intepreter is cmd.exe, and it uses the ordinary Unix > syntax in order to redirect output of a program, so the command to be executed can be like

cmd /c "b.exe >tempfile"

You can execute such a command via C++ system. The system function already executes the specified command via a command intepreter, which in Windows is cmd.exe. And so the argument to system only needs to be

b.exe > tempfile

where tempfile is the name or full path to the file where you want the result.

You can create a fresh temporary filename via the tmpnam function.