linux解析命令行参数getopt_long

            一直以前命令参数好高端,比如 ./nginx -s reload 重新加载配置文件, ./nginx -h 查看帮助文档, 还可以./nginx直接启动nginx,其实linux上其实提供了解析命令行参数的函数getopt_long(头文件getopt.h),特别容易使用,这些都是在webbench一个开源项目中get到的。

       

#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>


int clients=1;
int force=0;

static const struct option long_options[]=
{

  {"help", no_argument, NULL, '?'},
  {"version", no_argument, NULL, 'V'},
  {"clients", required_argument, NULL, 'c'},
  {"force", no_argument, &force, 1},
  {NULL, 0, NULL, 0}
};

static void usage()
{
    fprintf(stderr,
            "webbench [option]... URL \n"
            "  -f|--force         Don't wait for reply from server.\n"
            "  -?|-h|--help       This information.\n"
            "  -c|--clients <n>   Use n clients.\n"
            "  -V|--version       Display program version.\n"
            );
}

int main(int argc, char *argv[])
{
    int opt = 0;
    int options_index = 0;

    while((opt=getopt_long(argc, argv, "Vfc:?h", long_options, &options_index)) != EOF){
       switch(opt){
         case  0 : break;
         case 'f': force=1; printf("force = %d\n", force);break;
         case 'V': printf("vaynedu 1.1.1\n");exit(0);
         case '?': usage();exit(0);
         case 'h': usage();exit(0);
         case 'c': clients=atoi(optarg); printf("clients = %d\n", clients);break;
         default : printf("input error,please input ./webbench -h\n");break;
      }
    }

    printf(" vaynedu try to use getopt\n");

    return 0;
}

输出结果演示:

          


具体的使用方法和高端操作,看了两篇很好的博客,我也就不多BB了

linux-解析命令行选项getopt_long用法


函数getopt(),及其参数optind

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值