直接上代碼:涉及函數getopt(),getopt_long()
1 #include <unistd.h> 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <getopt.h> 5 6 /* 7 int main(int argc, char *argv[]) 8 { 9 int opt; 10 char * optstring = "a:b:c:d"; 11 12 while ((opt = getopt(argc, argv, optstring)) != -1) 13 { 14 printf("opt = %c\n", opt); 15 printf("optarg = %s\n", optarg); 16 printf("optind = %d\n", optind); 17 printf("argv[optind - 1] = %s\n\n", argv[optind - 1]); 18 } 19 20 return 0; 21 } 22 */ 23 24 //getopt_long()和getopt_long_only()函數支持長選項的命令行解析,其中,后者的長選項字串是以一個短橫線開始的,而非一對短橫線。 25 int main(int argc, char **argv) 26 { 27 int opt; 28 int digit_optind = 0; 29 int option_index = 0; 30 char *optstring = "a:b:c:d"; 31 static struct option long_options[] = { 32 {"reqarg", required_argument, NULL, 'r'}, 33 {"noarg", no_argument, NULL, 'n'}, 34 {"optarg", optional_argument, NULL, 'o'}, 35 {0, 0, 0, 0} 36 }; 37 /* 38 *extern char *optarg; //選項的參數指針 39 *extern int optind, //下一次調用getopt時,從optind存儲的位置處重新開始檢查選項 40 *extern int opterr, //當opterr=0時,getopt不向stderr輸出錯誤信息。 41 *extern int optopt; //當命令行選項字符不包括在optstring中或者最后一個選項缺少必要的參數時,該選項存儲在optopt中,getopt返回'?’ 42 * 43 */ 44 45 while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) 46 { 47 printf("opt = %c\n", opt); 48 printf("optarg = %s\n", optarg); 49 printf("optind = %d\n", optind); 50 printf("argv[optind - 1] = %s\n", argv[optind - 1]); 51 printf("option_index = %d\n", option_index); 52 } 53 54 return 0; 55 }
? int getopt(int argc, char * const argv[], const char *optstring);
該函數用來解析命令行參數。前兩個參數設為main函數的兩個參數。
optstring設為由該命令要處理的各個選項組成的字符串。選項后面帶有冒號':'時,
該選項是一個帶參數的選項。
例如:make -f filename -n
-f是一個帶參數的選項,-n是一個沒有參數的選項。
可以下面這樣調用函數getopt來解析上面的例子。
c = getopt(argc, argv, "f:n");
此函數的返回值即為當前找到的命令選項,全部選項都找到時的返回值為-1。
通常一個命令有多個選項,為了取得所有選項,需要循環調用此函數,直到返回值為-1。
要使用此函數,還有幾個全局變量必須要了解。
extern char *optarg;
extern int optind, opterr, optopt;
optarg: 當前選項帶參數時,optarg指向該參數。
optind: argv的索引。通常選項參數取得完畢時,通過此變量可以取得非選項參數(argv[optind])
optopt: 一個選項在argv中有,但在optstring中不存在時,或者一個帶參數的選項沒有參數時,
? ? ? ? getopt()返回'?',同時將optopt設為該選項。
opterr: 將此變量設置為0,可以抑制getopt()輸出錯誤信息。
int getopt_long(int argc, char * const argv[],
? ? ? ? ? ? ? ? ? const char *optstring,
? ? ? ? ? ? ? ? ? const struct option *longopts, int *longindex);
這是支持長命令選項的函數,長選項以'--'開頭。
前三個參數與函數getopt的參數是一樣的。只支持長選項時,參數optstring設置為NULL或者空字符串
第四個參數是一個構造體struct option的數組。此構造體定義在頭文件getopt.h中。
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
構造體各個成員的解釋如下
name ? : 長選項的名字
has_arg: no_argument或0表示此選項不帶參數,required_argument或1表示此選項帶參數,optional_argument或2表示是一個可選選項。
flag : 設置為NULL時,getopt_long()返回val,設置為NULL以外時,getopt_long()返回0,且將*flag設為val。
val : 返回值或者*flag的設定值。有些命令既支持長選項也支持短選項,可以通過設定此值為短選項實現。
此數組的最后一個須將成員都置為0。
關于返回值有以下幾種情況:
識別為短選項時,返回值為該短選項。
識別為長選項時,如果flag是NULL的情況下,返回val,如果flag非NULL的情況下,返回0。
所有選項解析結束時返回-1。
存在不能識別的選項或者帶參數選項的參數不存在時返回'?
?