getopt()

#include <unistd.h>

int getopt(int argc, char * const argv[],
const char *optstring); extern char *optarg;
extern int optind, opterr, optopt;

getopt()函数的作用:解析命令行参数。

当命令行中的元素以"-"开头,那么该元素(argv[i])就是参数选项,其后的字符串就是参数。参数选项列表通过optstring指定。

测试代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> int main(int argc, char** argv)
{
int opt;
printf("optind:%d\n", optind); opt = getopt(argc, argv, "ha:b::"); printf("opt:%d\n", opt);
printf("optarg:%s\n", optarg);
printf("optind:%d\n", optind); return 0;
}

The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector.

optind 的值为 argv中下一个待处理参数的索引值。optind的初始值为1。调用者可以将optind设置为1,来重新扫描argv

图1

从上图可以看出,optind的值为3,即下一个参数的索引值。

optstringi is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. Two colons mean an option takes an optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"), then it is returned in optarg, otherwise optarg is set to zero. This is a GNU extension.

如果optstring中的字符后跟了一个冒号,那么该字符表示参数选项,并且必需带上参数(如果不带参数,会有打印提示);同时optarg指向该参数,如图1所示,optarg指向 参数选项(-a)的参数(abc)。

不带参数,会有打印提示"./getopt_test: option requires an argument -- 'a' "

参数选项和参数之间没有空格分隔,也能正常解析。建议,参数选项和参数之间用空格分隔

如果optstring中的字符后跟了两个冒号,那个该字符表示可选参数选项,若带上参数,那么optarg指向该参数;若没有带上参数,那么optarg为NULL;

两冒号的参数选项,选项和参数之间必须连在一起,否则,optarg获取不到参数值。上图中,-b参数选项是两冒号的,当-b 与参数"qwe"之间有空格时,optarg为NULL。

如果optstring中的字符后没有跟冒号,那么参数选项不需要带参数。

上图中,-h 是不带参数选项,所以optarg指向NULL。

从上图可知,getopt()是不支持long option。如需要支持long option,则要使用getopt_long()函数。

getopt_long()

#include <getopt.h>

int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);

The getopt_long() function works like getopt() except that it also accepts long options, started with two dashes. (If the program accepts only long options, then optstring should be specified as an empty string (""), not NULL.) Long option names may be abbreviated if the abbreviation is unique or is an exact match for some defined option. A long option may take a parameter, of the form --arg=param or --arg param.

getopt_long()的参数选项 是使用 two dashed("--")来指定。如果程序支持 长参数选项,需要将optstring设置为空串("")。长选项参数的目的是为了避免参数产生歧义,只要不产生歧义,也可以只用缩写。

{"device", 2, &flag, 'd'},由上图可知,--devi 由于不会产生歧义,就作为device处理;

\[longopts$$ is a pointer to the first element of an array of **struct option** declared in <getopt.h> as

struct option {
const char *name;
int has_arg;
int *flag;
int val;
};

The meanings of the different fields are:

***name*** is the name of the long option.

***has_arg***
is: no_argument (or 0) if the option does not take an argument; required_argument (or 1) if the option requires an argument; or optional_argument (or 2) if the option takes an optional argument.

***flag*** specifies how results are returned for a long option. If ***flag*** is NULL, then getopt_long() returns ***val***. (For example, the calling program may set ***val*** to the equivalent short option character.) Otherwise, getopt_long() returns 0, and flag points to a variable which is set to val if the option is found, but left unchanged if the option is not found.

***val*** is the value to return, or to load into the variable pointed to by flag.

**The last element of the array has to be filled with zeros**.k

If ***longindex*** is not NULL, it points to a variable which is set to the index of the long option relative to ***longopts***.
\]

int main(int argc, char** argv)
{
int c;
int longindex = 0;
int time = -1; struct option long_option[] =
{
{"help", 0, NULL, 'h'},
{"time", 1, &time, 't'},
{"device", 2, NULL, 'd'},
{NULL, 0, NULL, 0},
}; c = getopt_long(argc, argv, "ht:d:", long_option, &longindex); printf("c:%d\n", c);
printf("optarg:%s\n", optarg);
printf("optind:%d\n", optind);
printf("longindex:%d\n", longindex);
printf("time=%d\n", time); return 0;
}

如果flag为NULL,getopt_long()的返回值为val(即对应的 短参数选项字符的值);如果指定了flag,getopt_long的返回值为0,若有指定相应的option,则flag的值为val。

指定了flag,getopt_long的返回值c等于0;flag变量time的值为字符't'的值。longindex指向longopts数组的第一个元素。

flag为NULL,getopt_long的返回值c等于字符'd'的值。

--arg=param和--arg param的区别

建议 使用 --arg=param 格式。

int main(int argc, char** argv)
{
int ret = -1;
int longindex = 0; struct option long_option[] =
{
{"help", 0, NULL, 'h'},
{"time", 1, NULL, 't'},
{"device", 2, NULL, 'd'},
{"debug", 1, NULL, 'd'},
{NULL, 0, NULL, 0},
}; while((ret = getopt_long(argc, argv, "ht:d:", long_option, &longindex)) >= 0)
{
switch(ret)
{
case 'h':
printf("help\n");
break;
case 't':
printf("optind:%d\n", optind);
printf("longindex:%d\n", longindex);
printf("time:%s\n", optarg);
break;
case 'd':
printf("optind:%d\n", optind);
printf("longindex:%d\n", longindex);
if (0 == strcmp("device", long_option[longindex].name))
{
printf("device:%s\n", optarg);
}
else if (0 == strcmp("debug", long_option[longindex].name))
{
printf("debug:%s\n", optarg);
}
break;
default:
printf("?? getopt returned character code 0x%x ??\n", ret);
break;
}
} return 0;
}

