zoukankan      html  css  js  c++  java
  • getopt函数

    Linux命令行参数处理函数:

    #include <unistd.h>
    extern char *optarg;  //选项的参数指针
    extern int optind,    //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。 
    extern int opterr,    //当opterr=0时,getopt不向stderr输出错误信息。
    extern int optopt;    //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回'?’、
    int getopt(int argc, char * const argv[], const char *optstring);

    getopt函数第三个参数格式:

    1.单个字符,表示选项,
    2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
    3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)

    代码示例:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
     
    int main(int argc, char **argv)
    {
        int result;
     
        //opterr = 0;  //0表示不输出错误信息,没找到的选项或者错误的选项会走?case
     
        while( (result = getopt(argc, argv, "ab:c::")) != -1 )
        {
               switch(result)
              {
                   case 'a':
                       printf("option=a, optopt=%c, optarg=%s
    ", optopt, optarg);
                       break;
                  case 'b':
                       printf("option=b, optopt=%c, optarg=%s
    ", optopt, optarg);
                       break;
                  case 'c':
                       printf("option=c, optopt=%c, optarg=%s
    ", optopt, optarg);
                       break;
                  case '?':
                        printf("result=?, unknown optopt=%c, optarg=%s
    ", optopt, optarg);
                        break;
                  default:
                       printf("default, result=%c
    ",result);
                       break;
               }
            //printf("next argv[%d]=%s
    ", optind, argv[optind]);
        }
        printf("result=-1, optind=%d
    ", optind); 
     
      //未处理参数 for(result = optind; result < argc; result++) printf("+++++argv[%d]=%s ", result, argv[result]);

      //参数真是顺序 for(result = 1; result < argc; result++) printf("-----argv[%d]=%s ", result, argv[result]); return 0; }

     输出:

     

    参考文章:https://blog.csdn.net/kunikida/article/details/8922754

  • 相关阅读:
    pylab
    通过在 Page 指令或 配置节中设置 validateRequest=false 可以禁用请求验证
    PRIMUS
    Ubuntu 下安装AMBER10/AmberTools 1.2
    SUPCOMB
    biopython
    python IDE
    SASREF
    PEAK
    ANDROID移植: WIFI设计原理(源码分析
  • 原文地址:https://www.cnblogs.com/yinguojin/p/15306703.html
Copyright © 2011-2022 走看看