2013-03-11 48 views
0

是否有使用的getopt函數解析方式:的Getopt結合參數

./prog -L -U 

的一樣:

./prog -LU  

這是我嘗試(不工作):

while ((c = getopt(argc, argv, "LU")) != -1) { 
    switch (c) { 
    case 'L': 
     // L catch 
     break; 
    case 'U': 
     // U catch 
     break; 
    default: 
     return; 
    } 
} 

在這個簡單的例子只有2個參數,但在我的項目中需要6個參數的所有組合。例如:-L-LURGHX-LU -RG -H等 可以getopt()處理?或者我必須編寫複雜的解析器來做到這一點?

+0

'getopt'應該看到你的兩個例子中完全相同的方式...查看第二和第三個例子在這裏的文檔:http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html#Example-of-Getopt。 – 2013-03-11 01:16:24

回答

2

節省缺少的支柱,你的代碼工作正常,我:

#include <stdio.h> 
#include <unistd.h> 

int main(int argc, char **argv) { 
    int c; 
    while ((c = getopt(argc, argv, "LU")) != -1) { 
     switch (c) { 
     case 'L': 
      // L catch 
      printf("L\n"); 
      break; 
     case 'U': 
      // U catch 
      printf("U\n"); 
      break; 
     default: 
      break; 
     } 
    } 
    return 0; 
} 
$ ./a.out -LU 
L 
U 
$ ./a.out -L 
L 
$ 
2

getoptdoes seem capable of handling itand it does

這裏是顯示用的參數不同組合一下這個程序打印一些例子:

% testopt 
aflag = 0, bflag = 0, cvalue = (null) 

% testopt -a -b 
aflag = 1, bflag = 1, cvalue = (null) 

% testopt -ab 
aflag = 1, bflag = 1, cvalue = (null) 
2

它的行爲完全一樣,你想:

#include <stdio.h> 
#include <unistd.h> 

int main(int argc, char** argv) 
{ 
    int c; 

    while ((c = getopt(argc, argv, "LU")) != -1) { 
     switch (c) { 
     case 'L': 
      puts("'L' option"); 
      break; 
     case 'U': 
      // U catch 
      puts("'U' option"); 
      break; 
     default: 
      puts("shouldn't get here"); 
      break; 
     } 
    } 

    return 0; 
} 

並對其進行測試:

[email protected]:~$ gcc -o test test.c 
[email protected]:~$ ./test -LU 
'L' option 
'U' option 
[email protected]:~$ ./test -L -U 
'L' option 
'U' option 

getopt() is a POSIX standard function下面的POSIX "Utiltiy Syntax Guidelines",其中包括以下內容:

準則5:落後時一個分組 沒有選項參數選項應該被接受「 - 」分隔符。