歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用Linux下的getopt類函數解析參數列表

用Linux下的getopt類函數解析參數列表

日期:2017/3/1 10:16:17   编辑:Linux編程

在GNU下有getopt類的函數可以輕松解析參數列表,省去很多煩惱,定義如下:

#include <unistd.h>
int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
#define _GNU_SOURCE
#include <getopt.h>
int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
int getopt_long_only(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);

需要對長參數(非一個字符)進行解析的時候要用到getopt_long(),這個函數有個參數struct option的定義為:

struct option {
const char *name;
int has_arg;
int *flag;
int val;
};

這個結構體定義屬於頭文件<getopt.h>

對與這個結構體的詳細解釋為:

struct option {
const char *name; // 名字
int has_arg; // 0 沒有參數, 1 必須有參數, 2 可選參數
int *flag; // 如果這個指針為NULL,那麼getopt_long()返回該結構val字段中的數值。如果該指針不為NULL,getopt_long()會使得它所指向的變量中填入val字段中的數值,並且getopt_long()返回0。如果flag不是NULL,但未發現長選項,那麼它所指向的變量的數值不變。
int val; // 發現了長選項時的返回值,或者flag不是 NULL時載入*flag中的值。典型情況下,若flag不是NULL,那麼val是個真/假值,譬如1 或0;另一方面,如果flag是NULL,那麼val通常是字符常量,若長選項與短選項一致,那麼該字符常量應該與optstring中出現的這個選項的參數相同。
};// 此數據類型的數據最後一個元素必須是0

下面是一個例子:

#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>
// 定義長參數
static struct option long_options[] = {
{"addsg", 0, 0, '1'},
{"rmsg", 0, 0, '2'},
{"addnode", 0, 0, '3'},
{"rmnode", 0, 0, '4'},
{"from", 1, 0, 'f'},
{"to", 1, 0, 't'},
{"help", 0, 0, 'h'},
{"version", 0, 0, 'v'},
{"reflush", 0, 0, 'r'},
{0, 0, 0, 0}
};
// 定義短參數
char* const short_options = "1234f:t:hvr";
// 循環解析參數,並進行處理
int get_options (int argc, char **argv)
{
int c;
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
c = getopt_long (argc, argv, short_options, long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case '1':
printf ("start addnode function\n");
break;
case '2':
printf ("start removesg function\n");
break;
case '3':
printf ("start addnode function\n");
break;
case '4':
printf ("start removenode function\n");
break;
case 'h':
printf ("show help\n");
break;
case 'v':
printf("show version\n");
break;
case 'f':
printf ("src ip is : '%s'\n", optarg);
break;
case 't':
printf ("dst ip is : '%s'\n", optarg);
break;
case 'r':
printf ("should reflush data\n");
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc) {
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
return 0;
}
int main (int argc, char **argv)
{
printf("main function\n");
get_options(argc, argv); // 將程序的參數直接傳給函數,用以解析
return 0;
}

Copyright © Linux教程網 All Rights Reserved