热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

浅析linux的命令行的参数getopt_long函数

前言在linux中,经常需要各种命令,



前言

在linux中,经常需要各种命令,通常情况下都会带各种参数,而这些参数是如何解析的呢?通常使用GNU C提供的函数getopt、getopt_long、getopt_long_only函数来解析命令行参数。

一、关于命令行参数

命令行参数可以分为两类,一类是短选项,一类是长选项,短选项在参数前加一杠"-",长选项在参数前连续加两杠"–",如下表(ls 命令参数)所示,其中-a,-A,-b都表示短选项,–all,–almost-all, --author都表示长选项。他们两者后面都可选择性添加额外参数。比如–block-size=SIZE,SIZE便是额外的参数。

浅析linux的命令行的参数getopt_long函数 - 文章图片

二、getopt_long函数

getopt函数只能处理短选项,而getopt_long函数两者都可以,可以说getopt_long已经包含了getopt_long的功能。因此,这里就只介绍getopt_long函数。而getopt_long与getopt_long_only的区别很小,等介绍完getopt_long,在提起会更好。

#include
extern char *optarg;
extern int optind, opterr, optopt;
#include
int getopt(int argc, char * const argv[],const char *optstring);
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
int getopt_long_only(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);

参数以及返回值介绍(以上三个函数都适用):

1、argc和argv和main函数的两个参数一致。

2、optstring: 表示短选项字符串。

形式如“a:b::cd:“,分别表示程序支持的命令行短选项有-a、-b、-c、-d,冒号含义如下:
(1)只有一个字符,不带冒号——只表示选项, 如-c
(2)一个字符,后接一个冒号——表示选项后面带一个参数,如-a 100
(3)一个字符,后接两个冒号——表示选项后面带一个可选参数,即参数可有可无, 如果带参数,则选项与参数直接不能有空格
形式应该如-b200

3、longopts:表示长选项结构体。结构如下:

struct option
{
const char *name;
int has_arg;
int *flag;
int val;
};
eg:
static struct option longOpts[] = {
{ "daemon", no_argument, NULL, 'D' },
{ "dir", required_argument, NULL, 'd' },
{ "out", required_argument, NULL, 'o' },
{ "log", required_argument, NULL, 'l' },
{ "split", required_argument, NULL, 's' },
{ "http-proxy", required_argument, &lopt, 1 },
{ "http-user", required_argument, &lopt, 2 },
{ "http-passwd", required_argument, &lopt, 3 },
{ "http-proxy-user", required_argument, &lopt, 4 },
{ "http-proxy-passwd", required_argument, &lopt, 5 },
{ "http-auth-scheme", required_argument, &lopt, 6 },
{ "version", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, 'h' },
{ 0, 0, 0, 0 }
};

(1)name:表示选项的名称,比如daemon,dir,out等。

(2)has_arg:表示选项后面是否携带参数。该参数有三个不同值,如下:

a: no_argument(或者是0)时 ——参数后面不跟参数值,eg: --version,–help b:
required_argument(或者是1)时 ——参数输入格式为:–参数 值 或者 --参数=值。eg:–dir=/home c:
optional_argument(或者是2)时 ——参数输入格式只能为:–参数=值

(3)flag:这个参数有两个意思,空或者非空。

a:如果参数为空NULL,那么当选中某个长选项的时候,getopt_long将返回val值。
eg,可执行程序 --help,getopt_long的返回值为h. b:如果参数不为空,那么当选中某个长选项的时候,getopt_long将返回0,并且将flag指针参数指向val值。
eg: 可执行程序 --http-proxy=127.0.0.1:80 那么getopt_long返回值为0,并且lopt值为1。

(4)val:表示指定函数找到该选项时的返回值,或者当flag非空时指定flag指向的数据的值val。

4、longindex:longindex非空,它指向的变量将记录当前找到参数符合longopts里的第几个元素的描述,即是longopts的下标值。

5、全局变量:

