先看一段代码:数组
#include <stdio.h> #include <stdlib.h> #include <getopt.h> void print_help(void); int main(int argc, char **argv) { const char *optstrings = "ngl:i::";//全部的短选项,单冒号是必需要有参数,双引号是选择性的有否参数,其它是无须参数 const struct option longopts[] = { {"name", 0, NULL, 'n'}, {"gf_name", 0, NULL, 'g'}, {"love", 1, NULL, 'l'}, {"istrue", 2, NULL, 'i'}, }; /* 短选项用一个字符串就能够表示它的信息了(哪一个选项是有参数阿等等信息),但对于长选项来讲,每一个选项都是好几个字符, * * 全部咱们用一个option结构体数组表示长选项的信息,每一个结构体第一个参数表示长选项的名字,第二项是个数值用来决定 * * 此长选项是否要带参数,第三个选项咱们通常都置为NULL,用来决定getopt_long函数的返回值就是第四个选项的值,因此 * * 第四个选项是此长选项相对应的短选项值,所以一旦此函数读到此长选项时,就返回与此长选项相对应的短选项,咱们就能够 * * 好判断了。 */ while(1) { int c; c = getopt_long(argc, argv, optstrings, longopts, NULL); /* 这里要清楚一个道理,就是此函数读取参数,读取到何时开始返回,好比说,咱们设置了无参数短选项-n,而后后面还有非 * * 的一串字符,好比在此程序里就是“woaini”,通过debug咱们发现,此函数读完‘-n’选项后,返回n,而后紧随着再次读取, * *发现没有选项了,尽管此时还有一串“woaini”字符串,它依然返回一个-1值 */ if (c == -1) break; switch (c) { case 'n': printf("my name is chengyang\n"); break; case 'g': printf("her name is XXX\n"); break; case 'l': printf("our love is %s\n", optarg); break; case 'i': if (optarg != NULL) printf("it is %s\n", optarg);//optarg表明参数 else printf("it is not true!\n"); break; case '?': print_help(); exit(1); break; default: print_help(); exit(1); } printf("the optind is %d\n the argc is %d\n", optind, argc);//测试了解optind } if ((argc - optind) != 1) { print_help(); exit(1); } return 0; } void print_help() { printf("the usage: [options] claim of love\n "); } 短选项参数的指定: 当使用单冒号(必需要有参数)时,咱们能够这么指定:-l [augment],中间能够有空格也能够没有空格 当使用双冒号时(能够没有参数)时,咱们必须这么指定:-i[augment],也就是说中间必须只能没有空格 长选项参数指定: 一概用如此形式:--istrue=true,中间用=号 argc和optind的区别: argc: 是所带字符串的个数,包括程序自己; optind:初始化的时候,optind就是1,能够理解为此时的1是程序自己个数,而后后面的每个选项就算一个,以及选项后的参数 (注意,若是用短选项中间没有空格指定了一个参数的话,那么此选项和参数自己只能算一个字符串,加一)算一个, 注意:最后的“woaini”,由于它不是选项因此它不能算到optind中去,因此最后,正确的话,那么argc比optind要大一。