命令行参数解析函数 —— getopt()

getopt()函数声明如下:
#include <unistd.h>

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

extern char *optarg;
extern int optind, opterr, optopt;
该函数的argc和argv参数通常直接从main()的参数直接传递而来。optstring是选项字母组成的字串。如果该字串里的任一字符后面有冒号,那么这个选项就要求有选项参数。
当给定getopt()命令参数的数量 (argc)、指向这些参数的数组 (argv) 和选项字串 (optstring) 后,getopt() 将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有可识别的选项,将返回 -1,此任务就完成了。
getopt() 所设置的全局变量包括:
  • char *optarg——当前选项参数字串(如果有)。
  • int optind——argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。
  • int opterr——这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。
  • int optopt——当发现无效选项字符之时,getopt()函数或返回'?'字符,或返回':'字符,并且optopt包含了所发现的无效选项字符。
以下面的程序为例:
选项:
  • -n —— 显示“我的名字”。
  • -g —— 显示“我女朋友的名字”。
  • -l —— 带参数的选项.
  • 清单2:

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

int main (int argc, char **argv)
{
    int oc;                     /*选项字符 */
    char *b_opt_arg;            /*选项参数字串 */

    while((oc = getopt(argc, argv, "ngl:")) != -1)
    {
        switch(oc)
        {
            case 'n':
                printf("My name is Lyong.\n");
                break;
            case 'g':
                printf("Her name is Xxiong.\n");
                break;
            case 'l':
                b_opt_arg = optarg;
                printf("Our love is %s\n", optarg);
                break;
        }
    }
   return 0;
}
运行结果:
$ ./opt_parse_demo -n
My name is Lyong.
$ ./opt_parse_demo -g
Her name is Xxiong.
$ ./opt_parse_demo -l forever
Our love is forever
$ ./opt_parse_demo -ngl forever
My name is Lyong.
Her name is Xxiong.
Our love is forever
  • 6、改变getopt()对错误命令行参数信息的输出行为

不正确的调用程序在所难免,这种错误要么是命令行选项无效,要么是缺少选项参数。正常情况下,getopt()会为这两种情况输出自己的出错信息,并且返回'?'。为了验证此事,可以修改一下上面的清单2中的代码。
  • 清单3:

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

int main (int argc, char **argv)
{
    int oc;                     /*选项字符 */
    char *b_opt_arg;            /*选项参数字串 */

    while((oc = getopt(argc, argv, "ngl:")) != -1)
    {
        switch(oc)
        {
            case 'n':
                printf("My name is Lyong.\n");
                break;
             case 'g':
                printf("Her name is Xxiong.\n");
                break;
            case 'l':
                b_opt_arg = optarg;
                printf("Our love is %s\n", optarg);
                break;
            case '?':
                printf("arguments error!\n");
                break;
        }
    }
    return 0;
}
输入一个错误的命令行,结果如下:
$ ./opt_parse_demo -l
./opt_parse_demo: option requires an argument -- l
arguments error!
如果不希望输出任何错误信息,或更希望输出自定义的错误信息。可以采用以下两种方法来更改getopt()函数的出错信息输出行为:
  • 在调用getopt()之前,将opterr设置为0,这样就可以在getopt()函数发现错误的时候强制它不输出任何消息。
  • 如果optstring参数的第一个字符是冒号,那么getopt()函数就会保持沉默,并根据错误情况返回不同字符,如下:
    • “无效选项” —— getopt()返回'?',并且optopt包含了无效选项字符(这是正常的行为)。
    • “缺少选项参数” —— getopt()返回':',如果optstring的第一个字符不是冒号,那么getopt()返回'?',这会使得这种情况不能与无效选项的情况区分开。
  • 清单4:

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

int main (int argc, char **argv)
{
    int oc;                     /*选项字符 */
    char ec;                             /*无效的选项字符*/
    char *b_opt_arg;            /*选项参数字串 */

    while((oc = getopt(argc, argv, ":ngl:")) != -1)
    {
        switch(oc)
        {
            case 'n':
                printf("My name is Lyong.\n");
                break;
             case 'g':
                printf("Her name is Xxiong.\n");
                break;
            case 'l':
                b_opt_arg = optarg;
                printf("Our love is %s\n", optarg);
                break;
            case '?':
                ec = (char)optopt;
                printf("无效的选项字符 \' %c \'!\n", ec);
                break;
            case ':':
                printf("缺少选项参数!\n");
                break;
        }
    }
    return 0;
}
测试结果:

