1. 程式人生 > >命令行參數解析(getopt函數使用)

命令行參數解析(getopt函數使用)

const 給定 -s net 完成 get efault 全局 ons

部分轉自 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是選項字母組成的字串。如果該字串裏的任一字符後面有冒號,那麽這個選項就要求有選項參數。

當給定getopt()命令參數的數量 (argc)、指向這些參數的數組 (argv) 和選項字串 (optstring) 後,getopt() 將返回第一個選項,並設置一些全局變量。使用相同的參數再次調用該函數時,它將返回下一個選項,並設置相應的全局變量。如果不再有可識別的選項,將返回 -1,此任務就完成了。

getopt() 所設置的全局變量包括:

  • char *optarg——當前選項參數字串(如果有)。
  • int optind——argv的當前索引值。當getopt()在while循環中使用時,循環結束後,剩下的字串視為操作數,在argv[optind]至argv[argc-1]中可以找到。
  • int opterr——這個變量非零時,getopt()函數為“無效選項”和“缺少參數選項,並輸出其錯誤信息。
  • int optopt——當發現無效選項字符之時,getopt()函數或返回‘?‘字符,或返回‘:‘字符,並且optopt包含了所發現的無效選項字符。

2. 示例代碼

 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 }

輸出:

  

[email protected]:~/codetest# ./a.out -mnc third_opt
opt is m
opt is n
opt is third_opt
[email protected]:~/codetest# 

命令行參數解析(getopt函數使用)