攀升·Uranus


Something Different,Something New
数据加载中……

glibc: getopt()

这个东西比较有用,
以后可以用它来直接读了。

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

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

给定了命令参数的数量 (argc)、指向这些参数的数组 (argv) 和选项字符串 (optstring) 后,getopt() 将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有识别到的选项,将返回 -1,此任务就完成了。

getopt() 所设置的全局变量包括:

  • optarg——指向当前选项参数(如果有)的指针。
  • optind——再次调用 getopt() 时的下一个 argv 指针的索引。
  • optopt——最后一个已知选项。

 ./getopt -a -d -b foo
optind: 2
HAVE option: -a
./getopt: invalid option -- d
optind: 3
Unknown option: d
optind: 5
HAVE option: -b
The argument of -b is foo

posted on 2009-07-17 14:29 攀升 阅读(1436) 评论(1)  编辑 收藏 引用 所属分类: Linux

评论

# re: glibc: getopt()[未登录]  回复  更多评论   

看着 头晕~
你呢?
2009-07-28 12:38 | 胖胖

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理