预注:命令行(commandline)被操做系统的命令分析器(/日后简称cmdlineparser)分解到命令参数argv[0]…[n],这里,commandline是入料,argv是出品.html
Microsoft C/C++ 程序引导代码使用如下规则解析操做系统命令行中给出的参数:ios
以上这段文字翻译自http://msdn.microsoft.com/en-us/library/17w5ykft.aspx ,主要仍是本人理解的语义。原文以下算法
Microsoft C/C++ startup code uses the following rules when interpreting arguments given on the operating system command line:浏览器
示例sass
下面的过程演示如何经过命令行参数:less
// command_line_arguments.cpp // compile with: /EHsc #include < iostream > using namespace std; int main( int argc, // Number of strings in array argv char * argv[], // Array of command-line argument strings char * envp[] ) // Array of environment variable strings { int count; // Display each command-line argument. cout << " \nCommand-line arguments:\n " ; for ( count = 0 ; count < argc; count ++ ) cout << " argv[ " << count << " ] " << argv[count] << " \n " ; }
下表显示示例输入,并预期的输出,演示上面的规则列表
ide
命令行输入 | argv [1] | argv [2] | argv [3]
-----------------|-------------|--------------|---------------
"abc" d e | abc | d | e
a\\b d"e f"g h | a\\b | de fg | h
a\\\"b c d | a\"b | c | d
a\\\\"b c" d e | a\\b c | d | ethis
/////////////////////////////////////////////////spa
又:操作系统
有关连在一块儿的多个双引号的解析,很是狗血,请参考讨论
尤为是 http://www.daviddeley.com/autohotkey/parameters/parameters.htm 中的这个补充说明:
及其算法:
5.10 The Microsoft C/C++ Command Line Parameter Parsing Algorithm
The following algorithm was reverse engineered by disassembling a small C program compiled using Microsoft Visual C++ and examining the disassembled code:
1. Parse off parameter 0 (the program filename)
* The entire parameter may be enclosed in double quotes (it handles double quoted parts)
(Double quotes are necessary if there are any spaces or tabs in the parameter)
* There is no special processing of backslashes (\)
2. Parse off next parameter:
a. Skip over multiple spaces/tabs between parameters
LOOP
b. Count the backslashes (\). Let m = number of backslashes. (m may be zero.)
c. IF next character following m backslashes is a double quote:
If m is even (or zero)
if currently in a double quoted part
IF next character is also a "
move to next character (the 2nd ". This character will be added to the parameter.)
ELSE
set flag to not add this " character to the parameter
ENDIF
toggle double quoted part flag
else
set flag to not add this " character to the parameter
endif
Endif
m = m/2 (floor divide e.g. 0/2=0, 1/2=0, 2/2=1, 3/2=1, 4/2=2, 5/2=2, etc.)
ENDIF
d. add m backslashes
e. add this character to our parameter
ENDLOOP