最近用到了getopt()這個函數,對它進行了一些了解。這篇博文還是寫的非常清楚的。值得學習。最近在改進一個開源項目,希望自己能靜下心好好分析代碼。
---------------------------------------------------------------------------------------------------
getopt被用來解析命令行選項參數。
#include <unistd.h>
extern char *optarg; //選項的參數指針
extern int optind, //下一次調用getopt的時,從optind存儲的位置處重新開始檢查選項。
extern int opterr, //當opterr=0時,getopt不向stderr輸出錯誤信息。
extern int optopt; //當命令行選項字符不包括在optstring中或者選項缺少必要的參數時,該選項存儲在optopt 中,getopt返回'?’、
int getopt(int argc, char * const argv[], const char *optstring);
調用一次,返回一個選項。 在命令行選項參數再也檢查不到optstring中包含的選項時,返回-1,同時optind儲存第一個不包含選項的命令行參數。
首先說一下什麼是選項,什麼是參數。
1.單個字符,表示選項,
2.單個字符後接一個冒號:表示該選項後必須跟一個參數。參數緊跟在選項後或者以空格隔開。該參數的指針賦給optarg。
3 單個字符後跟兩個冒號,表示該選項後必須跟一個參數。參數必須緊跟在選項後不能以空格隔開。該參數的指針賦給optarg。(這個特性是GNU的擴張)。
例如gcc -g -o test test.c ,其中g和o表示選項,test為選項o的參數。
上面是getopt()函數的基本含義,大家懂得了這些之後,我們一個例子加深一下理解。
例如我們這樣調用getopt(argc, argv, "ab:c:de::");
從上面我們可以知道,選項a,d沒有參數,選項b,c有一個參數,選項e有有一個參數且必須緊跟在選項後不能以空格隔開。getopt首先掃描argv[1]到argv[argc-1],並將選項及參數依次放到argv數組的最左邊,非選項參數依次放到argv的最後邊。
1 #include <unistd.h>
2 #include <stdio.h>
3 int main(int argc, char * argv[])
4 {
5 int aflag=0, bflag=0, cflag=0;
6 int ch;
7 printf("optind:%d,opterr:%d\n",optind,opterr);
8 printf("--------------------------\n");
9 while ((ch = getopt(argc, argv, "ab:c:de::")) != -1)
10 {
11 printf("optind: %d,argc:%d,argv[%d]:%s\n", optind,argc,optind,argv[optind]);
12 switch (ch) {
13 case 'a':
14 printf("HAVE option: -a\n\n");
15
16 break;
17 case 'b':
18 printf("HAVE option: -b\n");
19
20 printf("The argument of -b is %s\n\n", optarg);
21 break;
22 case 'c':
23 printf("HAVE option: -c\n");
24 printf("The argument of -c is %s\n\n", optarg);
25
26 break;
27 case 'd':
28 printf("HAVE option: -d\n");
29 break;
30 case 'e':
31 printf("HAVE option: -e\n");
32 printf("The argument of -e is %s\n\n", optarg);
33 break;
34
35 case '?':
36 printf("Unknown option: %c\n",(char)optopt);
37 break;
38 }
39 }
40 printf("----------------------------\n");
41 printf("optind=%d,argv[%d]=%s\n",optind,optind,argv[optind]);
42 }
執行結果: