#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
int main(int argc, char** argv)
{
int res = 0;
int longindex = 0;
/*
struct option {
const char *name; //长参数名
int has_arg; //0-无参数,1-有参数,2-可选
int *flag; //若为NULL,则val字段值被getop_long函数返回,不为NULL,
则函数返回0,flag指向val字段值
int val; //函数返回值或flag指向自己
};
*/
struct option opt_sts[5]={
{"PORT", 1, NULL, 'P'},
{"password", 1, NULL, 'p'},
{"host", 1, NULL, 'h'},
{"user", 1, NULL, 'u'},
{"HELP", 0, NULL, 'H'}
};
while (1)
{
/* option参数
(1)只有一个字符,不带冒号——只表示选项, 如-c
(2)一个字符,后接一个冒号——表示选项后面带一个参数,如-p 60000
(3)一个字符,后接两个冒号——表示选项后面带一个可选参数,即参数可有可无, 如果带参数,则选项与参数直接不能有空格 -P60000
*/
//res = getopt(argc, argv, "P:p:h:u:H");
/*getopt_long兼容长参数,--PORT --password,具体可以man 3 getopt查看 */
res = getopt_long(argc, argv, "P:p:h:u:H", opt_sts, &longindex);
if (res < 0)
{
break;
}
switch(res)
{
case 'P':
printf("PORT:%s\n", optarg);
break;
case 'p':
printf("password:%s\n", optarg);
break;
case 'h':
printf("host:%s\n", optarg);
break;
case 'u':
printf("user:%s\n", optarg);
break;
case 'H':
printf("help:\n");
break;
default:
pause();
break;
}
}
return 0;
}
./getopt_test --host 127.0.0.1 -u zhangsan --password 1234 -P60000
host:127.0.0.1
user:zhangsan
password:1234
PORT:60000