getopt_long 函数的使用

2023-10-31

        getopt_long 函数的使用网上已经有很多了,这里只是记录一下方便自己后续查找。首先函数原型声明:

#include <getopt.h>

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

函数是用于解析命令行参数的,与函数 getopt() 函数是相似的,它可以处理长选项,即两个短杠"--" 连接的参数选项。而且比 getopt() 多两个参数。

参数说明:

1,argc        一般就是 main 函数里的 argc

2,argv    同上

3,optstring  要匹配的参数,如:"ha" 或  "h:a" 或 "h:a::",带一个冒号的表示此选项须带参数,两个冒号的表示是可选参数

4,longopts 这个是长选项结构的指针,一般传的是数组

5,longindex  如果不为空,它将指向 longopts 的一个元素的位置,即longopts的数组下标

结构体类型 struct option 声明为:

struct option {
   const char *name; /*这个就是长选项的名称*/
   int         has_arg; /*指示是否带参数*/
   int        *flag;
   int         val; /*如果flag=NULL, 匹配到时返回这个值*/
};

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.

 直接用 man 手册上的例子说明:

#include <getopt.h>
#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */

int main(int argc, char *argv[])
{
	int c;
	int digit_optind = 0;

	while (1) {
		int this_option_optind = optind ? optind : 1;
		int option_index = 0;
		
		/*长选项的匹配只要匹配到前n个字符相同就会返回,若是模棱两可时会返回?,同时stderr会有相应打印*/
		static struct option long_options[] = {
		   {"add",     required_argument, 0,  0 },
		   {"append",  no_argument,       0,  0 },
		   {"delete",  required_argument, 0,  0 },
		   {"verbose", no_argument,       0,  0 },
		   {"create",  required_argument, 0, 'c'},
		   {"file",    required_argument, 0,  0 },
		   {0,         0,                 0,  0 }
	   };
		
		/*短选项跟一个冒号表示有选项参数,两个冒号表示选项参数可选*/
	   c = getopt_long(argc, argv, "abc:d:012",
					   long_options, &option_index);
	   if (c == -1)
		   break;

	   switch (c) {
	   case 0: /* 匹配到长选项时,返回的val,即struct optaion 中的 val,这里为 0 则表示匹配到 add、append, delete, verbose, file时都会跟到这个 case, 而create 则匹配到字符'c'*/
			printf("get option_index = %d, option %s", option_index, long_options[option_index].name);
			if (optarg)
			   printf(" with arg %s", optarg);
			printf("\n");
			break;

	   case '0':
	   case '1':
	   case '2':
			if (digit_optind != 0 && digit_optind != this_option_optind)
			 printf("digits occur in two different argv-elements.\n");
			digit_optind = this_option_optind;
			printf("option %c\n", c);
			break;

	   case 'a':
			printf("option a\n");
			break;

	   case 'b':
			printf("option b\n");
			break;

	   case 'c':
			printf("option c with value '%s'\n", optarg);
			break;

	   case 'd':
			printf("option d with value '%s'\n", optarg);
			break;

	   case '?': /*ambiguous 模棱两可的时候返回? 如只输入 --a 则会匹配到 add 和 append*/
			printf("it's ambiguous, please selete one\n");
			break;
		
	   default:
			printf("?? getopt returned character code 0%o ??\n", c);
	   }
	}

	if (optind < argc) {
		printf("non-option ARGV-elements: ");
		while (optind < argc)
		   printf("%s ", argv[optind++]);
		printf("\n");
	}

	exit(EXIT_SUCCESS);
}

getopt_long() 函数支持短选项和长选项,如:

 

可以看到短选项时,如果需要带参数, 参数可以直接紧跟选项或是位于空格之后 。而长选项则需要加"=",如:

长选项只要匹配到前n(n<=strlen(name))个字符就可以。如果有多个匹配到则返回 ?,同时stderr 会有输出信息。这个函数里涉及到的全局变量:

1,optind  表示在argv中要处理的下一个元素的索引

2,optarg 当匹配到选项时,它指向的就是选项的参数,如上面的iii, jj, aa, 000

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

getopt_long 函数的使用 的相关文章

