linux 之 getopt_long()
文件#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 forever
My name is XL.
His name is ST.
Our love is forever!
[root@localhost liuxltest]#
[root@localhost liuxltest]# ./getopt -nb -l forever
My name is XL.
His name is ST.
Our love is forever!
[root@localhost liuxltest]# ./getopt -nbl forever
My name is XL.
His name is ST.
Our love is forever!
最後更新:2017-04-03 16:48:50