当两个不同的参数中有空格时,C system() 不起作用

新手上路,请多包涵

我正在尝试使用 system() 运行需要一些参数的 .exe。

如果 .exe 的路径和传入参数的文件的路径中有空格,我会收到以下错误:

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

这是生成该错误的代码:

 #include <stdlib.h>
#include <conio.h>

int main (){
    system("\"C:\\Users\\Adam\\Desktop\\pdftotext\" -layout \"C:\\Users\\Adam\\Desktop\\week 4.pdf\"");
    _getch();
}

如果“pdftotext”的路径不使用引号(我需要它们,因为有时目录会有空格),一切正常。此外,如果我将“system()”中的内容放入字符串中并输出,然后将其复制到实际的命令窗口中,它就可以工作。

我想也许我可以使用这样的东西链接一些命令:

 cd C:\Users\Adam\Desktop;
pdftotext -layout "week 4.pdf"

所以我已经在正确的目录中,但我不知道如何在同一个 system() 函数中使用多个命令。

谁能告诉我为什么我的命令不起作用,或者我想到的第二种方法是否有效?

编辑: 看起来我需要一组额外的引号,因为 system() 将它的参数传递给 cmd /k,所以它需要在引号中。我在这里找到了它:

C++:如何让我的程序打开一个带有可选参数的 .exe

所以我会投票关闭重复,因为即使我们没有收到相同的错误消息,问题也非常接近,谢谢!

原文由 Adam Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 617
1 个回答

system() cmd /C command 命令。这是来自 cmd doc的引用:

 If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:

    1.  If all of the following conditions are met, then quote characters
        on the command line are preserved:

        - no /S switch
        - exactly two quote characters
        - no special characters between the two quote characters,
          where special is one of: &<>()@^|
        - there are one or more whitespace characters between the
          two quote characters
        - the string between the two quote characters is the name
          of an executable file.

    2.  Otherwise, old behavior is to see if the first character is
        a quote character and if so, strip the leading character and
        remove the last quote character on the command line, preserving
        any text after the last quote character.

您似乎遇到了案例 2,而 cmd 认为整个字符串 C:\Users\Adam\Desktop\pdftotext" -layout "C:\Users\Adam\Desktop\week 4.pdf (即没有第一个和最后一个引号)是可执行文件的名称。

所以解决方案是将整个命令用额外的引号括起来:

 //system("\"D:\\test\" nospaces \"text with spaces\"");//gives same error as you're getting
system("\"\"D:\\test\" nospaces \"text with spaces\"\""); //ok, works

这很奇怪。我认为添加 /S 也是一个好主意,只是为了确保它总是按案例 2 解析字符串:

 system("cmd /S /C \"\"D:\\test\" nospaces \"text with spaces\"\""); //also works

原文由 hamstergene 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题