Linux命令行解析函数getopt()

#include <srdio.h>
#include <unistd.h>

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

    while((ch = getopt(argc, argv, "ab:c::d")) != -1){
        switch(ch){
            case 'a':
                print("a, no opt");
                break;
            case 'b':
                print("b, opt:", optarg);
                break;
            case 'c':
                print("c, opt:", optarg);
                break;
            case 'd':
                print("d, no opt");
                break;
            default:
                print("opt err");
        }
    }

    return 0;
}

输出:

./a.out -a x
a, no opt

./a.out -a -b x
a, no opt
b, opt: x

./a.out -ab x -c xx
a, no opt
b, opt: x
c, opt: //xx应紧跟c后面

./a.out -adb x -cxx
a, no opt
d, no opt
b, opt: x
c, opt: xx



Linux中getopt函数、optind等变量使用详解

1. getopt函数的声明

该函数是由Unix标准库提供的函数,查看命令man 3 getopt

#include <unistd.h>

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

extern char *optarg;
extern int optind, opterr, optopt;

getopt函数的参数:

  • 参数argc和argv:通常是从main的参数直接传递而来,argc是参数的数量,argv是一个常量字符串数组的地址。
  • 参数optstring:一个包含正确选项字符的字符串,如果一个字符后面有冒号,那么这个选项在传递参数时就需要跟着一个参数。

外部变量:

  • char *optarg:如果有参数,则包含当前选项参数字符串
  • int optind:argv的当前索引值。当getopt函数在while循环中使用时,剩下的字符串为操作数,下标从optind到argc-1。
  • int opterr:这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。
  • int optopt:当发现无效选项字符之时,getopt()函数或返回 \’ ? \’ 字符,或返回字符 \’ : \’ ,并且optopt包含了所发现的无效选项字符。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值