預注:命令行(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