getopt 命令行参数解析

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

 

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

  • char *optarg——当前选项参数字串(如果有)。
  • int optind——argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。
  • int opterr——这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。
  • int optopt——当发现无效选项字符之时,getopt()函数或返回'?'字符,或返回':'字符,并且optopt包含了所发现的无效选项字符。

 

 

#include <stdio.h>
extern char *optarg;
int main(int argc,char* argv[])
{
        char c;
while ((c = getopt (argc, argv, "D:aA:c:g:hns:t:v:")) != EOF)
  {
printf("%c %s\n", c,optarg);
  }
return 2;
}

 

posted @ 2012-08-17 17:08  ahuo  阅读(202)  评论(0编辑  收藏  举报