c: getopt

這幾天看了一份測試camera的user layer code,看到了關於getopt這個API,也就順便了解一下他的詳細內容。

使用getopt()時必須先include unistd.h這個header file.

在使用getopt()的時候有幾個變數可以使用,似乎是被宣告成global的樣子。

先附上自己寫的測試程式getopt_practice.c:

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

int main(int argc, char* argv[]) {
    char ch;
    opterr = 0;
  
    while((ch = getopt(argc, argv, "a:b:c::d")) != -1) {
printf("optind = %d\n", optind);
printf("optopt = %c\n", optopt);
        switch(ch)
        {
         case 'a':
                 printf("option: %c \nother arguement: %s\n", ch, optarg);
                        break;
                case 'b':
                 printf("option: %c \nother arguement: %s\n", ch, optarg);
                        break;
                case 'c':
               printf("option: %c \nother arguement: %s\n", ch, optarg);
                        break;
                case 'd':
                        printf("option: %c \nother arguement: %s\n", ch, optarg);
                        break;
                default:
                        printf("unkonw parameter\n");
                        break;
        }        
    }
    return 0;
}
測試環境為ubuntu 10.04 kernel 2.6.31-22-generic


以下說明剛剛提到的變數:
1. opterr : 型態int,此變數若是非零,會在接收到unknown option character時印出標準的錯誤訊息。
2. optopt : 型態int,當出現unknown option character的時候,用來儲存該unknown option character。列如執行./getopt_practice -z,該參數-z為unknown option character,則optopt的值等於z。
3. optind : 型態int,用來標記argv array中下一個element的index,若輸入./getopt_practice -a foo,此時optind = 3。
4. optarg : 型態char*,用來儲存option character接受的arguement,./getopt_practice -a foo,此時-a為option character,foo為-a接受的arguement,所以optarg = foo。

getopt()的參數有三個,前兩個即為main所使用的argc和argv,第三個參數為所要接受的option character和相對應的accept argument。

範例中a:b:c::d:,
a:表示option character為a且接受一個argument。
c::表示option character為c且接受一個argument,該argument也可以省略不要。
d表示option character為d,不需要arguement。

以上
參考:http://www.gnu.org/s/libc/manual/html_code/Using-Getopt.html
若有侵犯任何版權煩請告知,我會立刻刪除,感謝。

留言

熱門文章