Ada*_*ith 13 c++ windows system
我正在尝试使用system()运行需要一些参数的.exe.
如果.exe的路径中存在空格并且在参数中传递的文件的路径中,我会收到以下错误:
The filename, directory name, or volume label syntax is incorrect.
Run Code Online (Sandbox Code Playgroud)
以下是生成该错误的代码:
#include <stdlib.h>
#include <conio.h>
int main (){
system("\"C:\\Users\\Adam\\Desktop\\pdftotext\" -layout \"C:\\Users\\Adam\\Desktop\\week 4.pdf\"");
_getch();
}
Run Code Online (Sandbox Code Playgroud)
如果"pdftotext"的路径不使用引号(我需要它们,因为有时目录会有空格),一切正常.另外,如果我将"system()"中的内容放在字符串中并输出它并将其复制到实际的命令窗口中,它就可以工作.
我想也许我可以用这样的东西链接一些命令:
cd C:\Users\Adam\Desktop;
pdftotext -layout "week 4.pdf"
Run Code Online (Sandbox Code Playgroud)
所以我已经在正确的目录中,但我不知道如何在同一个system()函数中使用多个命令.
任何人都可以告诉我为什么我的命令不起作用或者我想到的第二种方式是否有效?
编辑:看起来我需要一组额外的引号,因为system()将其参数传递给cmd/k,所以它需要在引号中.我在这里找到了:
因此,即使我们没有得到相同的错误消息,我也会投票关闭,因为问题非常接近,谢谢!
ham*_*ene 28
system()运行命令为cmd /C command.这是来自cmddoc 的引用:
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.
Run Code Online (Sandbox Code Playgroud)
看来你正在点击案例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
Run Code Online (Sandbox Code Playgroud)
这非常奇怪.我认为添加/Sjust以确保它总是通过案例2解析字符串也是一个好主意:
system("cmd /S /C \"\"D:\\test\" nospaces \"text with spaces\"\""); //also works
Run Code Online (Sandbox Code Playgroud)
我来这里寻找答案,这是我想出的代码(我这么明确是为了下一个人维护我的代码):
std::stringstream ss;
std::string pathOfCommand;
std::string pathOfInputFile;
// some code to set values for paths
ss << "\""; // command opening quote
ss << "\"" << pathOfCommand << "\" "; // Quoted binary (could have spaces)
ss << "\"" << pathOfInputFile << "\""; // Quoted input (could have spaces)
ss << "\""; // command closing quote
system( ss.str().c_str() ); // Execute the command
Run Code Online (Sandbox Code Playgroud)
它解决了我所有的问题。