$ ./opt_parse_demo -a
无效的选项字符 ' a '!
$ ./opt_parse_demo -l
缺少选项参数!

------ 转载 CSDN

liunx 系统调用 getopt() 函数的更多相关文章

  1. getopt函数的使用——分析命令行参数

    getopt(分析命令行参数) getopt(分析命令行参数) 短参数的定义 返回值 范例 getopt_long 相关函数表头文件#include<unistd.h> 函数声明int g ...

  2. Linux c 下使用getopt()函数

    命令行参数解析函数 —— getopt() getopt()函数声明如下: #include <unistd.h> int getopt(int argc, char * const ar ...

  3. Linux下getopt()函数的简单使用

    最近在弄Linux C编程,本科的时候没好好学啊,希望学弟学妹们引以为鉴. 好了,虽然啰嗦了点,但确实是忠告.步入正题: 我们的主角----getopt()函数. 英雄不问出处,getopt()函数的 ...

  4. C语言-getopt函数

    #include<unistd.h> int getopt(int argc,char *const argv[],const char *optstring); extern char ...

  5. 如何使用getopt()函数解析参数

    最近在写程序的过程中,把一部分时间都花费在程序对参数的处理上.今天听了学长说到getopt函数,才发现原来c里面还有一个专门解决参数处理的函数,查询了相关资料,这里简单总结一下. 使用int main ...

  6. Python中getopt()函数的使用

    在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能.目前有短选项和长选项两种格式.短选项格式为"-"加上单个字母选项:长选项为"--"加 ...

  7. 实验作业:使gdb跟踪分析一个系统调用内核函数

    实验作业:使gdb跟踪分析一个系统调用内核函数(我使用的是getuid) 20135313吴子怡.北京电子科技学院 [第一部分] 根据视频演示的步骤,先做第一部分,步骤如下 ①更新menu代码到最新版 ...

  8. [转载]Linux下getopt()函数的简单使用

    转载源地址:https://www.cnblogs.com/qingergege/p/5914218.html 1.getopt()函数的出处就是unistd.h头文件(哈哈),写代码的时候千万不要忘 ...

  9. Linux getopt()函数 getopt_long()函数---转

    http://hi.baidu.com/scoundrelgg/item/d4083f8412eea05d26ebd97f Linux getopt()函数 getopt_long()函数 get_o ...

随机推荐

  1. 移动WEB 响应式设计 @media总结

    第一种: 在引用样式的时候添加 <link rel="stylesheet" media="mediatype and|not|only (media featur ...

  2. Bootstrap table 元素列内容超长自动折行显示方法?

    共需要四步: 1.在table元素的父容器div加上:class="table-responsive" 3.设置表头th的width:<th width="20%& ...

  3. 平稳切换nginx版本

    html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...

  4. Elasticsearch学习笔记 一

    本文版权归博客园和作者吴双本人共同所有 转载和爬虫请注明原文地址 www.cnblogs.com/tdws. 本文参考和学习资料 <ES权威指南> 一.基本概念 存储数据到ES中的行为叫做 ...

  5. Scala基础之注解(annotation

    在学习Scala的过程中,总会碰到一些注解: // Predef.scala @inline def implicitly[T](implicit e: T) = e @deprecated(&quo ...

  6. 【学习】js学习笔记:数组(一)

    1.创建数组并赋值 //对象方式 var arr=new Array(1,2,3,4); //隐形声明方式 var arr2=[5,6,7,8]; 2.数组可以存储任何类型的数据 3.访问数组,是用下 ...

  7. 张高兴的 Xamarin.Android 学习笔记:(四)常用控件

    示例地址 GitHub : https://github.com/ZhangGaoxing/xamarin-android-demo/tree/master/ControlsDemo

  8. win10 edge扩展

    安装红石预览版 https://dev.windows.com/zh-cn/microsoft-edge/extensions/#available-extensions 微软翻译 鼠标手势

  9. 查漏补缺系列之dapper初体验

    什么是dapper 在维护一些较老的项目的时候,往往我们会用很多sql那么这个时候我们要考虑优化这些项目的时候,我们就可以使用dapper dapper 是一款轻量级的ORM框架,它的优势很多轻量级, ...

  10. 在C#中winform程序中应用nlog日志工具

    在C#中winform程序中应用nlog日志工具,配置文件简单应用. 文件名 nlog.config,请注意修改属性为"始终复制",发布时候容易遇到不存在文件的错误提示. 通过Nu ...