命令行参数的获取

6 篇文章 0 订阅
4 篇文章 0 订阅

时不时我们会遇到对命令含参数的处理,如果参数个数较多,按照顺序处理有可能会出现错误或者一些可选参数将不能实现,接下来介绍几个处理命令行参数的函数

  • getopt
#include <unistd.h>
int getopt(int argc, char * const argv[],
           const char *optstring);
extern char *optarg;//带值参数的值
extern int optind, opterr, optopt;
//optind:下一个要被处理的参数在argv中的下标值
//opterr:如果opterr=0,在函数出现错误是,就不会将错误信息打印在标准输出上
//optopt:函数返回值

getopt函数的前两个参数argc和argv根main函数的一样,第三个参数optstring就是我们要解析的很多参数;
eg:
char* optstring = "avtc:l";
传入opstring之后,函数会依次检查命令是否指定了-a,-v,-t,-c,-l;如果检查到制定了某个参数,函数就会返回该参数的名称(一直检查到返回-1)
c后面有冒号表示这个参数可以指定值;-c 100

  • getopt_long
#include <getopt.h>
int getopt_long(int argc, char * const argv[],
                  const char *optstring,
                  const struct option *longopts,
                  int *longindex);

前三个参数和getopt一样,该函数包括getopt的功能,并且支持指定长参数
第四个参数: longopts是一个结构体(option)数组

struct option {
    const char *name;
    int    has_arg;
    int    *flag;
    int    val;
};
//name :是参数的名称
//has_arg :指明是否带参数值,其数值可选:
       /* no_argument (即 0) 表明这个长参数不带参数(即不带数值,如:--name)
        required_argument (即 1) 表明这个长参数必须带参数(即必须带数值,如:--name Bob)
        optional_argument(即2)表明这个长参数后面带的参数是可选的,(即--name和--name Bob均可)*/
//flag:当这个指针为空的时候,函数直接将val的数值从getopt_long的返回值返回出去,当它非空时,val的值会被赋到flag指向的整型数中,而函数返回值为0
//val :用于指定函数找到该选项时的返回值,或者当flag非空时指定flag指向的数据的值。


//eg:
static const struct option long_options[] =
{
    { "force", no_argument, &force, 1 },
    { "reload", no_argument, &force_reload, 1 },
    { "time", required_argument, NULL, 't' },
    { "help", no_argument, NULL, '?' },
    { "http09", no_argument, NULL, '9' },
    { "http10", no_argument, NULL, '1' },
    { "http11", no_argument, NULL, '2' },
    { "get", no_argument, &method, METHOD_GET },
    { "head", no_argument, &method, METHOD_HEAD },
    { "options", no_argument, &method, METHOD_OPTIONS },
    { "trace", no_argument, &method, METHOD_TRACE },
    { "version", no_argument, NULL, 'V' },
    { "proxy", required_argument, NULL, 'p' },
    { "clients", required_argument, NULL, 'c' },
    { NULL, 0, NULL, 0 }
};

第五个参数:记录当前longopts的下标

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

getopt_long_only函数,它与getopt_long函数使用相同的参数表,在功能上基本一致,只是getopt_long只将–name当作长参数,但getopt_long_only会将–name和-name两种选项都当作长参数来匹配。在getopt_long在遇到-name时,会拆解成-n -a -m -e到optstring中进行匹配,而getopt_long_only只在-name不能在longopts中匹配时才将其拆解成-n -a -m -e这样的参数到optstring中进行匹配。

之前博客:命令行参数简介

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值