getopt函数

getopt概述

getopt只支持短参数,例如-a -b
int getopt(int argc, char * const argv[], const char *optstring);

需要解释的几个概念
(1)参数optstring,表示程序支持的参数,例如char *optstr = "a::b:c:di:p:";就表示当前程序支持的参数有:-a -b -c -d -i -p
冒号的意思

单个字符a         表示选项a没有参数            格式:-a即可,不加参数
单字符加冒号b:     表示选项b有且必须加参数      格式:-b 100或-b100,但-b=100错
单字符加2冒号c::   表示选项c可以有,也可以无     格式:-c200,其它格式错误

(2)变量optarg,这是库中定义好的一个变量,保存了参数后面的值,比如有参数-b 100,当getopt函数返回b的时候,此时optarg存储的就是100
(3)getopt函数的返回值:char类型的参数所对应的int值,比如-b 100,getopt函数返回的就是字符对应的int值
(4)另外几个与optarg类似的几个变量
optind —— 再次调用 getopt() 时的下一个 argv指针的索引。
optopt —— 最后一个未知选项。
opterr ­—— 如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。

用法

getopt_long

int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts,int *longindex);
这是getopt函数的加强版,getopt不支持长选项(例如:--ipaddr这种),getopt_long除了支持getopt的所有功能之外,还支持长选项。
短选项的用法与getopt完全一样。
getopt_long函数的第四个参数(longopts)与第三个参数(optstring)功能一致,optstring用于支持短选项,longopts则用于支持长选项。
longopts是一个结构体数组,每个结构体表示一个支持的选项

struct option {
const char  *name;       /* 参数名称 */
int          has_arg;    /* 是否带有参数*/
int          *flag;      /* flag=NULL时,返回value;不为空时,*flag=val,返回0 */
int          val;        /* 指定函数匹配到*name表示的选项后,getopt_long函数的返回值,或flag非空时指定*flag的值 */
}; 

假设有例子:

代码实例

更实际的使用例子:

#include <cstring>
#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <getopt.h>

//long opt
char ip[20];
char port[20];

//short opt
char age[20];
char name[20];

int main(int argc, char *argv[]) {

    int opt = 0;
    int opt_index = 0;
    //a means age, n means name
    char *optstr= "a:n:";
    static struct option long_options[] = {
        {"ip", required_argument, NULL, 1},
        {"port",required_argument, NULL, 2},
        {NULL, 0, NULL, 0},
    };
    while((opt =getopt_long_only(argc,argv,optstr,long_options,&opt_index))!= -1){
        switch(opt){
            //ip
            case 1:
                memcpy(ip,optarg,strlen(optarg));
                break;
            //port
            case 2:
                memcpy(port,optarg,strlen(optarg));
                break;
            //age
            case 'a':
                memcpy(age,optarg,strlen(optarg));
                break;
            //name
            case 'n':
                memcpy(name,optarg,strlen(optarg));
                break;
        }
    }
    printf("ip:%s,   addr:%s,   age:%s,   name:%s\n", ip, port, age, name);
    return 0;
}

执行结果:

不带-*的参数

比如cat a.txt这种类型
假设有例子app -port 9900 a.txt
在getopt函数返回-1之后,再去打印argv[optind]就是跟在最后边的a.txt

posted @ 2022-01-22 18:06  feipeng8848  阅读(1330)  评论(0编辑  收藏  举报