I can't figure how to have cmd.exe not interpret something like %PATH%
as an environment variable.
Given this program:
#include<stdio.h>
#include<windows.h>
int main(int argc, char *argv[])
{
int i;
printf("cmd line: %s\n", GetCommandLine());
for (i = 0; i < argc; i++) {
printf("%d: %s\n", i开发者_开发问答, argv[i]);
}
return 0;
}
I have these different outputs according to the position of the arguments:
>args "k\" o" "^%PATH^%"
cmd line: args "k\" o" "%PATH%"
0: args
1: k" o
2: %PATH%
>args "^%PATH^%" "k\" o"
cmd line: args "^%PATH^%" "k\" o"
0: args
1: ^%PATH^%
2: k" o
I guess it's because cmd.exe doesn't recognize the escaped \"
and sees the escaped double quote as closing the first, leaving in the first case %PATH%
unquoted. I say this, because if I don't quote the argument, it always works:
>args ^%PATH^% "k\" o"
cmd line: args %PATH% "k\" o"
0: args
1: %PATH%
2: k" o
but then I can have no spaces...
This is apparently possible by also escaping the quotes:
>args ^"oo \\\^" \^" ^%PATH^%^"
cmd line: args "oo \\\" \" %PATH%"
0: args
1: oo \" " %PATH%
So from what I gather these are the escaping rules:
For the C runtime/CommandLineToArgvW
tokenization
- Replace
\"
→\\"
- Replace
"
→\"
- Surround the result with double quotes.
For cmd.exe parsing
- Escape the characters <, >, |, &, ^, ", %, ^ and SPACE by adding the escape character ^.
- Escaping spaces is unnecessary is the C runtime escape rules were applied and cmd.exe is only to pass the arguments to an another program.
These transformations should be applied in order, first the C runtime rules and then the cmd.exe rules.
If writing something to be interpreted directly by cmd.exe, only the cmd.exe rules should be applied; if starting a program in a way that doesn't involve cmd.exe, only the C runtime rules should be applied.
Here's an example of an argument interpreted directly by cmd.exe, which writes to a file named oo %PATH%
:
echo test > oo^ ^%PATH^%
精彩评论