Alternative to system() and _popen() on Windows

winapi

This is related to: How do I read the results of a system() call in C++?

I am trying to do the exact the same thing only that my program needs to pass 'multiple parameters with spaces' to the command. I need the command line output and the exit code from the process.

Example: An example with Textpad. The application I'm really using prints stuff on stdout.


string command1 = "\"C:\Program Files\TextPad 5\Textpad.exe\" C:\readme0.txt";
string command2 = "\"C:\Program Files\TextPad 5\Textpad.exe\" \"C:\read me2.txt\"";
cout << system(command1.c_str()) << endl;
cout << system(command1.c_str()) << endl;


Output:

0
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.

1

The first call to system passes and second one fails with the error above. _popen in Windows works similarly on Windows so no help there. I can easily do this on Linux as I can escape spaces in the parameters without having to use quotes.

An alternative is to write a huge chunk of non-cross-platform code as listed here:
http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx

But in case I want to avoid that, are there any alternatives to system() and _popen() on Windows?

Thanks!

Best Solution

The lowest level Windows API function used by _popen() and system() is CreateProcess().

However CreateProcess() is not that simple to use - especially when you want to get the process'es output or write to the process'es input.

CreateProcess() will definitely work with file names that contain space characters (as long as they are written in quotation marks the way you did that).

Related Question