getopt_long函數

先看一段代碼:數組

#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要大一。
相關文章
相關標籤/搜索