#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
void get_option(int argc, char **argv)
{
char *cmd = argv[0];
while (1) {
int option_index = 0;
struct option long_options[] =
{
{"ip" , 1, 0, 'i'},
{"port" , 1, 0, 'p'},
{"file" , 1, 0, 'f'},
{"type" , 1, 0, 't'}, //1代表有参数
{"help" , 0, 0, 'h'} //0代表没有参数
};
int c;
c = getopt_long(argc, argv, "i:p:f:t:h",long_options, &option_index); //注意这里的冒号,有冒号就需要加参数值,没有冒号就不用加参数值
if (c == -1)
break;
switch (c)
{
case 'i':
printf("Input arg IP \n");
break;
case 'p':
printf("option p with value '%s'\n", optarg);
break;
case 'f':
printf("option f with value '%s'\n", optarg);
break;
case 't':
printf("option t with value '%s'\n", optarg);
//g_cfg.type = optarg;
break;
case 'h':
default:
printf("this is default!\n");
break;
}
}
return;
}
int main(int argc, char **argv)
{
get_option(argc , argv);
return 0;
}
c语言getopt解析命令行参数实例包括长参数与短参数
最新推荐文章于 2024-03-13 22:22:39 发布