C语言中getopt()和getopt_long()函数的用法

一、命令行参数的使用

C程序的主函数有两个参数,其中,第一个参数是整型,可以获得包括程序名字的参数个数,第二个参数是字符数组指针或字符指针的指针,可以按顺序获得命令行上各个字符串参数。其原形是:

int main(int argc, char *argv[]);
或者是:
int main(int argc, char **argv);
比如在命令行输入:
./test hello world  

则argc=3,argv[0]="./test",argv[1]="hello",argv[3]="world"


在主函数中可以直接对命令行参数进行处理,但当命令行参数个数较多时,如果按照顺序一个一个定义参数含义很容易造成混乱,而且如果程序只按顺序处理参数的话,一些“可选参数”的功能将很难实现。在Linux中,可以使用getopt()、getopt_long()、getopt_long_only()等函数来对复杂的命令行参数进行处理。

二、getopt()函数

原型:

#include <unistd.h>
 
extern char *optarg;
extern int optind, opterr, optopt;
int getopt(int argc, char * const argv[], const char *optstring);
描述:

1、getopt函数的前两个参数,就是main函数的argc和argv,这两者直接传入即可,要考虑的就只剩下第三个参数。

2、optstring的格式举例说明比较方便,例如:

    char *optstring = "abcd:";
上面这个optstring在传入之后,getopt函数将依次检查命令行是否指定了 -a, -b, -c及 -d(这需要多次调用getopt函数,直到其返回-1),当检查到上面某一个参数被指定时,函数会返回被指定的参数名称(即该字母)

最后一个参数d后面带有冒号,: 表示参数d是可以指定值的,如 -d 100 或 -d user。字符后带两个':'表示该选项带可选参数(参数可有可无)。

3、optind表示的是下一个将被处理到的参数在argv中的下标值。

4、如果指定opterr = 0的话,在getopt、getopt_long、getopt_long_only遇到错误将不会输出错误信息到标准输出流。
例一:

#include <unistd.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
    
    int ch;
    printf("\n\n");
    printf("optind:%d,opterr:%d\n",optind,opterr);
    printf("--------------------------\n");
       while ((ch = getopt(argc, argv, "ab:c:de::")) != -1)
       {
        printf("optind: %d\n", optind);
           switch (ch) 
        {
               case 'a':
                       printf("HAVE option: -a\n\n");   
                       break;
               case 'b':
                       printf("HAVE option: -b\n"); 
                       printf("The argument of -b is %s\n\n", optarg);
                       break;
               case 'c':
                       printf("HAVE option: -c\n");
                       printf("The argument of -c is %s\n\n", optarg);
                       break;
               case 'd':
                   printf("HAVE option: -d\n");
                     break;
              case 'e':
                    printf("HAVE option: -e\n");
                    printf("The argument of -e is %s\n\n", optarg);
                  break;
              case '?':
                       printf("Unknown option: %c\n",(char)optopt);
                       break;
               }
       }


}

例二:

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

int main(int argc, char *argv[])
{
    int opt;
    char *optstring = "a:b:c:d";

    while ((opt = getopt(argc, argv, optstring)) != -1)
    {
        printf("opt = %c\n", opt);
        printf("optarg = %s\n", optarg);
        printf("optind = %d\n", optind);
        printf("argv[optind - 1] = %s\n\n",  argv[optind - 1]);
    }

    return 0;
}
输出结果;
cashey@ubuntu:~/Desktop/getopt$ ./test_getopt -a 100 -b 200 -c admin -d  
opt = a  
optarg = 100  
optind = 3  
argv[optind - 1] = 100  
  
opt = b  
optarg = 200  
optind = 5  
argv[optind - 1] = 200  
  
opt = c  
optarg = admin  
optind = 7  
argv[optind - 1] = admin  
  
opt = d  
optarg = (null)  
optind = 8  
argv[optind - 1] = -d  

三、getopt_long()函数

getopt_long函数包含了getopt函数的功能,并且还可以指定“长参数”(或者说长选项),与getopt函数对比,getopt_long比其多了两个参数。

原型:

#define _GNU_SOURCE

#include <getopt.h>

extern char *optarg;

extern int optind, opterr, optopt;

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、注意相比getopt,使用getopt_long需要加头文件<getopt.h>;
2、getopt_long除了会接受长选项,其他概念和getopt是一样的;
3、如果使用getopt_long想只接受短选项,设置longopts为NULL即可;如果只想接受长选项,相应地设置optstring为NULL即可;
4、长选项名是可以使用缩写方式,比如:选项有--file\--create,那么输入--c/--cr/--cre等均会被正确识别为create选项;
5、对于带参数的长选项格式是:--arg=param或--arg param;
6、longopts是指向struct option数组的第一个元素的指针,struct option定义在<getopt.h>中;
7、longindex如果非NULL,则是返回识别到struct option数组中元素的位置指针;

8、当所给的参数存在问题时,函数的返回值是'?'

struct option的说明:

           struct option {
               const char *name;
               int         has_arg;
               int        *flag;
               int         val;
           };

name: 长选项名
has_arg: 是否带参数或可选参数,这个值在getopt.h中有宏定义,如下:
     # define no_argument        0                表明这个长参数不带参数(即不带数值,如:--name)
     # define required_argument  1           表明这个长参数必须带参数(即必须带数值,如:--name Bob)
     # define optional_argument  2            表明这个长参数后面带的参数是可选的,(即--name和--name Bob均可)
flag: 确定函数返回值的情况,如果flag==NULL,则识别选项后返回val(常用的如:设置val为长命令的短命令字符);否则,识别后getopt_long返回0,flag指向一个设置到val的变量;
val: 设置为返回值,或者是flag指向的变量;这里要注意不要写-1到val,否则其作用是getopt_long返回-1,然后停止解析选项;

[注意] longopts的最后一个元素必须是全0填充,否则会报段错误

例子:

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

int
main(int argc, char **argv)
{
   int opt;
   int digit_optind = 0;
   int option_index = 0;
   char *optstring = "a:b:c:d";
   static struct option long_options[] = {
       {"reqarg", required_argument, NULL, 'r'},
       {"noarg",  no_argument,       NULL, 'n'},
       {"optarg", optional_argument, NULL, 'o'},
       {0, 0, 0, 0}
   };

   while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1)
   {
        printf("opt = %c\n", opt);
        printf("optarg = %s\n", optarg);
        printf("optind = %d\n", optind);
        printf("argv[optind - 1] = %s\n",  argv[optind - 1]);
        printf("option_index = %d\n", option_index);
   }

   return 0;
}

输出结果:

[ye@localhost c]$ ./test_getopt -a 100 --reqarg 100 --noarg
opt = a
optarg = 100
optind = 3
argv[optind - 1] = 100
option_index = 0
opt = r
optarg = 100
optind = 5
argv[optind - 1] = 100
option_index = 0
opt = n
optarg = (null)
optind = 6
argv[optind - 1] = --noarg
option_index = 1

最后说明一下,getopt_long_only与getopt_long的区别在于:getopt_long仅仅只能将"--"开始的选项视为长选项,但getopt_long_only将"-"开头选项也会视为长选项,当长选项列表均不满足时,且短选项满足时,"-"才会解析为短选项;


参考文献:

[1]. http://blog.csdn.net/xiaocainiaoshangxiao/article/details/13996459

[2]. http://www.cnblogs.com/water-moon/p/5984108.html

[3]. http://blog.csdn.net/cashey1991/article/details/7942809



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值