Chinaunix首页 | 论坛 | 博客
  • 博客访问: 607027
  • 博文数量: 353
  • 博客积分: 1104
  • 博客等级: 少尉
  • 技术积分: 1457
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-23 23:02
个人简介

1、刚工作时做Linux 流控;后来做安全操作系统;再后来做操作系统加固;现在做TCP 加速。唉!没离开过类Unix!!!但是水平有限。。

文章存档

2015年(80)

2013年(4)

2012年(90)

2011年(177)

2010年(1)

2009年(1)

分类:

2012-06-09 19:42:32

一、getopt用法
#include
extern char *optarg;
extern int optind, opterr, optopt;

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

Returns: the next option character, or -1 when all options have been processed
 
The "argc" and "argv" arguments are the same ones passed to the main function of the program.
The "options" argument is a string containing the option characters supported by the command.
If an option character is followed by a colon, then the option takes an argument.
Otherwise, the option exists by itself. For example, if the usage statement for a command was
    command [-i] [-u username] [-z] filename

we would pass "iu:z" as the "options" argument string to getopt.

二、getopt_long用法
#include
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);

longopts is a pointer to the first element of an array of struct option declared in
struct option {
     const char *name;
     int has_arg;
     int *flag;
     int val;
};


The meanings of the different fields are:

name   is the name of the long option.

has_arg
        is: no_argument (or 0) if the option does not take an argument,
        required_argument (or 1) if the option requires an argument, or 
        optional_argument  (or 2) if the option takes an optional argument.

flag   specifies  how results are returned for a long option.  If flag is NULL, then
       getopt_long() returns val.  (For example, the calling program may set val
       to the equivalent short option character.)  Otherwise, getopt_long() returns 0,
       and flag points to a variable which is set to  val  if  the  option  is
       found, but left unchanged if the option is not found.

val    is the value to return, or to load into the variable pointed to by flag.
       The last element of the array has to be filled with zeroes.

If longindex is not NULL, it points to a variable which is set to the index of the long option relative to longopts.

三、外部变量

optarg  (感觉最有用,指向 option 的 argument 的指针)
 If an option takes an argument, getopt sets optarg to point to the option's argument string when an option is processed.
 
optind
 The index in the argv array of the next string to be processed. It starts out at 1 and is incremented for each argument processed by getopt.
每次 getopt_long() 会处理选项以及它的参数 (至多一个,不处理可选参数)
而 optind 指向下次要处理的字符串在argv中的索引值

static const struct option long_options[] = {
    { "device",  1, 0, 'D' },
    { "loop",    0, 0, 'l' },
    { "config",  2, 0, 'c' },
    { "speed",   1, 0, 's' },
    { NULL, 0, 0, 0 },
};

./test --loop papa nana --device lala wawa haha --config tata yaya --speed rara eaea
getopt_long 每次返回时,打印optarg、optind 的值如下

         optarg     optind
第一次   null       2  "下次要处理papa"
第二次   lala       6  "下次要处理wawa"
第三次   null       9  "下次要处理tata"   不处理可选参数
第四次   rara       13 "下次要处理eaea"

剩下两个是用来错误调试用的
opterr
 If an option error is encountered, getopt will print an error message by default. To disable this behavior, applications can set opterr to 0.
 
optopt
 If an error is encountered during options processing, getopt will set optopt to point to the option string that caused the error.

四、小技巧

The normal use of getopt is in a loop that terminates when getopt returns -1.
During each iteration of the loop, getopt will return the next option processed.
It is up to the application to sort out any conflict in options, however;
getopt simply parses the options and enforces a standard format.

When it encounters an invalid option, getopt returns a question mark instead of the character.
If an option's argument is missing, getopt will also return a question mark, but if the first
character in the options string is a colon, getopt returns a colon instead.

The special pattern -- will cause getopt to stop processing options and return -1.
This allows users to provide command arguments that start with a minus sign but aren't options.
For example, if you have a file named -bar, you can't remove it by typing
    rm -bar
because rm will try to interpret -bar as options. The way to remove the file is to type
    rm -- -bar

五、示例代码


int main(int argc, char **argv)
{
    int c;
    while( (c=getopt(argc,argv,"a:b")) != -1 ){
        switch(c){
            case 'a':
                printf("-a %s\n",optarg);
                break;
            case 'b':
                printf("-b\n");
                break;
            default:
                break;
        }
    }
    return 0;
}

---------------------------------------------------------------

    static struct option long_options[] = {
        {"dump",           0,    NULL,    'd'},
        {"loop",           1,    NULL,    'l'},
        {NULL,    0,    NULL,    0}
    };
       
    int main(int argc, char *argv[])
    {
        int c;
        int fd = -1;
        struct cmd_arg cmd;
        cmd.phy_addr = 2;    //default value
       
        while(1) {
            c = getopt_long(argc,argv, "a:t", long_options,NULL);
            if(c == -1)
                break;
            switch(c){
                case 'a':
                    cmd.phy_addr = atoi(optarg);
                    break;
                case 'd':
                    ioctl(fd, DUMP_5461_PHY , &cmd);
                    break;
                case 'l':
                    cmd.data = atoi(optarg);
                    ioctl(fd, LOOP_5461_PHY, &cmd);
                    break;
                case 't':
                    ioctl(fd, TEST, &cmd);
                    break;      
                default:
                    break;
            }
        }
       
        return 0;
    }
阅读(441) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~