getopt函数详解

46 篇文章 0 订阅

getopt函数

1、定义:

int getopt(int argc, char * const argv[], const char *optstring);

注意!!!!

使用之后,会对参数的顺序进行重排序,不在选项后面的第一个参数的参数,全放在后面

2、描述:

getopt是用来解析命令行选项参数的,但是只能解析短选项: -d 100,不能解析长选项:--prefix

3、参数:

  • argc:main()函数传递过来的参数的个数
  • argv:main()函数传递过来的参数的字符串指针数组
  • optstring:选项字符串,告知 getopt()可以处理哪个选项以及哪个选项需要参数

4、返回:

如果选项成功找到,返回选项字母;如果所有命令行选项都解析完毕,返回 -1;如果遇到选项字符不在 optstring 中,返回字符 '?';如果遇到丢失参数,那么返回值依赖于 optstring 中第一个字符,如果第一个字符是 ':' 则返回':',否则返回'?'并提示出错误信息。

5、下边重点举例说明optstring的格式意义:

char*optstring = “ab:c::”;

单个字符a 表示选项a没有参数 格式:-a即可,不加参数

单字符加冒号b: 表示选项b有且必须加参数 格式:-b 100或-b100,但-b=100错

单字符加2冒号c:: 表示选项c可以有,也可以无 格式:-c200,其它格式错误

上面这个 optstring 在传入之后,getopt 函数将依次检查命令行是否指定了 -a, -b, -c(这需要多次调用 getopt 函数,直到其返回-1),当检查到上面某一个参数被指定时,函数会返回被指定的参数名称(即该字母)

  • optarg —— 指向当前选项参数(如果有)的指针。
  • optind —— 再次调用 getopt() 时的下一个 argv指针的索引。
  • optopt —— 最后一个未知选项。
  • opterr ­—— 如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。

 

例子:

int main(int argc, char **argv)

{

    char interface[256] = "", bpfstr[256] = "";

    int packets = 0, c, i;

    // Get the command line options, if any

    while ((c = getopt (argc, argv, "hi:n:")) != -1)

    {

        switch (c)

        {

        case 'h':

            printf("usage: %s [-h] [-i ] [-n ] []\n", argv[0]);

            exit(0);

            break;

        case 'i':

            strcpy(interface, optarg);

            break;

        case 'n':

            packets = atoi(optarg);

            break;

        }

    }

    // Get the packet capture filter expression, if any.

    for (i = optind; i < argc; i++)

    {

        strcat(bpfstr, argv[i]);

        strcat(bpfstr, " ");

    }

}


#include<stdio.h>

#include<unistd.h>

#include<getopt.h>

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

{

    int opt;

    char *string = "a::b:c:d";

    while ((opt = getopt(argc, argv, string))!= -1)

    {  

        printf("opt = %c\t\t", opt);

        printf("optarg = %s\t\t",optarg);

        printf("optind = %d\t\t",optind);

        printf("argv[optind] = %s\n",argv[optind]);

    }  

}

 

使用范例:

mouse@mouse:/work/hello$ ./hello -a100 -b 200 -c 300 -d

opt = a         optarg = 100            optind = 2              argv[optind] = -b

opt = b         optarg = 200            optind = 4              argv[optind] = -c

opt = c         optarg = 300            optind = 6              argv[optind] = -d

opt = d         optarg = (null)         optind = 7              argv[optind] = (null)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值