Linux应用之参数解析函数---getopt()与getopt_long()

一、Linux应用程序参数介绍

在Linux应用程序运行时往往会带入参数,例如./xxx_tool -f filename -d portnum,这里-f 和-d后面都带有参数,再比如最基础的命令ls,- -help之后告诉你一大堆可使用的参数(如下图),例如短参数-a, 长参数- -all。
这里提及一个概念:Linux命令行参数可以分为两类,一类是短选项,参数前加一个杠"-“,如-a -A都是,另外一类是长选项,长选项在参数前连续加两个杠”- -",如- -all,- -author都表示长选项。

root@100ask:/home/book/Desktop/test# ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all                  do not ignore entries starting with .
  -A, --almost-all           do not list implied . and ..
      --author               with -l, print the author of each file
  -b, --escape               print C-style escapes for nongraphic characters
      --block-size=SIZE      scale sizes by SIZE before printing them; e.g.,
                               '--block-size=M' prints sizes in units of
                               1,048,576 bytes; see SIZE format below

二、getopt()与getopt_long()函数原型

先说下这两个函数的区别,getopt()可以获取短选项参数信息,getopt_long()则是短选项和长选项参数信息都可以获取到。

另外大家知道通常Linux中应用main函数的原型为int main(int argc, char *argv[]),其中argc表示参数的个数,argv[]就是程序运行时带进来的参数了。

int main(int argc, char *argv[])

getopt()和getopt_long()函数的原型如下:

#include <getopt.h>
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);  

前2个参数的意义如main函数,这里说明一下第3个参数optstring:表示短选项字符串。

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

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

这里重点介绍第4个参数longopts:表示长选项结构体。结构如下:

struct option 
{  
     const char *name;  
     int         has_arg;  
     int        *flag;  
     int         val;  
};  
eg:
static struct option longOpts[] = {
  { "diag-port", required_argument, NULL, 'd' },
  { "save-dir", required_argument, NULL, 's' },
  { "max-log-size", required_argument, NULL, 'm' },
  { "max-log-filenum", required_argument, NULL, 'n' },
  { "ftpipaddr", required_argument, &lopt, 1 },
  { "username", required_argument, &lopt, 2 },
  { "passwd", required_argument, &lopt, 3 },
  { "help", no_argument, NULL, 'h' },
  { 0, 0, 0, 0 }
};

结构体option成员has_arg表示选项后面是否带参数,具体如下:

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

结构体option成员flag:空或者非空。

    a:如果参数为空NULL,那么当选中某个长选项的时候,getopt_long()函数将返回第四个结构体成员val的值。
    	例如: --help,getopt_long()的返回值为h.             
    b:如果参数不为空,那么当选中某个长选项的时候,getopt_long()将返回0,并且将结构体成员flag指针参数指向val值。
        例如: --ftpipaddr192.168.1.100 那么getopt_long返回值为0,并且lopt值为1(如上图longOpts结构体数组的定义)。

结构体option成员val:表示指定函数找到该选项时的返回值,当flag非空时指定flag指向数据值val。

函数返回值:

     (1)如果短选项找到,那么将返回短选项对应的字符。

     (2)如果长选项找到,如果flag为NULL,返回val。如果flag不为空,返回0

     (3)如果遇到一个选项没有在短字符、长字符里面。或者在长字符里面存在二义性的,返回“?”

     (4)如果解析完所有字符没有找到(一般是输入命令参数格式错误,eg: 连斜杠都没有加的选项),返回“-1”

     (5)如果选项需要参数,忘了添加参数。返回值取决于optstring,如果其第一个字符是“:”,则返回“:”,否则返回“?”。

说了这么多估计大家也记不住,看个C语言参考代码大家就可以理解了,实际我们理解基本用法就可以,高级用法如果需要用,到时候再查也是可以的。

三、实例与测试

参考代码如下:

#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>

 
void showUsage() {
  printf("options\r\n");
  printf("<-d [diag port]> <-s [log save dir]> <-m [single logfile size(MB)]> <-n [max_log_filenum]>\r\n");
  printf("<--ftpipaddr [address]> <--username [username]> <--passwd [password]>\r\n");
}

int lopt;
static struct option longOpts[] = {
  { "diag-port", required_argument, NULL, 'd' },
  { "save-dir", required_argument, NULL, 's' },
  { "max-log-size", required_argument, NULL, 'm' },
  { "max-log-filenum", required_argument, NULL, 'n' },
  { "ftpipaddr", required_argument, &lopt, 1 },
  { "username", required_argument, &lopt, 2 },
  { "passwd", required_argument, &lopt, 3 },
  { "help", no_argument, NULL, 'h' },
  { 0, 0, 0, 0 }
};
	
int main(int argc, char* argv[]) {
  int optIndex = 0;
  int opt;

  while((opt = getopt_long(argc, argv, "d:s:m:n:h", longOpts, &optIndex))!= -1) 
  {
	printf("opt is %d\r\n", opt);
    switch(opt) 
	{
		case 0:
		{
		  switch(lopt) {
			  case 1: 
			  {
				printf("ftpipaddr: %s\r\n",optarg);
				break;
			  }
			  case 2:
			  {
				printf("username: %s\r\n",optarg);
				break;
			  }
			  case 3:
			  {
				printf("passwd: %s\r\n",optarg);
				break;
			  }
			}
			break;
		}
		case 'd':
		  printf("d: %s\r\n",optarg);
		  break;
		case 's':
		  printf("s: %s\r\n",optarg);
		  break;
		case 'm':
		  printf("m: %s\r\n",optarg);
		  break;
		case 'n':
		  printf("n: %s\r\n",optarg);
		  break;
		case 'h':
		  showUsage();
		  break;
		default:
		  showUsage();
		  break;
    }
  }
  return 0;
}


测试结果:

root@ubuntu:~/temp$ ./getopt_long -d /dev/ttyUSB0 -s ./ -m 40 -n 8 --ftpipaddr 192.168.1.123 --username maiochaodahai0902 --passwd 12345678
opt is 100
d: /dev/ttyUSB0
opt is 115
s: ./
opt is 109
m: 40
opt is 110
n: 8
opt is 0
ftpipaddr: 192.168.1.123
opt is 0
username: maiochaodahai0902
opt is 0
passwd: 12345678

几点注意:

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

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

与该函数相关的几个全局变量:

    (1)optarg:表示当前选项对应的参数值。

    (2)optind:表示的是下一个将被处理到的参数在argv中的下标值。

    (3)opterr:如果opterr = 0,在getopt、getopt_long遇到错误将不会输出错误信息到标准输出流。opterr在非0时,向终端输出错误。

    (4)optopt:表示没有被未标识的选项。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值