使用getopt函數來分析命令列參數

Reference:
http://www.gnu.org/s/hello/manual/libc/Getopt.html
http://checko.blogspot.com/2006/02/c-function-getopt.html

       最近想寫個程式來處理一些事情,但這個程式需要有一些選項來讓自己在不同的需求下,只要輸入不同的選項就能處理不同的事。之前再寫的話都是直接抓argv裏面的字串來做判斷,但是想一想還真麻煩,所幸在網路上看到有getopt的function可以用,讓自己可以少寫很多東西。以下是範例:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h> 
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
 
int main(int argc, char **argv)
{
    int c,i;
    char *optionValue = NULL;
    while((c = getopt(argc,argv,"a:bc:")) != -1)
    {
        switch(c)
        {
            case 'a':
                optionValue = optarg;
                printf("Option -a\n");
                printf("Option a value = %s, optind = %d\n",optarg,optind);
            break;
            case 'b':
                printf("Option -b\n");
                printf("optind = %d\n",optind);
            break;
            case 'c':
                printf("Option -c\n");
                optionValue = optarg;
                printf("Option C value = %s, optind = %d\n",optarg,optind);
            break;
            case '?':
                printf("Option ?\n");
                printf("Using getopt -a value -b -c value\n");
            break;
            default:
            abort();
            break;
        }
    }
    printf("\nAll Option :\n");
    for(i=0;i<optind;i++)
        printf("opt[%d]: %s\n",i,argv[i]);
 
    return 0;
}
 


輸出結果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
./getopt -a foo -bc xo
 
Option -a
Option a value = foo, optind = 3
Option -b
optind = 3
Option -c
Option C value = xo, optind = 5
 
All Option :
opt[0]: ./getopt
opt[1]: -a
opt[2]: foo
opt[3]: -bc
opt[4]: xo


當然上面的程式只能夠用單一字母來做選項,所以必須用另一個function來可以用字串來做選項,那就是getopt_long,以下連結有範例。http://www.gnu.org/s/hello/manual/libc/Getopt-Long-Option-Example.html#Getopt-Long-Option-Example


留言

熱門文章