I recently ran into a stupid problem using the system()
call in C++ on Windows platforms. For some strange reason, calls to system()
get passed through the cmd /c
command. This has some strange side effects if your paths contain spaces, and you try to use double quotes to allow those paths. From the cmd
documentation:
If /C or /K is specified, then the remainder of the command line after the switch is processed as a command line, where the following logic is used to process quote (") characters:
- If all of the following conditions are met, then quote characters on the command line are preserved:
- no /S switch
- exactly two quote characters
- no special characters between the two quote characters, where special is one of: &<>()@^|
- there are one or more whitespace characters between the two quote characters
- the string between the two quote characters is the name of an executable file
- Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character.
As you can see from this documentation, if you have any special characters or spaces in your call to system()
, you must wrap the entire command in an extra set of double quotes. Here's a working example:
string myCommand = "\"\"C:\\Some Path\\Here.exe\" -various -parameters\"";
int retVal = system(myCommand.c_str());
if (retVal != 0)
{
// Handle the error
}
Note that I've got a pair of quotes around the entire command, as well as a pair around the path with spaces. This requirement isn't apparent at first glance, but it's something to keep in mind if you ever find yourself in this situation.