optarg与getopt的用法

optarg与getopt的用法

这里是我遇到的问题,不想看的,可直接跳过,去下面看解释

前言:

今天在一个项目里的iReadOptions(int argc, char **argv)函数里遇到extern char *optarg;我知道这是引用外部声明的变量,我当时就突发奇想,想看看这个外部变量是在什么地方定义的,又在外部文件中有什么作用,于是我就在那个库里挨个文件找optarg,找到最后都没有找到optarg,我就开始郁闷了,那函数iReadOptions的optarg引用的是哪里的变量?于是我就有去百度寻找答案,最后寻找到了下面的一些信息,才解决了我的疑惑

正文:

getopt被用来解析命令行选项参数。就不用自己写东西处理argv了

#include

extern char *optarg; //选项的参数指针

extern int optind, //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。

extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。

extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回’?’、

int getopt(int argc, char * const argv[], const char *optstring);

调用一次,返回一个选项。 在命令行选项参数再也检查不到optstring中包含的选项时,返回-1,同时optind储存第一个不包含选项的命令行参数。

首先说一下什么是选项,什么是参数。

字符串optstring可以下列元素,

1.单个字符,表示选项,

2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。

3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。

getopt处理以’-’开头的命令行参数,
如optstring=“ab:c::d::”,
命令行为 getopt.exe -a -b host -ckeke -d haha
在这个命令行参数中,-a和-h就是选项元素,去掉’-’,a,b,c就是选项。host是b的参数,keke是c的参数。但haha并不是d的参数,因为它们中间有空格隔开。

还要注意的是默认情况下getopt会重新排列命令行参数的顺序,所以到最后所有不包含选项的命令行参数都排到最后。
如getopt.exe -a ima -b host -ckeke -d haha, 都最后命令行参数的顺序是: -a -b host -ckeke -d ima haha

如果optstring中的字符串以’+'加号开头或者环境变量POSIXLY_CORRE被设置。那么一遇到不包含选项的命令行参数,getopt就会停止,返回-1。

#include

#include

#include

int main(int argc, char **argv)

{

int result;

    opterr = 0;  //使getopt不行stderr输出错误信息

    while( (result = getopt(argc, argv, "ab:c::")) != -1 )

	{
	
	switch(result)
	
		{

		case 'a':
		
		printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
		
		break;
		
		case 'b':
		
		printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
		
		break;
		
		case 'c':
		
		printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
		
		break;
		
		case '?':
		
		printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
		
		break;
		
		default:
		
		printf("default, result=%c\n",result);
		
		break;

		}

	printf("argv[%d]=%s\n", optind, argv[optind]);

	}

	printf("result=-1, optind=%d\n", optind);   //看看最后optind的位置

    for(result = optind; result < argc; result++)

		printf("-----argv[%d]=%s\n", result, argv[result]);


 //看看最后的命令行参数,看顺序是否改变了哈。

	for(result = 1; result < argc; result++)

		printf("\nat the end-----argv[%d]=%s\n", result, argv[result]);

	return 0;

}

unistd里有个 optind 变量,每次getopt后,这个索引指向argv里当前分析的字符串的下一个索引,因此

argv[optind]就能得到下个字符串,通过判断是否以 '-'开头就可。下面是个测试程序

#include

#include

int main(int argc, char* argv[])
{
int tmp = 4;
	while( (tmp = getopt(argc, argv, "abck")) != -1  )
	{
		printf("-%c\t", tmp);
		int opt = optind ;
		while( opt < argc )
		{
			if ( argv[opt][0] != '-' )
			{
				printf("%s\t", argv[opt]);
				opt ++;
			}
			else
				break;
		}
	printf("\n");

	}
getchar();
}

函数说明 getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错 信息,则只要将全域变量opterr设为0即可

返回值 如果找到符合的参数则返回此参数字母,如果参数不包含在参数optstring 的选项字母则返回“?”字符,分析结束则返回-1。

范例  #include<stdio.h>
#include<unistd.h>
int main(int argc,char **argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,”a:bcde”))!= -1)
switch(ch)
{
case ‘a’:
printf(“option a:’%s’\n”,optarg);
break;
case ‘b’:
printf(“option b :b\n”);
break;
default:
printf(“other option :%c\n”,ch);
}
printf(“optopt +%c\n”,optopt);
}

执行 $./getopt –b
option b:b
$./getopt –c
other option:c
$./getopt –a
other option :?
$./getopt –a12345
option a:’12345’

  • 12
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
getoptLinux下的一个命令行参数解析函数。其基本的语法格式为: getopt [选项] 参数列表 其中,选项的格式为: -a 或 --all:匹配所有选项 -b 或 --brief:简短模式,只输出短选项 -l 或 --longoptions:长选项 -o 或 --options:短选项 -n 或 --name:命令名称,一般不需要指定 -p 或 --shell:指定shell,一般不需要指定 -q 或 --quiet:安静模式,不输出错误信息 -r 或 --long-only:只支持长选项 -s 或 --silent:安静模式,不输出错误信息 -u 或 --unquoted:不转义引号 -- :结束选项列表,后面的参数都是非选项参数 使用getopt函数时,需要先定义一个选项字符串,选项字符串中包含了程序支持的所有选项,格式为“短选项字母:”,其中,短选项字母表示选项的名称,冒号表示该选项需要一个参数。例如,选项字符串“abc:def:”表示程序支持选项a、b、c、d、e、f,其中选项d和e需要一个参数。 然后,使用getopt函数进行解析,其基本的语法格式为: getopt [选项] 参数列表 其中,选项的格式为: -a 或 --all:匹配所有选项 -b 或 --brief:简短模式,只输出短选项 -l 或 --longoptions:长选项 -o 或 --options:短选项 -n 或 --name:命令名称,一般不需要指定 -p 或 --shell:指定shell,一般不需要指定 -q 或 --quiet:安静模式,不输出错误信息 -r 或 --long-only:只支持长选项 -s 或 --silent:安静模式,不输出错误信息 -u 或 --unquoted:不转义引号 -- :结束选项列表,后面的参数都是非选项参数 例如,下面的示例代码演示了如何使用getopt函数解析命令行参数: ``` #include <stdio.h> #include <stdlib.h> #include <getopt.h> int main(int argc, char **argv) { int opt; int aflag = 0, bflag = 0; char *cvalue = NULL; while ((opt = getopt(argc, argv, "abc:")) != -1) { switch (opt) { case 'a': aflag = 1; break; case 'b': bflag = 1; break; case 'c': cvalue = optarg; break; case '?': if (optopt == 'c') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint(optopt)) fprintf(stderr, "Unknown option `-%c'.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort(); } } printf("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue); for (int index = optind; index < argc; index++) printf("Non-option argument %s\n", argv[index]); return 0; } ``` 在上面的示例代码中,选项字符串为“abc:”,表示程序支持选项a、b、c,其中选项c需要一个参数。然后,使用getopt函数解析命令行参数,将选项的值保存在变量中。最后,输出变量的值和非选项参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值