• 命令行解析getopt_long


    getopt_long函数可以轻松的解析main函数的命令行参数。

    int getopt_long(int argc,char * const argv[],const char *optstring,const struct option *longopts,int *longindex)

    函数中的参数argc和argv通常直接从main()的两个参数传递而来。optstring是选项参数组成的字符串。

    字符串optstring可以下列元素: 
    1. 单个字符,表示选项, 
    2. 单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。 
    3. 单个字符后跟两个冒号,表示该选项后可以有参数也可以没有参数。如果有参数,参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。

    optstring是一个字符串,表示可以接受的参数。例如,"a:b:cd",表示可以接受的参数是a,b,c,d,其中,a和b参数后面跟有更多的参数值。

    struct option { 
    const char *name; //name表示的是长参数名 
    int has_arg; //has_arg有3个值,no_argument(或者是0),表示该参数后面不跟参数值 
    // required_argument(或者是1),表示该参数后面一定要跟个参数值 
    // optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值 
    int *flag; 
    //用来决定,getopt_long()的返回值到底是什么。如果flag是null,则函数会返回与该项option匹配的val值 
    int val; //和flag联合决定返回值 

    #include <stdio.h>
    #include <getopt.h>
    int parse_cmd_line(int argc, char ** argv)
    {
      struct option long_option[] = {
        {"usrname", required_argument, NULL, 'u'},
        {"passwd", required_argument, NULL, 'p'},
        {"money", required_argument, NULL, 'm'},
        {"job", optional_argument, NULL, 'j'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0},
      };
      int opt;
      while((opt = getopt_long(argc,argv,"u:p:hm:j::",long_option, NULL)) != -1)
      {
        switch(opt)
        {
          case 'u':
          printf("usrname:%s ", optarg);
          break;
          case 'p':
          printf("passwd:%s ", optarg);
          break;
          case 'm':
          printf("money:%d ",atoi(optarg));
          break;
          case 'j':
          printf("job:%s ", optarg);
          break;
          case 'h':
          printf("print help info here ");
          break;
          default:
          printf("invalid argument ");
        }
      }
      if (optind < argc)
      {
        printf("Too many argument ");
      }
      return 0;
    }
    int main(int argc, char **argv)
    {
      parse_cmd_line(argc, argv);
      return 0;
    }

    ./test -u fellow -p 111 -m 100 --job=sw

  • 相关阅读:
    tomcat中配置https服务
    https无法下载
    将页面导成excel
    如何用sql语言只获得数据库当前日期,且格式为"yyyymmdd"?
    一个测试webservice服务的工具
    java中相对路径,绝对路径问题总结(转)
    Hadoop: I/O操作中的数据检查
    Java中Array.sort相关方法
    数据的I/O序列化操作
    Java中Comparable和Comparator实现对象比较
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6127500.html
Copyright © 2020-2023  润新知