(1)optarg:表示当前选项对应的参数值。
(2)optind:表示的是下一个将被处理到的参数在argv中的下标值。
(3)opterr:如果opterr = 0,在getopt、getopt_long、getopt_long_only遇到错误将不会输出错误信息到标准输出流。opterr在非0时,向屏幕输出错误。
(4)optopt:表示没有被未标识的选项。

6、返回值:

  1. 如果短选项找到,那么将返回短选项对应的字符。
  2. 如果长选项找到,如果flag为NULL,返回val。如果flag不为空,返回0
  3. 如果遇到一个选项没有在短字符、长字符里面。或者在长字符里面存在二义性的,返回“?”
  4. 如果解析完所有字符没有找到(一般是输入命令参数格式错误,eg: 连斜杠都没有加的选项),返回“-1”
  5. 如果选项需要参数,忘了添加参数。返回值取决于optstring,如果其第一个字符是“:”,则返回“:”,否则返回“?”。

注意:

(1)longopts的最后一个元素必须是全0填充,否则会报段错误

(2)短选项中每个选项都是唯一的。而长选项如果简写,也需要保持唯一性。

三、测试(自行测试)

#include /* for printf */
#include /* for exit */
#include
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;
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:
printf("option %s", 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 '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind printf("non-option ARGV-elements: ");
while (optind printf("%s ", argv[optind++]);
printf("\n");
}
exit(EXIT_SUCCESS);
}

2、自己项目相关一个例子。

