getopt

来源:互联网 发布:电脑音频加速软件 编辑:程序博客网 时间:2024/05/26 02:20

getopt()是用来分析命令行参数的。

argc和argv分别代表参数个数和参数。

optstring为选项字符串,告诉getopt()要处理哪个选项以及哪个选项需要参数,如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,optarg 即会指向所跟参数后面的参数。如果遇到了不符合optstring指定的其他选项,getopt()将显示“?”字符。

#include <stdio.h>
#include<unistd.h>
int main(int argc,const char **argv)
  {
  int cc;

  while(-1 != (cc = getopt(argc,argv,"a:b:cd:e")))
  {
      switch(cc)
      {
      case 'a': 

                     printf("option a:%s\n",optarg); 

                     break;
      case 'b': 

                     printf("option b :b\n"); 

                     break;
      default: printf("other option :%c\n",cc);
     }
     printf("optopt +%c\n",optopt);
     }
  return 0;
  }