getopt_long

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
static int verbose_flag;

/*
 *
 * getopt_long 这个获取命令行的参数还是很有用的
 * 我们可以在程序名的后面加上-或者--来做相应的参数配置
 */
int main(int argc, char ** argv)
{
    int c;
    while(1){
        static struct option long_options[]={
            {"verbose",no_argument,&verbose_flag,1},//对相应的状态位进行置位
            {"brief",no_argument,&verbose_flag,0},


            {"add",no_argument,0,'a'},
            {"append",no_argument,0,'b'},
            {"delete",required_argument,0,'d'},
            {"create",required_argument,0,'c'},
            {"file",required_argument ,0,'f'},
            {0,0,0,0}
        };
        int option_index=0;
         c = getopt_long (argc, argv, "abc:d:f:",
                   long_options, &option_index);//获取状态位
        if(c==-1)//倘若为空的话就退出
            break;
//printf("%d,%d,%d\n",c,*long_options[option_index].flag,option_index);
        switch(c){
            case 0://
                if(*long_options[option_index].flag!=0)//./a.out --brief flag置为0
                    break;
                printf("options %s",long_options[option_index].name);//打印options brief
                if(optarg)
                    printf(" with arg %s",optarg);
                printf("\n");
                break;
            case 'a'://倘若./a.out -a -后面只要有任何一个参数为a就会打印下面的语句
                puts("option -a\n");
                break;
            case 'c'://如上只是—a 变成-c
                printf("option -c with value '%s'\n",optarg);
                break;
            default://虽然都没有定义的参数就中断程序
              abort ();

        }
    }
    if (verbose_flag)//./a.out verbose 会执行下面的输出
        puts ("verbose flag is set");
  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
        printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

    return 0;
}




你可能感兴趣的:(getopt_long)