这里说的解析命令行参数,并不是说类似getopt的解析函数,而是说win平台的命令行参数是按什么规则传入程序的。前两天我写了个命令行的程序,程序对根目录的处理总是有问题。经过跟踪,发现当输入参数是(”D:\”)的时候,实际程序读到的参数是(D:”)。在路径的两端加上引号,是为了让路径名称中出现空格的时候不会作为参数分隔符处理。可是显然最后一个引号被\转移为 ” 了。 求助于MSDN,终于找到了命令行解析的规则,原文链接:http://msdn2.microsoft.com/en-us/library/aa243471.aspx。这里我做一下翻译: 参数用空格或者TAB进行分割。 一个字符串若被两个双引号包含,则即使其中包含空格或TAB字符也会被视为一个参数。被引起来的字符串可以嵌入参数内。 字符串中存在的双引号可以通过前置反斜杠进行转义。 反斜杠会被解释成单个字符,除非后面紧接着一个双引号。 如果偶数个反斜杠后面跟随一个双引号,每对反斜杠放一个反斜杠到参数中,双引号被解释为一个字符串界定符。 如果奇数个反斜杠后面跟随一个双引号,每对反斜杠放一个反斜杠到argv数组中,双引号则被剩下的反斜杠转义放入到argv中,而不会作文字符串界定符。
Parsing C Command-Line Arguments Microsoft Specific —> Microsoft C startup code uses the following rules when interpreting arguments given on the operating system command line: Arguments are delimited by white space, which is either a space or a tab. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. Note that the caret (^) is not recognized as an escape character or delimiter. A double quotation mark preceded by a backslash, \", is interpreted as a literal double quotation mark ("). Backslashes are interpreted literally, unless they immediately precede a double quotation mark. If an even number of backslashes is followed by a double quotation mark, then one backslash (\) is placed in the argv array for every pair of backslashes (\\), and the double quotation mark (") is interpreted as a string delimiter. If an odd number of backslashes is followed by a double quotation mark, then one backslash (\) is placed in the argv array for every pair of backslashes (\\) and the double quotation mark is interpreted as an escape sequence by the remaining backslash, causing a literal double quotation mark (") to be placed in argv.
欢迎光临 批处理之家 (http://www.bathome.net/) | Powered by Discuz! 7.2 |