学习解析命令行参数函数-getopt函数

学习解析命令行参数函数 —— getopt函数

背景

       工作的过程中,我们需要根据命令行参数来决定程序运行的过程。因此我们可以使用getopt函数来满足我们的工作需要。


函数简介

       函数原型如下:

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

       如果getopt函数找到一个选项字符,则返回该字符,更新外部变量optind和一个静态变量nextchar,以便下次调用getopt函数可以使用下一个选项字符或argv中 带-符号的参数恢复扫描。如果没有更多选项字符,getopt()返回-1。 那么optind是第一个argv中带-的参数的索引。

       optstring是一个包含合法选项字符的字符串。

       补充说明:

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

       变量optind是要在argv中处理的下一个元素的索引。 系统将该值初始化为1.调用者可以将其重置为1,以重新扫描相同的argv,或扫描新的参数向量时。

       如果getopt()不识别选项字符,则会向stderr打印一条错误消息,将该角色存储在optopt中,并返回'?'。调用程序可以通过将opterr设置为0来阻止错误消息。


测试代码

       以下代码存放在test.c文件中

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

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

           char *tvalue;
           flags = 0;
           //解析argc、argv参数,argv参数要求t后面需要有参数值,参数n后面可以不接参数值
           while ((opt = getopt(argc, argv, "nt:")) != -1) {
               switch (opt) {
               case 'n':
                   flags = 1;
                   break;
               case 't':
                   tvalue = optarg;// -t 后从参数值存储在optarg全局变量中
                   break;
               case '?': /* 如果不是-n 或-t参数 ,返回’?’ */
                   fprintf(stderr, "Usage: %s [-t tvalue] [-n] name\n",
                           argv[0]);
                   exit(EXIT_FAILURE);
               }
           }
           //用于查看opterr, optind,optopt变量
           printf("opterr=%d; optind=%d ;optopt=%d\n", opterr, optind,optopt);

           if (optind >= argc) {
               fprintf(stderr, "Expected argument after options\n");
               exit(EXIT_FAILURE);
           }

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

           exit(EXIT_SUCCESS);
       }


编译生成测试程序

       gcc test.c


总结

        我们可以使用getopt函数来解析命令行参数。


参考资料

       以上资料是根据在Linux终端上运行man getopt的信息总结而来的。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值