Chinaunix首页 | 论坛 | 博客
  • 博客访问: 189287
  • 博文数量: 71
  • 博客积分: 2990
  • 博客等级: 少校
  • 技术积分: 705
  • 用 户 组: 普通用户
  • 注册时间: 2005-03-29 14:04
文章分类

全部博文(71)

文章存档

2011年(1)

2009年(1)

2007年(6)

2006年(42)

2005年(21)

我的朋友

分类: C/C++

2005-12-07 16:19:13

象xxx -h host --password 123456这种命令,编程时,如何方便的取得命令行参数?有一个很好的方法,就是调用getopt()。

函数定义:
#include
int getopt(int argc, char * const argv[],
        const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;


#define _GNU_SOURCE
#include

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);


getopt()函数是用来解析命令行参数的。这里,主要解释getopt_long()。

    getopt_long()的头两参数,argc和argv分别是传递给main()的参数的个数和参数数组(和main()的argc和argv是一个概念)。

    getopt_long()中,optstring是一个字符串,表示可以接受的参数。例如,"a:b:cd",表示可以接受的参数是a,b,c,d,其中,a和b参数后面

跟有更多的参数值。(例如:-a host --b name)

    getopt_long()中,参数longopts,其实是一个结构的实例:
struct option {
  const char *name;
   
//name表示的是长参数名
  int has_arg;
    //has_arg有3个值,no_argument(或者是0),表示该参数后面不跟参数值
    //   required_argument(或者是1),表示该参数后面一定要跟个参数值
    //   optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值
  int *flag;
    //用来决定,getopt_long()的返回值到底是什么。如果flag是null,则函数会返回与该项option匹配的val值
  int val;
    //和flag联合决定返回值
}

给个例子:

struct option long_options[] = {
  {"a123",       required_argument,      0, 'a'},
  {"c123",       no_argument,            0, 'c'},
}

现在,如果命令行的参数是-a 123,那么调用getopt_long()将返回字符'a',并且将字符串123由optarg返回(注意注意!字符串123由optarg带

回!optarg不需要定义,在getopt.h中已经有定义)
那么,如果命令行参数是-c,那么调用getopt_long()将返回字符'c',而此时,optarg是null。

最后,当getopt_long()将命令行所有参数全部解析完成后,返回-1。

看来,我说的有点混乱,那么,看个例子,我相信,代码最能说明问题:

#include
#include
#include
#include

int main( int argc, char **argv )
{

 struct option long_options[] = {
   {"a123",       required_argument,      0, 'a'},
   {"c123",       no_argument,            0, 'c'},
 }
 int opt;
 
 printf("starting... ");
 
 while((opt = getopt_long(argc, argv, "a:c", long_options, NULL)) != -1)
 {
  switch (opt)
  {
  case 'a':
    printf("It's a! ");
    printf("string of a:%s ",optarg);
  break;
    
  case 'c':
    printf("It's c! ");
  break;
    
  default:
    printf("You should look for help! ");
    exit(1);
  break;            
  }
 }
 printf("end... ");
 return 0;
}

编译后,假设生成a.out,可以试验一下。
./a.out -a hello -c
输出:
starting...
It's a!
string of a:hello
It's c!
end...

这个程序不难,一下子就能看明白。

阅读(789) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~