getopt用法

getopt用来解析命令行选项参数。就不用自己写东西处理argv了。

#include <unistd.h>

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

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

调用一次,返回一个选项。 在命令行选项参数再也检查不到optstring中包含的选项时,返回-1

字符串optstring可以下列元素:
    1.单个字符,表示选项,
    2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
    3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。

getopt处理以'-’开头的命令行参数,如optstring="ab:c::d::",命令行为getopt.exe -a -b host -ckeke -d haha 
在这个命令行参数中,-a和-h就是选项元素,去掉'-',a,b,c就是选项。host是b的参数,keke是c的参数。但haha并不是d的参数,因为它们中间有空格隔开。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int result;

    opterr = 0;  //使getopt不行stderr输出错误信息

    while( (result = getopt(argc, argv, "ab:c::")) != -1 )
    {
           switch(result)
          {
               case 'a':
                   printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'b':
                   printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'c':
                   printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case '?':
                    printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
                    break;
              default:
                   printf("default, result=%c\n",result);
                   break;
           }
        printf("argv[%d]=%s\n", optind, argv[optind]);
    }
    printf("result=-1, optind=%d\n", optind);   //看看最后optind的位置

    for(result = optind; result < argc; result++)
         printf("-----argv[%d]=%s\n", result, argv[result]);

 //看看最后的命令行参数,看顺序是否改变了哈。
    for(result = 1; result < argc; result++)
          printf("\nat the end-----argv[%d]=%s\n", result, argv[result]);
    return 0;
}

此程序运行结果如下

[root@test test]# ./a.out -a -b bbbbbb -ccccccccc
option=a, optopt=, optarg=(null)
argv[2]=-b
option=b, optopt=, optarg=bbbbbb
argv[4]=-ccccccccc
option=c, optopt=, optarg=cccccccc
argv[5]=(null)
result=-1, optind=5

at the end-----argv[1]=-a

at the end-----argv[2]=-b

at the end-----argv[3]=bbbbbb

at the end-----argv[4]=-ccccccccc



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前进的蜗牛啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值