C程序从一个C程序,我试图建立,将在系统调用中使用的字符串中:系统调用的问题在Windows
char myCommands[128];
...
/* packing myCommands string */
..
system(myCommands);
的命令字符串来执行这样的容貌:
setEnvVars.bat & xCmd.exe ...command-paramters...
如果“... command-parameters ...”不包含任何引号字符,则一切正常,语句成功。
如果 “...命令参数......” 包含任何引号字符我得到这个错误:
The filename, directory name, or volume label syntax is incorrect.
例子:
setEnvVars.bat & xCmd.exe -e "my params with spaces"
另一个奇怪的事情,如果我把myCommands字符串逐字地转换成* .bat文件,引号和所有它完美地工作。
什么是“系统(...)”与众不同?
== OK,更多详细信息==
我有一个简单的程序来演示这个问题。这个版本确实工作:
#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文件”
(对人是具有路径名称空间,想法是一个好主意痘。)
(它使用单引号不会改变的行为。)
尝试“用'\'”''替换,看如果它不工作得更好。 – 2013-02-22 22:14:33
我建立的命令字符串时所使用的\”转义序列。它并没有帮助。 – 2013-02-22 22:23:00
我认为你正在寻找与C运行时库执行系统()''的一个已知的问题。你可以建立命令字符串(包括领先的'CMD.EXE/C')自己和使用的CreateProcess? – 2013-02-23 01:52:36