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 just execute a command. Here's an example of what I'm looking for:
std::string result = system( "./some_command" ) ;
I need to run an arbitrary command and get it's output. I've looked at Boost.org but I have not found anything that will give me what I need.
I'd use popen() (++waqas).
But sometimes you need reading and writing...
Seems like nobody does things the hard way any more.
(Assuming a Unix/Linux/Mac environment, or perhaps Windows with a POSIX compatibility layer...)
You also might want to play around with select() and non-blocking reads.
Pre-C++11 version:
Replace
popen
andpclose
with_popen
and_pclose
for Windows.For Windows
popen
also works, but it opens up console window - which quickly flashes over your UI application. If you want to be a professional, it's better to disable this "flashing" (Especially if end-user can cancel it).So here is my own version for Windows:
(This code partially recombined from ideas written in codeproject and MSDN samples)
You can use the Boost.Process library. It's not officially part of boost though. I've seen it work nicely for others. Unfortunately, boost.process progress apparently has been stalled. pstreams is another (apparently active) project. Certainly worth a try I would say - but it's only for posix compatible operation systems.
This might be a portable solution. Follows standards.
I couldn't figure out why popen/pclose is missing from Codeblocks/MinGW. So I worked around the problem by using CreateProcess() and CreatePipe() instead. Here's the solution that worked for me: