[英]How do you call a batch file with an argument that has quotes, using system()
For example, in the command line this works (the 1st argument has quotes but the 2nd argument doesn't): "test.bat" "a" b ie it know that "a" is the 1st argument and b is the second例如,在命令行中这是有效的(第一个参数有引号,但第二个参数没有):“test.bat”“a”b 即它知道“a”是第一个参数而 b 是第二个
but using system() it doesn't work: system("test.bat" "a" b)
但是使用 system() 它不起作用: system("test.bat" "a" b)
this also doesn't work: system("test.bat" \\"a\\" b)
这也不起作用: system("test.bat" \\"a\\" b)
This is gonna be simplest if we use a raw string literal.如果我们使用原始字符串文字,这将是最简单的。 A raw string literal is a way of writing a string in c++ where nothing gets escaped.原始字符串文字是在 c++ 中编写字符串的一种方式,其中没有任何转义。 Let's look at an example:让我们看一个例子:
char const* myCommand = R"(test.bat "a" b)";
The R
at the beginning indicates that it's a raw string literal, and if you call system(myCommand)
, it will be exactly equivalent to typing开头的R
表示它是原始字符串文字,如果您调用system(myCommand)
,它将完全等同于键入
$ test.bat "a" b
into the command line.进入命令行。 Now, suppose you want to escape the quotes on the command line:现在,假设您想转义命令行上的引号:
$ test.bat \"a\" b
With a raw string literal, this is simple:使用原始字符串文字,这很简单:
char const* myCommand = R"(test.bat \"a\" b)";
system(myCommand);
Or, alternatively:或者,或者:
system(R"(test.bat \"a\" b)");
Hope this helps!希望这可以帮助!
A bit more info on raw string literals: Raw string literals are a great feature, and they basically allow you to copy+paste any text directly into your program.关于原始字符串文字的更多信息:原始字符串文字是一个很棒的功能,它们基本上允许您将任何文本直接复制并粘贴到您的程序中。 They begin with R
, followed by a quote and a parenthesis.它们以R
开头,后跟引号和括号。 Only the stuff inside the parenthesis gets included.只包含括号内的内容。 Examples:例子:
using std::string;
string a = R"(Hello)"; // a == "Hello"
Begin and end with "raw":以“raw”开头和结尾:
string b = R"raw(Hello)raw"; // b == "Hello"
Begin and end with "foo"以“foo”开头和结尾
string c = R"foo(Hello)foo"; // c == "Hello"
Begin and end with "x"以“x”开头和结尾
string d = R"x(Hello)x"; // d == "Hello"
The important thing is that we begin and end the literal with the same string of letters (called the delimiter), followed by the parenthesis.重要的是我们用相同的字母字符串(称为分隔符)开始和结束文字,后跟括号。 This ensures we never have a reason to escape something inside the raw string literal, because we can always change the delimiter so that it's not something found inside the string.这确保我们永远没有理由转义原始字符串文字中的某些内容,因为我们始终可以更改分隔符,以便在字符串中找不到它。
我现在让它工作:
system(R"(C:\"to erase\test.bat" "a")");
I found the answer: system("test.bat" ""a"" b);
我找到了答案: system("test.bat" ""a"" b);
or more precisely: system("\\"test.bat\\" ""a"" b");
或更准确地说: system("\\"test.bat\\" ""a"" b");
So the answer is to escape the quotes with a double quote所以答案是用双引号转义引号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.