Home > Backend Development > C++ > body text

How to Execute Programs with Parameters Containing Spaces Using `system()` in C ?

Patricia Arquette
Release: 2024-11-02 02:37:30
Original
941 people have browsed it

How to Execute Programs with Parameters Containing Spaces Using `system()` in C  ?

C system() call fails with parameters containing spaces

When using system() to execute a program that takes parameters containing spaces, a common error encountered is:

The filename, directory name, or volume label syntax is incorrect.
Copy after login

This occurs when both the executable path and parameter paths contain spaces.

For example, the following code:

<code class="cpp">#include <stdlib.h>
#include <conio.h>

int main() {
  system("\"C:\Users\Adam\Desktop\pdftotext\" -layout \"C:\Users\Adam\Desktop\week 4.pdf\"");
  _getch();
}</code>
Copy after login

generates the error message due to the presence of spaces in the "pdftotext" path and the PDF file path.

This problem arises because system() passes its arguments to cmd /k, which interprets the first quote character as the beginning of the executable name and the second quote character as the end of the executable name. As a result, the command line is parsed incorrectly, leading to the error.

To solve this issue, the command can be enclosed in double quotes:

<code class="cpp">system("\"\"C:\Users\Adam\Desktop\pdftotext\" -layout \"C:\Users\Adam\Desktop\week 4.pdf\"\"");</code>
Copy after login

Alternatively, cmd /S can be used to force the command line to be interpreted strictly without special parsing rules:

<code class="cpp">system("cmd /S /C \"\"C:\Users\Adam\Desktop\pdftotext\" -layout \"C:\Users\Adam\Desktop\week 4.pdf\"\"");</code>
Copy after login

By applying these solutions, the system() call can successfully execute the program with parameters that contain spaces.

The above is the detailed content of How to Execute Programs with Parameters Containing Spaces Using `system()` in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!