檔案
#include <getopt.h>函數原型int getopt_long(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex);函數說明getopt被用來解析命令列選項參數。getopt_long支援長選項的命令列解析,使用man getopt_long,得到其聲明如下:int getopt_long(int argc, char * const argv[],const char *optstring, const struct option *longopts,int *longindex);函數中的argc和argv通常直接從main()的兩個參數傳遞而來。optsting是選項參數組成的字串:字串optstring可以下列元素:1.單個字元,表示選項,2.單個字元後接一個冒號:表示該選項後必須跟一個參數。參數緊跟在選項後或者以空格隔開。該參數的指標賦給optarg。3 單個字元後跟兩個冒號,表示該選項後可以有參數也可以沒有參數。如果有參數,參數必須緊跟在選項後不能以空格隔開。該參數的指標賦給optarg。(這個特性是GNU的擴張)。optstring是一個字串,表示可以接受的參數。例如,"a:b:cd",表示可以接受的參數是a,b,c,d,其中,a和b參數後面跟有更多的參數值。(例如:-a host -b name)參數longopts,其實是一個結構的執行個體:struct option {const char *name; //name表示的是長參數名int has_arg; //has_arg有3個值,no_argument(或者是0),表示該參數後面不跟參數值// required_argument(或者是1),表示該參數後面一定要跟個參數值// optional_argument(或者是2),表示該參數後面可以跟,也可以不跟參數值int *flag;//用來決定,getopt_long()的傳回值到底是什麼。如果flag是null,則函數會返回與該項option匹配的val值int val; //和flag聯合決定傳回值}給個例子:struct option long_options[] = {{"a123", required_argument, 0, 'a'},{"c123", no_argument, 0, 'c'},}現在,如果命令列的參數是-a 123,那麼調用getopt_long()將返回字元'a',並且將字串123由optarg返回(注意注意!字串123由optarg帶回!optarg不需要定義,在getopt.h中已經有定義),那麼,如果命令列參數是-c,那麼調用getopt_long()將返回字元'c',而此時,optarg是null。最後,當getopt_long()將命令列所有參數全部解析完成後,返回-1。範例#include <stdio.h>#include <getopt.h>char *l_opt_arg;char* const short_options = "nbl:";struct option long_options[] = {{ "name", 0, NULL, 'n' },{ "bf_name", 0, NULL, 'b' },{ "love", 1, NULL, 'l' },{ 0, 0, 0, 0},};int main(int argc, char *argv[]){int c;while((c = getopt_long (argc, argv, short_options, long_options, NULL)) != -1){switch (c){case 'n':printf("My name is XL.\n");break;case 'b':printf("His name is ST.\n");break;case 'l':l_opt_arg = optarg;printf("Our love is %s!\n", l_opt_arg);break;}}return 0;}[root@localhost wyp]# gcc -o getopt getopt.c[root@localhost wyp]# ./getopt -n -b -l foreverMy name is XL.His name is ST.Our love is forever![root@localhost liuxltest]#[root@localhost liuxltest]# ./getopt -nb -l foreverMy name is XL.His name is ST.Our love is forever![root@localhost liuxltest]# ./getopt -nbl foreverMy name is XL.His name is ST.Our love is forever!