命令行参数的处理函数getopt

命令参数

在linux下, shell命令的参数分两种情况:
a.参数需要附加信息, 如"wget http://www.abc.com/1.zip -o 1.zip"
b.参数不需要附加信息, 如"ls -l"
有点像英语中的及物动词和不及物动词

getopt

#include <unistd.h>
int getopt(int argc, char * const argv[], const char * optstring);

extern char *optarg; //指向参数的附加信息
extern int optind;  // 初始化值为1,下一次调用getopt时,从optind存储的位置重新开始检查选项。
extern int opterr;  // 初始化值为1,当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt;  // 当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,
                                    // 该选项存储在optopt中, getopt返回'?’。

getopt前两个参数就是main函数里的两个参数
optstring是一个字符串包含需要捕获的参数,例"o:l"表示要捕捉o和l这两个参数

  • 后面带冒号的参数表示该参数有附加信息, 附加信息可通过optarg获取
  • 后面不带冒号的参数表示不带附加信息
  • 有些参数后面会带两个冒号, 表示附加信息可有可无, 但是如果有的话附加信息与参数之间不能有空格
  • 如果参数不在获取的字符串中, optarg返回一个问号, 同时getopt会输出错误信息, 可指定opterr=0来取消错误信息的输出

optind:
默认值为1, 即初始位置是a.out后面跟的第一个参数
假设当前optstring="a:b", 每调用一次getopt函数, optind就向后移动一次, 最后停留在第一个非optstring参数和非参数附加信息的参数上.
当遇到-b时, optind+=1, 即向后移动一位
当遇到-a时, optind+=2, 因为-a还会带一个附加信息
例如: a.out -a arg -b ...(不带-的其它任意参数), 循环执行完分析后, optind=4, 即停留在非optstring及其附加信息的参数上

例子

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
 
int main(int argc, char *argv[]){
    int ch;
    opterr=0;
    while((ch=getopt(argc,argv,"o:l")) != -1){
        switch(ch){
            case 'o':
                printf("option -o : %s
",optarg); break;
            case 'l':
                printf("option -l : l
"); break;
            default:
                printf("unknown option: %c
",ch);
        }
    }
    return 0;
}

测试:
a.out -o arg
a.out -l
a.out -lo arg //多个参数一起写时, 不及物参数写前面

原文地址:https://www.cnblogs.com/cfans1993/p/5753691.html