https://github.com/suonikeyinsuxiao/trunk/blob/master/libc/basic/usage/notes/getopt.md

c语言基础之getopt()的更多相关文章

  1. 《MSSQL2008技术内幕:T-SQL语言基础》读书笔记(下)

    索引: 一.SQL Server的体系结构 二.查询 三.表表达式 四.集合运算 五.透视.逆透视及分组 六.数据修改 七.事务和并发 八.可编程对象 五.透视.逆透视及分组 5.1 透视 所谓透视( ...

  2. 《MSSQL2008技术内幕:T-SQL语言基础》读书笔记(上)

    索引: 一.SQL Server的体系结构 二.查询 三.表表达式 四.集合运算 五.透视.逆透视及分组 六.数据修改 七.事务和并发 八.可编程对象 一.SQL Server体系结构 1.1 数据库 ...

  3. C#语言基础

    第一部分 了解C# C#是微软公司在2000年7月发布的一种全新且简单.安全.面向对象的程序设计语言,是专门为.NET的应用而开发的.体现了当今最新的程序设计技术的功能和精华..NET框架为C#提供了 ...

  4. C语言基础回顾

    第一章 C语言基础 1.  C语言编译过程 预处理:宏替换.条件编译.头文件包含.特殊符号 编译.优化:翻译并优化成等价的中间代码表示或汇编代码 汇编:生成目标文件,及与源程序等效的目标的机器语言代码 ...

  5. 黑马程序员_ C语言基础(二)

    ------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- 概览 今天基础知识分为以下几点内容(注意:循环.条件语句在此不再赘述):   1.Hello W ...

  6. C#语言基础— 输入与输出

    C#语言基础— 输入与输出 1.1函数的四要素:名称.输入.输出.加工 1.2主函数:输出语句.输入语句: Static viod Main(string[] stgs)//下划线部分可以自己指定 { ...

  7. 【GoLang】GO语言系列--002.GO语言基础

    002.GO语言基础 1 参考资料 1.1 http://www.cnblogs.com/vimsk/archive/2012/11/03/2736179.html 1.2 https://githu ...

  8. R语言基础:数组&列表&向量&矩阵&因子&数据框

    R语言基础:数组和列表 数组(array) 一维数据是向量,二维数据是矩阵,数组是向量和矩阵的直接推广,是由三维或三维以上的数据构成的. 数组函数是array(),语法是:array(dadta, d ...

  9. OC语言基础知识

    OC语言基础知识 一.面向对象 OC语言是面向对象的,c语言是面向过程的,面向对象和面向过程只是解决问题的两种思考方式,面向过程关注的是解决问题涉及的步骤,面向对象关注的是设计能够实现解决问题所需功能 ...

随机推荐

  1. ESP8266 AT指令开发(基于STC89C52单片机): 硬件使用说明

    实物图 硬件说明 开发板板载说明: 1.主控芯片: STC89C52 2.Wi-Fi模块: ESP8266 3.温湿度传感器: DHT11 4.液晶屏: IIC OLED 5.继电器: 220V 10 ...

  2. CSP2019 树的重心 题解

    本题当然可以通过大力讨论每棵子树的size的大小关系,然后用各种数据结构暴力维护.但是我更倾向于用一种更为性质的做法. 首先讲一下我在考场上想到的做法(没写).就是考虑换根,在换根的过程中计算每一条边 ...

  3. [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  4. Salesforce 开发整理(十)项目部署总结

    项目部署顺序 全局值集 小组 自定义字段-对象-设置(SF1 紧凑布局要和记录类型在这里要一起部署) 邮件模板-静态资源 角色 工作流-流定义(包含进程生成器) 批准过程 开发部署<Apex类, ...

  5. python脚本生成exe程序

    去年十一月换了新公司后,一直没闲着,马不停蹄地接不同的需求,一个版本一个版本的迭代,也没时间研究python了.十一休假归来,某日,老婆问金融量化需要学python吗?并分享了一个公众号文章,内容是吹 ...

  6. 【阿里云IoT+YF3300】2.阿里云IoT云端通信Alink协议介绍

    如果单单只有MQTT协议,也许很难支撑起阿里这个IoT大厦.Alink协议的出现,不仅仅是数据从传感端搬到云端,它就如基因图谱,它勾画了一个大厦的骨架,有了它,才有了IoT Studio,才有了大数据 ...

  7. nginx 目录自动加斜线”/”

    默认配置当你访问http://abc.example.com/dir 时不会加”/” 常见做法 if (-d $request_filename){  rewrite ^/(.*)([^/])$ ht ...

  8. SDK-基于Windows环境搭建

    SDK安装配置 前言:相信很多小伙伴还不会搭SDK,近日一位前同事询问我SDK怎么搭建了?不妨看看吧,小编是基于appium. 1.下载SDK:http://tools.android-studio. ...

  9. 【javascript】判断是否为正整数

    function isNormalInteger(str) { var n = Math.floor(Number(str)); return n !== Infinity && St ...

  10. Docker 安装 Request Tracker 工单系统

    1.需求 docker 安装工单系统 Request Tracker,并需要支持 LDAP 登入. 2.制作镜像 1)request-tracker-base镜像 第一个镜像安装一些基础支持软件,如 ...