#include
#include
#include
#include
#include
using namespace std;
void showUsage() {
//cout <<"Usage: " < cout <<"Options:" < cout <<" -d, --dir=DIR The directory to store downloaded file." < cout <<" -o, --out=FILE The file name for downloaded file." < cout <<" -l, --log=LOG The file path to store log. If '-' is specified," < cout <<" log is written to stdout." < cout <<" -D, --daemon Run as daemon." < cout <<" -s, --split=N Download a file using s connections. s must be" < cout <<" between 1 and 5. If this option is specified the" < cout <<" first URL is used, and the other URLs are ignored." < cout <<" --http-proxy=HOST:PORT Use HTTP proxy server. This affects to all" < cout <<" URLs." < cout <<" --http-user=USER Set HTTP user. This affects to all URLs." < cout <<" --http-passwd=PASSWD Set HTTP password. This affects to all URLs." < cout <<" --http-proxy-user=USER Set HTTP proxy user. This affects to all URLs" < cout <<" --http-proxy-passwd=PASSWD Set HTTP proxy password. This affects to all URLs." < cout <<" --http-auth-scheme=SCHEME Set HTTP authentication scheme. Currently, BASIC" < cout <<" is the only supported scheme." < cout <<" -v, --version Print the version number and exit." < cout <<" -h, --help Print this message and exit." < cout <<"URL:" < cout <<" You can specify multiple URLs. All URLs must point to the same file" < cout <<" or a download fails." < cout <<"Examples:" < cout <<" Download a file by 1 connection:" < cout <<" aria2c http://AAA.BBB.CCC/file.zip" < cout <<" Download a file by 2 connections:" < cout <<" aria2c -s 2 http://AAA.BBB.CCC/file.zip" < cout <<" Download a file by 2 connections, each connects to a different server." < cout <<" aria2c http://AAA.BBB.CCC/file.zip http://DDD.EEE.FFF/GGG/file.zip" < cout <<"Reports bugs to " <}
int main(int argc, char* argv[]) {
bool stdoutLog = false;
string logfile;
string dir;
string ufilename;
int split = 0;
bool daemOnMode= false;
int c;

while(1) {
int optIndex = 0;
int lopt;
static struct option longOpts[] = {
{ "daemon", no_argument, NULL, 'D' },
{ "dir", required_argument, NULL, 'd' },
{ "out", required_argument, NULL, 'o' },
{ "log", required_argument, NULL, 'l' },
{ "split", required_argument, NULL, 's' },
{ "http-proxy", required_argument, &lopt, 1 },
{ "http-user", required_argument, &lopt, 2 },
{ "http-passwd", required_argument, &lopt, 3 },
{ "http-proxy-user", required_argument, &lopt, 4 },
{ "http-proxy-passwd", required_argument, &lopt, 5 },
{ "http-auth-scheme", required_argument, &lopt, 6 },
{ "version", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, 'h' },
{ 0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "Dd:o:l:s:vh", longOpts, &optIndex);
printf("返回值: %c\n",c);
if(c == -1) {
break;
}
switch(c) {
case 0:{
switch(lopt) {
case 1: {
printf("1: %s\n",optarg);
break;
}
case 2:
printf("2: %s\n",optarg);
break;
case 3:
printf("3: %s\n",optarg);
break;
case 4:
printf("4: %s\n",optarg);
break;
case 5:
printf("5: %s\n",optarg);
break;
case 6:
printf("6: %s\n",optarg);
break;
}
break;
}
case 'D':
printf("D: %s\n",optarg);
break;
case 'd':
printf("d: %s\n",optarg);
break;
case 'o':
printf("o: %s\n",optarg);
break;
case 'l':
printf("l: %s\n",optarg);
break;
case 's':
printf("s: %s\n",optarg);
break;
case 'v':
printf("s: %s\n",optarg);
//showVersion();
exit(0);
case 'h':
showUsage();
exit(0);
default:
showUsage();
exit(1);
}
}
return 0;
}


推荐阅读
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
  • Linux环境变量函数getenv、putenv、setenv和unsetenv详解
    本文详细解释了Linux中的环境变量函数getenv、putenv、setenv和unsetenv的用法和功能。通过使用这些函数,可以获取、设置和删除环境变量的值。同时给出了相应的函数原型、参数说明和返回值。通过示例代码演示了如何使用getenv函数获取环境变量的值,并打印出来。 ... [详细]
  • 本文介绍了一个题目的解法,通过二分答案来解决问题,但困难在于如何进行检查。文章提供了一种逃逸方式,通过移动最慢的宿管来锁门时跑到更居中的位置,从而使所有合格的寝室都居中。文章还提到可以分开判断两边的情况,并使用前缀和的方式来求出在任意时刻能够到达宿管即将锁门的寝室的人数。最后,文章提到可以改成O(n)的直接枚举来解决问题。 ... [详细]
  • 本文讨论了clone的fork与pthread_create创建线程的不同之处。进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合。在调用系统调用fork创建一个进程时,子进程只是完全复制父进程的资源,这样得到的子进程独立于父进程,具有良好的并发性。但是二者之间的通讯需要通过专门的通讯机制,另外通过fork创建子进程系统开销很大。因此,在某些情况下,使用clone或pthread_create创建线程可能更加高效。 ... [详细]
  • 本文讨论了一个数列求和问题,该数列按照一定规律生成。通过观察数列的规律,我们可以得出求解该问题的算法。具体算法为计算前n项i*f[i]的和,其中f[i]表示数列中有i个数字。根据参考的思路,我们可以将算法的时间复杂度控制在O(n),即计算到5e5即可满足1e9的要求。 ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Go GUIlxn/walk 学习3.菜单栏和工具栏的具体实现
    本文介绍了使用Go语言的GUI库lxn/walk实现菜单栏和工具栏的具体方法,包括消息窗口的产生、文件放置动作响应和提示框的应用。部分代码来自上一篇博客和lxn/walk官方示例。文章提供了学习GUI开发的实际案例和代码示例。 ... [详细]
  • Go语言实现堆排序的详细教程
    本文主要介绍了Go语言实现堆排序的详细教程,包括大根堆的定义和完全二叉树的概念。通过图解和算法描述,详细介绍了堆排序的实现过程。堆排序是一种效率很高的排序算法,时间复杂度为O(nlgn)。阅读本文大约需要15分钟。 ... [详细]
  • Java自带的观察者模式及实现方法详解
    本文介绍了Java自带的观察者模式,包括Observer和Observable对象的定义和使用方法。通过添加观察者和设置内部标志位,当被观察者中的事件发生变化时,通知观察者对象并执行相应的操作。实现观察者模式非常简单,只需继承Observable类和实现Observer接口即可。详情请参考Java官方api文档。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
author-avatar
mobiledu2502901317
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有