随机推荐

  • 关于频率综合器

    完整版请参考 https mazhaoxin github io 2018 08 12 About Frequency Synthesizer http 483v7j coding pages com 2018 08 12 About Fr
  • 跳表

    跳表 前言 一 什么是跳表 二 跳表的时间复杂度 三 跳表的空间复杂度 四 高效的动态插入和删除 1 插入操作 2 删除操作 五 跳表退化与跳表索引的动态更新 前言 对于二分查找算法 其底层依赖支持随机查找特性的数组 一般情况下只能依靠数组
  • R语言与线性回归分析

    文章目录 1 原始数据的分析 2 回归模型的拟合 参数估计和检验 3 变量选择 4 回归诊断 5 改进措施 6 岭回归 8 其他 基本假设 正态性 独立性 线性 同方差性 常用R包 car carData MASS leap 1 原始数据的
  • paddleocr 训练自己的数据,详细笔记

    目录 算法原理 第一步 制作数据集 数据标注工具 可视化标注 一定要制
  • MYSQL数据库部署--5.7版本数据库部署

    目录 MySQL5 7安装 二进制方式安装 一 安装前的准备 二 安装MySQL数据库 1 解压MySQL安装包 2 将解压后的文件拷贝到安装路径下 3 修改文件的权限 4 创建存放data的文件夹 5 在 etc下创建mysql的参数文件
  • Dubbo admin安装教程

    github下载代码 git clone https github com apache dubbo admin git 打包dubbo admin server java jar 运行 想看的界面需要按照nodejs Node js 完成
  • 全面总结: Golang 调用 C/C++,例子式教程

    https www cnblogs com linguanh p 8323487 html 掘金 https juejin im user 587f0dfe128fe100570ce2d8 博客 http www cnblogs com l
  • 2021.12.6—12.11周总结

    1 将数据结构的查找这一章学完了 线性表 顺序 折半 分块 和树表 二叉排序树 平衡二叉树 B 树和B 树 哈希表 的查找 2 前端的期末作品肝完了 三四天 基本上来说 后续有空应该会继续完善 3 写算法题 准备蓝桥杯吧 虽然过不了 还是去
  • 盒子集成weith,不继承height

    div class fa div class son 111 div div
  • 毕业设计-基于机器学习的短期负荷预测算法

    目录 前言 课题背景和意义 实现技术思路 一 电力负荷预测 二 典型负荷预测算法 实现效果图样例 最后 前言 大四是整个大学期间最忙碌的时光 一边要忙着备考或实习为毕业后面临的就业升学做准备 一边要为毕业设计耗费大量精力 近几年各个学校要求
  • GO如何编写一个 Worker Pool

    作者 JustLorain https juejin cn post 7244733519948333111 前言 池化技术是一种资源管理技术 它通过提前创建和维护一组可重用的资源实例池 以便在需要时快速分配和回收这些资源 协程 gorou
  • java远程关机_java远程开关机

    packagetestFrame importjava awt Color importjava awt Font importjava awt event ActionEvent importjava awt event ActionLi
  • 关于STM32 下载程序下方提示internal command error的解决办法

    最近在调试一块板子 使用的是STM32CubeMx生成 结果发现 自己在烧写程序完成后 再次烧写就无法烧写成功 一直提示No Target connect 后在bulid output中发现了一个问题 在bulid output下方提示in
  • Memcache图形化管理工具MemAdmin

    1 美图 2 概述 下面给大家介绍一款 memcache图形化管理工具 MemAdmin 下载地址 http www junopen com memadmin MemAdmin是一款可视化的Memcached管理与监控工具 使用PHP开发
  • python网络爬虫之Max retries exceeded with url错误

    ConnectionError HTTPSConnectionPool host cq feibaos com port 443 Max retries exceeded with url news lists notice html re
  • IDEA导入本地项目

    1 文件 New Model from Existing Sources 2 选中需要导入的项目 3 选择maven文件选项 从外部模型导入模块 Idea本地项目部署路径 IDEA不会把你的项目部署到你的Tomcat安装目录 它会在操作系统
  • Weblogic SSRF漏洞

    1 漏洞描述 weblogic中存在SSRF漏洞 利用该漏洞可以发送任意HTTP请求 进而攻击内网中redis fastcgi等脆弱组件 2 影响版本 weblogic 10 0 2 10 3 6版本 3 POC http 192 168
  • 深入理解数据结构——堆栈的基本操作

    include
  • 版本号命名指南

    首先看看某些常见软件的版本号 Linux Kernel 0 0 1 1 0 0 2 6 32 3 0 18 若用 X Y Z 表示 则偶数 Y 表示稳定版本 奇数 Y 表示开发版本 Windows windows 98 windows 20
  • getopt_long 函数的使用

    getopt long 函数的使用网上已经有很多了 这里只是记录一下方便自己后续查找 首先函数原型声明 include