linux getopt函数应用

#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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值