命令行参数解析函数 —— 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. linux strace

    yum install -y strace 若某一进程占用cpu高可以用strace -p pid进行跟踪查看 strace常用来跟踪进程执行时的系统调用和所接收的信号. 在Linux世界,进程不能直 ...

  2. gerrit docker运行失败 chown: /var/gerrit/review_site: Permission denied 【已解决】

    Docker Volume 之权限管理(转) - jackluo - 博客园 http://www.cnblogs.com/jackluo/p/5783116.html 为什么在公司电脑没有问题,但在 ...

  3. UI优化

    进入正题,我们这一篇文章会提到为什么使用HierarchyViewer,怎么使用HierarchyViewer,后者内容会多一下. 为什么使用HierarchyViewer 不合理的布局会使我们的应用 ...

  4. 在HTML页面获取当前系统时间

    <script language="javascript"> function getCurDate() { var d = new Date(); var week; ...

  5. Erlang-基础篇

    一.整数运算: 1.Erlang采用不定长的整数来进行整数的算术演算.在Erlang中,整数运算没有误差,因此无需担心运算溢出,也不用为了一个固定字长容纳不下一个大整数而伤脑筋: 二.变量: 1.所有 ...

  6. iOS 证书申请和使用详解(详细版)

    对于iOS开发者来说,apple开发者账号肯定不会陌生.在开发中我们离不开它.下面我简单的为大家分享一下关于iOS开发中所用的证书相关知识. 第一部分:成员介绍 1.Certification(证书) ...

  7. PHP学习当中遗漏的知识点

    一, 当双引号中包含变量时,变量会与双引号中的内容连接在一起: 当单引号中包含变量时,变量会被当做字符串输出. <?php $love = "I love you!"; $s ...

  8. 【转】MYSQL入门学习之四:MYSQL的数据类型

    转载地址:http://www.2cto.com/database/201212/175536.html 一.整型  www.2cto.com            整数类型是数据库中最基本的数据类型 ...

  9. c#之委托所有方法

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...

  10. Windows手动添加开机启动项

    @方法1. 添加程序完整路径到注册表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run下 或者添加到HKEY_CURREN ...