命令行参数解析处理
getopt_long
描述:
- 函数的作用:解析命令行参数。
头文件:
#include <getopt.h>
函数定义:
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
函数返回值:
- 成功返回命令行的选项,失败反会-1。
函数说明:
- 参数argc和argv:在程序调用时传递给main()函数。
- optstring:接收 option结构体的参数。例:
"a:b:c"
- longopts:option结构体名。
- longindex:赋为NULL或指向一个变量,通常赋为NULL。
option结构体:
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
- name:
选项的名称。 - has_arg:
no_argument--------------选项没有参数------0
required_argument-------选项需要参数------1
optional_argument--------选项参数可选------2 - flag:
指定如何返回选项的结果。如果标志为NULL,则getopt_long()返回val。如果标志指向一个变量,getopt_long()返回0,如果找到该选项,该变量将设置为val。 - val:
要返回的值,或要加载到flag指向的变量中的值。
代码演示:
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
void print_usage(char *progname)
{
printf("%s usage: \n", progname);
printf("-i(--ip): sepcify IP address.\n");
printf("-p(--port): sepcify port.\n");
printf("-h(--help): print this help information.\n");
}
int main(int argc, char **argv)
{
int port = 0;
char *ip = NULL;
int ch = 0;
struct option opts[] = {
{"ip", required_argument, NULL, 'i'},
{"port", required_argument, NULL, 'p'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
printf("start parser arguments\n");
while( (ch=getopt_long(argc, argv, "i:p:h", opts, NULL)) != -1 )
{
printf("ch: %c\n", ch);
switch(ch)
{
case 'i':
ip=optarg; //optarg为char *类型
break;
case 'p':
port=atoi(optarg); //强制转换为int类型
break;
case 'h':
print_usage(argv[0]);
return 0;
}
}
if ( !ip || !port)
{
print_usage(argv[0]);
return 0;
}
printf("ip: %s\n", ip);
printf("port: %d\n", port);
}
执行结果:
lyt@ubuntu:~/test/apue$ ./getopt
start parser arguments
./getopt usage:
-i(–ip): sepcify IP address.
-p(–port): sepcify port.
-h(–help): print this help information.
lyt@ubuntu:~/test/apue$ ./getopt -h
start parser arguments
ch: h
./getopt usage:
-i(–ip): sepcify IP address.
-p(–port): sepcify port.
-h(–help): print this help information.
lyt@ubuntu:~/test/apue$
lyt@ubuntu:~/test/apue$ ./getopt -i 107.0.0.1 -p 8888
start parser arguments
ch: i
ch: p
ip: 107.0.0.1
port: 8888
lyt@ubuntu:~/test/apue$ ./getopt -p 8888 -i 107.0.0.1
start parser arguments
ch: p
ch: i
ip: 107.0.0.1
port: 8888