1.程序代码
short_options:短参数,后面跟一个冒号为有参数,后面跟两个为参数可有可没有
long_options:长参数,第二项为0为无参数,1为有参数,2为参数可有可无,第四项为对应的短参数
#include<stdio.h>
#include<stdlib.h>
#include<getopt.h>
#include<sys/time.h>
#define APP_VERSION "V1.0.0 ("__DATE__" "__TIME__")"
int main(int argc, char* argv[])
{
printf("Program Version: %s\n", APP_VERSION);
printf("Program Start!\n");
int next_option;
const char* const short_options="abcd:e:f:g::";
const struct option long_options[] =
{
{"aaaa", 0, NULL, 'a'},
{"bbbb", 0, NULL, 'b'},
{"cccc", 0, NULL, 'c'},
{"dddd", 1, NULL, 'd'},
{"eeee", 1, NULL, 'e'},
{"ffff", 1, NULL, 'f'},
{"gggg", 2, NULL, 'g'}
};
do
{
next_option = getopt_long(argc, argv, short_options, long_options, NULL);
switch(next_option)
{
case 'a':
{
printf("a received!\n");
}break;
case 'b':
{
printf("b received!\n");
}break;
case 'c':
{
printf("c received!\n");
}break;
case 'd':
{
printf("d received! Para:%s\n", optarg);
}break;
case 'e':
{
printf("e received! Para:%sWn", optarg);
}break;
case 'f':
{
printf("f received! Para:%s\n", optarg);
}break;
case 'g':
{
printf("g received! Para:%s\n", optarg);
}break;
case '?':
{
printf("unknown word!\n");
break;
}break;
}
//printf("%d\n",next_option);
}
while(next_option != -1);
printf("Program Closed!\n");
exit(0);
}
2.运行结果
END