getopt_long

#include <stdio.h>
#if _WIN32
#include "getopt.h"
#else
#include <getopt.h>
#endif
 
char *l_opt_arg;
char *ouput_opt_arg;
char* const short_options = "nbl:hvo:";
struct option long_options[] = {
{ "name", 0, NULL, 'n'},
{ "NIU", 0,   NULL,  'N' },
{ "bf_name", 0, NULL, 'b' },
{ "love",  1,   NULL, 'l' },
 
{"help", 0, NULL, 'h'},
{"output", 1, NULL, 'o' },
{"verbose", 0, NULL, 'v'},
{"2048", 1, NULL, '2'},
{NULL, 0, NULL, 0 }
};
/**
最后说说getopt_long_only函数,它与getopt_long函数使用相同的参数表,在功能上基本一致,只是getopt_long只将--name当作长参数,但getopt_long_only会将--name和-name两种选项都当作长参数来匹配。在getopt_long在遇到-name时,会拆解成-n -a -m -e到optstring中进行匹配,而getopt_long_only只在-name不能在longopts中匹配时才将其拆解成-n -a -m -e这样的参数到optstring中进行匹配。
*/
// ./test -n -b -l forever
// ./test -nb -l forever
// ./test -nbl forever
// ./test --love forever
// ./test --name --love forever
// ./test --NIU
// ./test --N --2048 string
int main(int argc, char *argv[])
{
    int c;
    while((c = getopt_long (argc, argv, short_options, long_options, NULL)) != -1)
    {
        //char* tmp=(char*)c;
        //if(NULL!=tmp)
        //	 printf("c=%\n",tmp);
        switch (c)
        {
        case 'n':
            printf("My name is XL.\n");
            break;
        case 'N':
            printf("My name is NIU.\n");
            break;
        case 'b':
            printf("His name is ST.\n");
            break;
        case 'l':
            l_opt_arg = optarg;
            printf("Our love is %s!\n", l_opt_arg);
            break;
        case 'h':
            printf("this is help.\n");
            break;
        case 'v':
            printf("this is verbose\n");
            break;
        case '2':
            ouput_opt_arg = optarg;
            printf("this is 2048=%s!\n", ouput_opt_arg);
            break;
        case 'o':
            ouput_opt_arg = optarg;
            printf("ouput is %s!\n", ouput_opt_arg);
            break;
        }
    }
    return 0;
}

最后说说getopt_long_only函数,它与getopt_long函数使用相同的参数表,在功能上基本一致,只是getopt_long只将--name当作长参数,但getopt_long_only会将--name和-name两种选项都当作长参数来匹配。在getopt_long在遇到-name时,会拆解成-n -a -m -e到optstring中进行匹配,而getopt_long_only只在-name不能在longopts中匹配时才将其拆解成-n -a -m -e这样的参数到optstring中进行匹配。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值