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的最后邊。
代碼如下:
#include <unistd.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
int aflag=0, bflag=0, cflag=0;
int ch;
printf("optind:%d,opterr:%dn",optind,opterr);
printf("--------------------------n");
while ((ch = getopt(argc, argv, "ab:c:de::")) != -1)
{
printf("optind: %d,argc:%d,argv[%d]:%sn", optind,argc,optind,argv[optind]);
switch (ch) {
case 'a':
printf("HAVE option: -ann");
break;
case 'b':
printf("HAVE option: -bn");
printf("The argument of -b is %snn", optarg);
break;
case 'c':
printf("HAVE option: -cn");
printf("The argument of -c is %snn", optarg);
break;
case 'd':
printf("HAVE option: -dn");
break;
case 'e':
printf("HAVE option: -en");
printf("The argument of -e is %snn", optarg);
break;
case '?':
printf("Unknown option: %cn",(char)optopt);
break;
}
}
printf("----------------------------n");
printf("optind=%d,argv[%d]=%sn",optind,optind,argv[optind]);
}
執行結果:
shiqi@wjl-desktop:~/code$ vim getopt.c
shiqi@wjl-desktop:~/code$ gcc getopt.c -o g
shiqi@wjl-desktop:~/code$ ./g file1 -a -b -c code -d file2 -e file3
optind:1,opterr:1
--------------------------
optind: 3,argc:10,argv[3]:-b
HAVE option: -a
optind: 5,argc:10,argv[5]:code
HAVE option: -b
The argument of -b is -c
optind: 7,argc:10,argv[7]:file2
HAVE option: -d
optind: 9,argc:10,argv[9]:file3
HAVE option: -e
The argument of -e is (null)
----------------------------
optind=6,argv[6]=file1 //while循環執行完后,optind=6