getopt解析

2024-05-27 16:58
文章标签 解析 getopt

本文主要是介绍getopt解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

getopt详解

       The  getopt()  function  parses  the  command-line  arguments.  Its arguments argc and argv are the argument count and array aspassed to the main() function on program invocation.  An element of argv that starts with '-' (and is not exactly "-" or  "--")is  an  option  element.   The  characters  of this element (aside from the initial '-') are option characters.  If getopt() iscalled repeatedly, it returns successively each of the option characters from each of the option elements.The variable optind is the index of the next element to be processed in argv.  The system initializes this  value  to  1.   Thecaller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector.If getopt() finds another option character, it returns that character, updating the external variable optind and a static vari‐able nextchar so that the next call to getopt() can resume the scan with the following option character or argv-element.If there are no more option characters, getopt() returns -1.  Then optind is the index in argv of the first  argv-element  thatis not an option.optstring  is  a  string  containing  the legitimate option characters.  If such a character is followed by a colon, the optionrequires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the followingargv-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  tozero.   This  is  a  GNU extension.  If optstring contains W followed by a semicolon, then -W foo is treated as the long option--foo.  (The -W option is reserved by POSIX.2 for implementation extensions.)  This behavior is a GNU extension, not  availablewith libraries before glibc 2.By  default,  getopt()  permutes  the  contents of argv as it scans, so that eventually all the nonoptions are at the end.  Twoother modes are also implemented.  If the first character of optstring is '+' or the environment  variable  POSIXLY_CORRECT  isset,  then option processing stops as soon as a nonoption argument is encountered.  If the first character of optstring is '-',then each nonoption argv-element is handled as if it were the argument of an option with character code 1.  (This  is  used  byprograms that were written to expect options and other argv-elements in any order and that care about the ordering of the two.)The special argument "--" forces an end of option-scanning regardless of the scanning mode.If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in  optopt,  andreturns '?'.  The calling program may prevent the error message by setting opterr to 0.If  getopt()  finds an option character in argv that was not included in optstring, or if it detects a missing option argument,it returns '?' and sets the external variable optopt to the actual option character.  If the  first  character  (following  anyoptional  '+'  or  '-'  described  above) of optstring is a colon (':'), then getopt() returns ':' instead of '?' to indicate amissing option argument.  If an error was detected, and the first character of optstring is not a colon, and the external vari‐able opterr is nonzero (which is the default), getopt() prints an error message.getopt_long() and getopt_long_only()The getopt_long() function works like getopt() except that it also accepts long options, started with two dashes.  (If the pro‐gram accepts only long options, then optstring should be specified as an empty string (""), not NULL.)  Long option  names  maybe 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.longopts is a pointer to the first element of an array of struct option declared in <getopt.h> asstruct 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_argis: no_argument (or 0) if the option does not take an argument; required_argument (or 1) if the option requires an argu‐ment; 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 flagpoints 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.If longindex is not NULL, it points to a variable which is set to the index of the long option relative to longopts.getopt_long_only()  is  like  getopt_long(), but '-' as well as "--" can indicate a long option.  If an option that starts with'-' (not "--") doesn't match a long option, but does match a short option, it is parsed as a short option instead.RETURN VALUEIf an option was successfully found, then getopt() returns the option character.  If all command-line options have been parsed,then  getopt()  returns  -1.   If  getopt() encounters an option character that was not in optstring, then '?' is returned.  Ifgetopt() encounters an option with a missing argument, then the return value depends on the first character in optstring: if itis ':', then ':' is returned; otherwise '?' is returned.getopt_long()  and  getopt_long_only()  also return the option character when a short option is recognized.  For a long option,they return val if flag is NULL, and 0 otherwise.  Error and -1 returns are the same as for getopt(), plus '?' for an ambiguousmatch or an extraneous parameter.ENVIRONMENTPOSIXLY_CORRECTIf this is set, then option processing stops as soon as a nonoption argument is encountered._<PID>_GNU_nonoption_argv_flags_This  variable was used by bash(1) 2.0 to communicate to glibc which arguments are the results of wildcard expansion andso should not be considered as options.  This behavior was removed in bash(1) version 2.01, but the support  remains  inglibc.CONFORMING TOgetopt():POSIX.2  and  POSIX.1-2001,  provided  the environment variable POSIXLY_CORRECT is set.  Otherwise, the elements of argvaren't really const, because we permute them.  We pretend they're const in the prototype to  be  compatible  with  othersystems.The use of '+' and '-' in optstring is a GNU extension.On  some older implementations, getopt() was declared in <stdio.h>.  SUSv1 permitted the declaration to appear in either<unistd.h> or <stdio.h>.  POSIX.1-2001 marked the use of <stdio.h> for this purpose as LEGACY.   POSIX.1-2001  does  notallow the declaration to appear in <stdio.h>.getopt_long() and getopt_long_only():These functions are GNU extensions.

##简解

这个东西会对argv中的参数进行解析.
首先碰到- 然后对-之后的解析.然后返回-之后的东西. 
如果继续调用,则会返回第二个-之后的东西
//注意:不解析不以-开始的参数,直解析以-开始的参数在解析,其实上面说的不全对,返回的不一定是-之后的东西,他会判定-之后的东西是否在getopt函数的第三个参数中,如果有,则返回,如果没有,则会打印出invalid option -- 'p' ,然后返回一个 ?第三个参数可以为"?hvVDarsuwAJSF:f:" ,f 和 F 必须要加参数 ,有参数 返回f,无参数返回?
//即如果后面有:,则表示要加参数
另外optind是已经被解析的参数个个数+1,即包括命令
而且getopt之后会对argv里面的参数重新排序

##实验代码
点我下载

这篇关于getopt解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1008064

相关文章

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

Golang HashMap实现原理解析

《GolangHashMap实现原理解析》HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持高效的插入、查找和删除操作,:本文主要介绍GolangH... 目录HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Java的栈与队列实现代码解析

《Java的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

java解析jwt中的payload的用法

《java解析jwt中的payload的用法》:本文主要介绍java解析jwt中的payload的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解析jwt中的payload1. 使用 jjwt 库步骤 1:添加依赖步骤 2:解析 JWT2. 使用 N

Python中__init__方法使用的深度解析

《Python中__init__方法使用的深度解析》在Python的面向对象编程(OOP)体系中,__init__方法如同建造房屋时的奠基仪式——它定义了对象诞生时的初始状态,下面我们就来深入了解下_... 目录一、__init__的基因图谱二、初始化过程的魔法时刻继承链中的初始化顺序self参数的奥秘默认

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析