命令行参数解析函数 —— 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,此任务就完成了。(所以一般使用 while(opt != -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()函数的出错信息输出行为:
  1. 在调用getopt()之前,将opterr设置为0,这样就可以在getopt()函数发现错误的时候强制它不输出任何消息。
  2. 如果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
缺少选项参数!

Linux c 下使用getopt()函数的更多相关文章

  1. Windows及Linux平台下的计时函数总结

    本文对Windows及Linux平台下常用的计时函数进行总结,包括精度为秒.毫秒.微秒三种精度的各种函数.比如Window平台下特有的Windows API函数GetTickCount().timeG ...

  2. Unix/Linux系统下获得时间戳函数

    在Unix/Linux系统下,使用gettimeofday函数来获得当前系统的时间戳,精度可达到微秒(microsecond,即μs)级别. 通过结构体timeval来存放当前时间戳的信息: #ifn ...

  3. 多线程编程之Linux环境下的多线程(一)

    一.Linux环境下的线程 相对于其他操作系统,Linux系统内核只提供了轻量级进程的支持,并未实现线程模型.Linux是一种“多进程单线程”的操作系统,Linux本身只有进程的概念,而其所谓的“线程 ...

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

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

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

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

  6. Linux下getopt()函数

    from https://www.cnblogs.com/qingergege/p/5914218.html 最近在弄Linux C编程,本科的时候没好好学啊,希望学弟学妹们引以为鉴. 好了,虽然啰嗦 ...

  7. windows下的getopt/getoptlong函数

    windows下的getopt/getoptlong函数 getopt/getopt_long函数是GNU C中的函数,在linux编程中很常用到.这里就不介绍了. windows下没有找到类似的函数 ...

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

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

  9. Linux下利用ioctl函数获取网卡信息

    linux下的ioctl函数原型如下: #include <sys/ioctl.h> int ioctl(int handle, int cmd, [int *argc, int argv ...

随机推荐

  1. button改变背景与文字颜色

    1.定义/zhsh/res/color/txt_guide_selector.xml <?xml version="1.0" encoding="utf-8&quo ...

  2. android 学习随笔二十二(小结)

    ADB进程 * adb指令 * adb install xxx.apk * adb uninstall 包名 * adb devices * adb start-server * adb kill-s ...

  3. 给文件加ip访问限制

    获取IP: function getIP(){ return isset($_SERVER['HTTP_X_FORWARDED_FOR'])? $_SERVER['HTTP_X_FORWARDED_F ...

  4. 【PHP设计模式 06_GuanChaZhe.php】观察者模式

    <?php /** * [观察者模式] * PHP5中提供了 观察者(observer) 和 被观察者(subject) 的接口 * 在手册搜索:SplSubject (PHP 5 >= ...

  5. class id 区别

    [1].id是唯一的,一个元素只能有一个,不能重复class可以重复 <div> <img src="" width="100%"/> ...

  6. System.exit(0)和System.exit(1)区别:

    System.exit(0)是将你的整个虚拟机里的内容都停掉了,而finish()只是退出了activity,并没有退出应用,Application还是存在于内存中的,除非被系统回收.无论如何,内存都 ...

  7. syntactically incorrect() 404

    遇到这个错误就来记录一下吧. 这个错误是springMVC报出的错误.大致的意思就是form传值的类型和controller中的参数不符. 有可能是名字错误,有可能是类型不对.比如前面你传来的是  p ...

  8. hdu1081 To the Max

    直接暴力枚举所有子矩形至少需要O(n^4)的复杂度,显然这不是一个合理的解决方法. 上述方案忽略了矩形之间的联系,进行了过多不必要的计算. 实际上如果固定矩形的左右边界,则底边在i行的矩形内数值之和与 ...

  9. Google Analytics Premium VS Adobe Analytics

    在很久以前的互联网年代,Google收购了一家名为Urchin的公司,进而演化诞生了Google Analytics.当Goochin(Google / Urchin)首次亮相时,它被所有人称为“新的 ...

  10. 周赛-Heros and Swords 分类: 比赛 2015-08-02 08:30 11人阅读 评论(0) 收藏

    Heros and Swords Time Limit: 6000/3000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others) Su ...