1

在 C 程序中,我试图构建一个将在系统调用中使用的字符串:

   char myCommands[128];
   ...
   /* packing myCommands string */
   ..
   system(myCommands);

要执行的命令字符串如下所示:

  setEnvVars.bat & xCmd.exe ...command-paramters...

如果 "...command-parameters..." 不包含任何引号字符,则一切正常且语句成功。

如果 "...command-parameters..." 包含任何引号字符,我会收到此错误:

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

例子:

  setEnvVars.bat & xCmd.exe -e "my params with spaces"

另一个奇怪的事情是,如果我将 myCommands 字符串逐字逐句放入 *.bat 文件中,引号和所有它都可以正常工作。

“系统(...)”有什么不同?

==好的,更多细节==

我有一个简单的程序来演示这个问题。这个版本确实有效:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
    char cmdStr[1024];
    strcpy(cmdStr, "\"C:\\Windows\\system32\\cmd.exe\" /c echo nospaces & C:\\Windows\\system32\\cmd.exe /c echo moretext");
    printf("%s\n", cmdStr);
    system(cmdStr);
}

输出:

"C:\Windows\system32\cmd.exe" /c echo nospaces & C:\Windows\system32\cmd.exe /c echo moretext
nospaces
moretext

不起作用

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
    char cmdStr[1024];
    strcpy(cmdStr, "\"C:\\Windows\\system32\\cmd.exe\" /c echo nospaces & \"C:\\Windows\\system32\\cmd.exe\" /c echo moretext");
    printf("%s\n", cmdStr);
    system(cmdStr);
}

输出:

"C:\Windows\system32\cmd.exe" /c echo nospaces & "C:\Windows\system32\cmd.exe\" /c echo moretext
The filename, directory name, or volume label syntax is incorrect.

我认为它可能与“cmd.exe /S”选项有关,但尝试引入该选项不会改变行为。

cmd.exe 路径周围的引号不需要,因为没有空间,但在我的目标程序中,我试图允许所有安装路径,其中可能包括“C:\Program Files”

(认为​​路径名中有空格是个好主意的人的一个痘痘。)

(并且使用单引号不会改变行为。)

4

2 回答 2

1

敲了一阵子后,我放弃了“system(cmdLine)”方法,转而使用“CreateProcess”调用(这将在 Windows 下运行)。

使用 CreateProcess 我能够绕过整个环境变量问题,这就是导致我尝试使用“cmd1 & cmd2”语法的原因。

CreateProcess 将允许您将不同的环境传递给子进程。我能够弄清楚如何重写环境并将其传递给孩子。这巧妙地解决了我的问题。

我重写环境的代码可能有点麻烦,但它可以工作并且看起来相当健壮。

于 2013-03-01T22:20:14.450 回答
0

您可能知道,单引号用于一个字符,双引号用于多个......您还知道,您不能在字符串中包含双引号,或者它会退出字符串并添加它们(取决于情况).. .

尝试以下操作并告诉您会发生什么:

system("setEnvVars.bat & xCmd.exe -e 'my params with spaces'");

system("setEnvVars.bat & xCmd.exe -e \"my params with spaces\"");
于 2013-02-22T23:26:35.043 回答