Shedex
Shedex

Reputation: 131

Start a program with a path containing spaces given

I have a string for a command, e.g.: start C:\Users\...\test application.exe with a path that has spaces.
Now I want to use the system() function to start it up:

system(command.c_str());

But the problem is, it doesnt start because the path contains a space. What do I have to do to fix this?

Upvotes: 1

Views: 412

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

What do I have to do to fix this?

The first thing you need to know is that system() uses the shell to execute the command, and the shell wants you to enclose the program path with "", if the path contains a space.

Using the current C++ standard, the easiest way to fix is to use a raw string literal:

std::string command = R"("C:\Users\test application.exe")";
system(command.c_str());

Otherwise (and for older C++ standards), you need to escape all of the special characters:

std::string command = "(\"C:\\Users\\test application.exe\")";
                     // ^   ^      ^                     ^

Upvotes: 5

Related Questions