Home >Backend Development >C++ >How to Execute External Applications with Arguments Containing Spaces Using C system()?
When invoking external applications through system() in C , it is crucial to ensure proper handling of arguments that contain spaces. If both the executable path and an argument contain spaces, an error may arise.
system() essentially executes the specified command using cmd /C. When processing the command line, cmd follows certain rules regarding quote characters. By default, it removes the leading and trailing quotes, treating the remaining string as an executable name.
To resolve this issue, the command must be enclosed in an additional set of double quotes:
<code class="cpp">system("\"\""CMD\"" \""ARG1\"" \""ARG2\"\"");</code>
This extra level of quoting ensures that cmd interprets each argument correctly, regardless of the presence of spaces.
An alternative approach involves using a batch file to execute the command with the desired arguments. The batch file can be created with the following contents:
cd PATH_TO_DIR EXECUTABLE_NAME ARG1 ARG2
By calling system() with this batch file name as the argument, the command will be executed as intended, even with arguments containing spaces.
To ensure compatibility with different environments and shell implementations, it is recommended to include the /S switch when using system(). This switch forces cmd to parse the command line strictly based on case 2 as described in the cmd documentation.
Example:
<code class="cpp">system("cmd /S /C \"\""CMD\"" \""ARG1\"" \""ARG2\"\"");</code>
The above is the detailed content of How to Execute External Applications with Arguments Containing Spaces Using C system()?. For more information, please follow other related articles on the PHP Chinese website!