How to pass parameters with spaces through cstdlib system

I have this console application for Windows that takes a file, performs some calculations and then writes the output to the specified file. The input is specified in the format "app.exe -input fullfilename". I need to call this application from my C ++ program, but I have a problem with spaces in the file path. When I call the application directly from cmd.exe, typing (without specifying the output file for clarity)

"c:\first path\app.exe" -input "c:\second path\input.file"

everything works as expected. But, when I try to use the cstdlib function std :: system (), i.e.

std::system(" \"c:\\first path\\app.exe\" -input \"c:\\second path\\input.file\" ");

the console prints that c: \ first is not a valid command. This is probably a common mistake and has a simple solution, but I could not find it. Thanks for any help.

+5
source share
2 answers

Instead of std :: system () you should use the _wspawnv function from the Windows API. Use _wspawnvp if you want to search for a program in PATH rather than specifying the full path to it.

#include <stdio.h>
#include <wchar.h>
...
const WCHAR * app = L "C: \\ path to \\ first app.exe";
const WCHAR * argv [] = {app, L "-input", L "c: \\ second path \\ input file.txt"};
_wpspawnv (_P_WAIT, app, argv);

You can also use _spawnv / _spawnvp if you are 100% sure that your input file name will never contain anything other than ASCII.

+1
source

Do not try to put quotation marks in a call to std :: system (). Try the following:

std::system("c:\\first\\ path\\app.exe -input c:\\second\\ path\\input.file");
0
source

All Articles