我试图通过使用system()来运行需要一些参数的.exe。
如果在.exepath中有一个空格,并且在传入参数的文件的path中,则会出现以下错误:
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”的path不使用引号(我需要它们,因为有时目录将有空格),一切工作正常。 另外,如果我把“system()”中的内容放在一个string中并输出,并将其复制到一个实际的命令窗口中,它就可以工作。
我想也许我可以使用这样的事情链接一些命令:
cd C:\Users\Adam\Desktop; pdftotext -layout "week 4.pdf"
所以我已经在正确的目录中,但我不知道如何在同一个system()函数中使用多个命令。
谁能告诉我为什么我的命令不起作用,或者如果我想到的第二种方式会起作用?
编辑:看起来像我需要一套额外的引号,因为system()传递它的参数到cmd / k,所以它需要在引号。 我在这里find了:
C ++:如何使我的程序打开一个带有可选参数的.exe文件
所以我会投票closures作为重复,因为即使我们没有得到相同的错误信息,问题是非常接近,谢谢!
system()
运行命令为cmd /C command
。 这里是从cmd
文档引用:
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