Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters with spaces via cstdlib system

Tags:

c++

std

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

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

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

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

the console prints out that c:\first is not any valid command. It's probably common mistake and has simple solution, but I have been unable to find any. Thx for any help.

like image 430
buchtak Avatar asked Nov 15 '22 10:11

buchtak


1 Answers

Instead of std::system(), you should use the _wspawnv function from the Windows API. Use _wspawnvp if you want to search for the program in PATH, rather than specifying a 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 could also use _spawnv / _spawnvp if you are 100% sure that your input filename will never, ever contain anything else than ASCII.

like image 76
Krzysztof Kosiński Avatar answered Dec 19 '22 18:12

Krzysztof Kosiński