Linux-getopt

Linux下命令行解析函数getopt.

原型:
int getopt(int argc,char *argv[],const char *optstring);
参数:
agrc:命令行参数个数
argv[]:命令行参数数组
optstring:命令行参数选项
  
getopt调用一次将返回第一个选项,再次调用将返回下一个选项并设置相应的全局变量,不再识别返回-1:
optarg--指向当前选项参数的指针
optind--成功调用一次指向下一个argv指针的索引
optopt--最后一个未知选项,默认为0,出错为出错时的选项
opterr--全局变量默认为1,控制错误信息的输出,改为0则不输出

optstring注意:a:b:c::e
 a b c d e表示命令行的 -a -b -c -d -e选项; :和::表示选项后有参数,e后边并没有参数。
 :参数在选项后有一个空格或者挨着; ::可省略参数或者参数紧挨着选项 。

#include<stdio.h>
#include<unistd.h>
#include<string.h>

//int opterr=0;//控制错误信息0表示关闭
int main(int argc,char *argv[]){
	int ch;
	printf("命令行参数个数:argc=%d\n",argc);
	
	for(int i=0;i<argc;i++){
		printf("命令行参数:argv[%d]=%s\n",i,argv[i]);
	}
	
	ch=getopt(argc,argv,"a:b::c:d");
	while(ch!=-1){
		switch(ch){
			case 'a':printf("选择a选项:ch=%c,optind=%d,optarg=%s,opterr=%d,optopt=%d\n",ch,optind,optarg,opterr,optopt);break;
			case 'b':printf("选择b选项:ch=%c,optind=%d,optarg=%s,opterr=%d,optopt=%d\n",ch,optind,optarg,opterr,optopt);break;
			case 'c':printf("选择c选项:ch=%c,optind=%d,optarg=%s,opterr=%d,optopt=%d\n",ch,optind,optarg,opterr,optopt);break;
			case 'd':printf("选择d选项:ch=%c,optind=%d,optarg=%s,opterr=%d,optopt=%d\n",ch,optind,optarg,opterr,optopt);break;
			case '?':printf("非法选项或者缺少参数:ch=%c,optind=%d,optarg=%s,opterr=%d,optopt=%d\n",ch,optind,optarg,opterr,optopt);break;
			default:printf("非法选项或者缺少参数返回?,等同于上边的?选项");break;
		}
		ch=getopt(argc,argv,"a:b::c:d");
	}
	return 0;
}

 

关闭错误信息设置:int opterr=0

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值