getopt函数的使用

来源:互联网 发布:淘宝上代买日亚电子书 编辑:程序博客网 时间:2024/05/02 20:32

http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using-Getopt

头文件 unistd.h

导出四个全局变量及其含义:

int opterr;

如果该变量被设置为非零值,则当getopt函数遇到未知的选项或者缺少必须的参数时,getopt函数将打印错误信息到标准错误中。这是默认的行为。如果你将这个变量设置为零,getopt函数将不会输出任何信息,但是函数返回'?'字符来表明错误发生。

int optopt;

当getopt函数遇到未知的选项或者缺少必须的参数时,函数将选项字符存在optopt变量中。你可以通过此方法来提供自己的错误提示。

int optind;

该变量被getopt函数设置为下一个将被处理的argv数组元素的下标。一旦getopt函数找到所有的选项参数,我们可以使用该变量来获取剩余非选项的参数的开始下标。该变量的初始值为1.

char *optarg;

该变量被getopt函数设置为指向选项的参数,即选项后面跟的参数。

函数原型

int getopt(int argc, char *const *argv, cont char *options)

getopt函数功能为从参数列表argv中获得下一个选项参数。

参数option是一个字符串,指明符合程序要求的选项字符。一个选项字符后跟着一个冒号(如”a:“)代表该选项需要一个参数。选项字符后跟着两个冒号(如”::“)代表该选项的参数可选。

getopt函数有三种方法处理位于非选项参数后面的选项。特殊参数”--“强制停止选项扫描。

1、默认处理方式为重新排列参数,将非选项参数移到参数末尾。这样允许按任意顺序给出函数参数。

2、

3、

getopt函数返回选项字符。当没有选项参数时,函数返回-1.可能还有剩余的非选项参数,我们可以通过比较optind和argc来确定。

如果选项带有参数,这getopt函数通过optarg变量传递。

简单的例子:

#include <ctype.h>

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

     

int main (int argc, char **argv)

{

int aflag = 0;

int bflag = 0;

char *cvalue = NULL;

int index;

int c;

    

printf("Before getopt: \n");

for(index = 0; index < argc; index++)

{

printf("argv[%d] = %s\n", index, argv[index]);

}


opterr = 1;

while ((c = getopt (argc, argv, "abc:")) != -1)

switch (c)

{

           case 'a':

             aflag = 1;

             break;

           case 'b':

             bflag = 1;

             break;

           case 'c':

             cvalue = optarg;

             break;

           case '?':

             if (optopt == 'c')

               fprintf (stderr, "Option -%c requires an argument.\n", optopt);

             else if (isprint (optopt))

               fprintf (stderr, "Unknown option `-%c'.\n", optopt);

             else

               fprintf (stderr,

                        "Unknown option character `\\x%x'.\n",

                        optopt);

             return 1;

           default:

             abort ();

}


printf("After getopt: \n");

for(index = 0; index < argc; index++)

{

printf("argv[%d] = %s\n", index, argv[index]);

}


     printf ("aflag = %d, bflag = %d, cvalue = %s\n",

               aflag, bflag, cvalue);

     

 for (index = optind; index < argc; index++)

         printf ("Non-option argument %s\n", argv[index]);

 

 return 0;

}

原创粉丝点击