部分轉自 http://blog.csdn.net/huangxiaohu_coder/article/details/7475156 感謝原做者。數組
1. getopt函數聲明函數
1 #include <unistd.h> 2 3 int getopt(int argc, char * const argv[], const char *optstring); 4 5 extern char *optarg; 6 extern int optind, opterr, optopt;
該函數的argc和argv參數一般直接從main()的參數直接傳遞而來。optstring是選項字母組成的字串。若是該字串裏的任一字符後面有冒號,那麼這個選項就要求有選項參數。spa
當給定getopt()命令參數的數量 (argc
)、指向這些參數的數組 (argv
) 和選項字串 (optstring
) 後,getopt()
將返回第一個選項,並設置一些全局變量。使用相同的參數再次調用該函數時,它將返回下一個選項,並設置相應的全局變量。若是再也不有可識別的選項,將返回 -1
,此任務就完成了。.net
getopt()
所設置的全局變量包括:code
char *optarg
——當前選項參數字串(若是有)。int optind
——argv的當前索引值。當getopt()在while循環中使用時,循環結束後,剩下的字串視爲操做數,在argv[optind]至argv[argc-1]中能夠找到。int optopt
——當發現無效選項字符之時,getopt()函數或返回'?'字符,或返回':'字符,而且optopt包含了所發現的無效選項字符。2. 示例代碼blog
1 #include <unistd.h> 2 #include <stdio.h> 3 4 int main(int argc, char *argv[]) 5 { 6 int res; 7 char *optstr = "mnc:"; 8 while ((res = getopt(argc, argv, optstr)) != -1) 9 { 10 switch (res) 11 { 12 case 'm': 13 printf("opt is %c\n", (char)res); 14 break; 15 case 'n': 16 printf("opt is %c\n", (char)res); 17 break; 18 case 'c': 19 printf("opt is %s\n", optarg); 20 break; 21 default: 22 printf("unknown option\n"); 23 } 24 } 25 exit(0); 26 27 }
輸出:索引
root@virtual:~/codetest# ./a.out -mnc third_opt opt is m opt is n opt is third_opt root@virtual:~/codetest#