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:
system("\"\""CMD\"" \""ARG1\"" \""ARG2\"\"");
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:
system("cmd /S /C \"\""CMD\"" \""ARG1\"" \""ARG2\"\"");
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3