主要介绍了两个函数
1、getopt
2、getopt_long 可以处理以双划线— —开始的长参数
#include<stdio.h>
#define _GUN_SOURCE
#include<getopt.h>
extern int char *optarg;
extern int optind, opterr, optind;
//结构体 数组
struct option longopts [ ] =
{
{"init", 0, NULL, 'i'},
{"file", 1, NULL, 'f' },
{"list", 0, NULL, 'l'},
{"restart", 0, NULL, 'r'},
{0, 0, 0, 0}
};
int main( int argc, char* argv[ ] )
{
int opt = 0;
while( ( opt = getopt_long(argc, argv, ":if:lr", longopts, NULL) ) != -1 )
{
switch( opt )
{
case 'i':
case 'l':
case 'r':
{
printf("option :%c\n", opt);
break;
}
case 'f':
{
printf("filename :%s\n", optarg);//关联值
break;
}
case ':':
{
printf("option needs a value.\n");
break;
}
case '?':
{
printf("unknown option :%c\n", optopt);
break;
}
}
}
//参数
for(; optind<argc; optind++ )
{
printf("argument :%s\n", argv[optind]);
}
return 0;
}
对于关联值的处理,貌似只能在输入参数f 为最后面的时候,才能识别出 “关联值缺失” 的情况。
./main --init --list --restart --file
./main --init --list --restart --file zhangxuan
./main --init --list --restart --file zhangxuan zhangsan
./main --init --list --file zhangxuang --restart zhangsan
./main --init --list --file --restart
./main --init --list --file --restart zhangsan