linux程序 option,long-option.c/解析命令行参数
#include //繼續ing。。。
#include "version-etc.h"
//初始化結構體
static struct option const long_options[] =
{
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0}
};
這里貼一下從網上找到的中文解釋(出自http://blog.chinaunix.net/u/12592/showart_429841.html):
struct options的定義如下:
struct option{
const char *name;
int has_arg;
int *flag;
int val;
};
對結構中的各元素解釋如下:
const char *name
這是選項名,前面沒有短橫線。譬如"help"、"verbose"之類。
int has_arg
描述了選項是否有選項參數。如果有,是哪種類型的參數,此時,它的值一定是下表中的一個。
符號常量???? 數值???? 含義
no_argument???? 0???? 選項沒有參數
required_argument???? 1???? 選項需要參數
optional_argument???? 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中出現的這個選項的參數相同。
/* Process long options --help and --version, but only if argc == 2.
Be careful not to gobble up `--'.? */
函數具體實現的地方:
void
parse_long_options (int argc,
char **argv,
const char *command_name,
const char *package,
const char *version,
void (*usage_func) (int),
/* const char *author1, ...*/ ...)
{
int c;//定義局部變量
int saved_opterr;
saved_opterr = opterr; 初始化saved_opterr
/* Don't print an error message for unrecognized options.? */
opterr = 0;
if (argc == 2 如果傳入的整型形參argc等于2并且
&& (c = getopt_long (argc, argv, "+", long_options(這里的這個結構體就是文件開頭初始化的那個結構體了), NULL)) != -1)c的值是通過getopt_long得到的值
{
switch (c)根據getopt_long獲得的c的值,選擇應該進入哪個代碼段執行程序
{
case 'h':如果是字符h,則調用注冊的usage_func函數,傳給這個函數的形參是EXIT_SUCCESS
(*usage_func) (EXIT_SUCCESS);
case 'v':如果是字符v,則打印下面列示的作者和幫助等信息,并返回0
{
va_list authors;
va_start (authors, usage_func);
version_etc_va (stdout, command_name, package, version, authors);
exit (0);
}
default:如果是其他值,則跳出switch語句塊
/* Don't process any other long-named options.? */
break;
}
}
/* Restore previous value.? */
opterr = saved_opterr;opterr這時候得到的值是程序開始執行時的值
/* Reset this to zero so that getopt internals get initialized from
the probably-new parameters when/if getopt is called later.? */
optind = 0;重新設置optind的值
}
這個解析函數早在第一個程序sync.c里面就見到了,當時沒有太關注,今天粗略地看了看,日后再詳細研究,關于命令行選項的問題,需要花時間專門看看。
總結
以上是生活随笔為你收集整理的linux程序 option,long-option.c/解析命令行参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分享按钮 html代码,超简洁微博分享按
- 下一篇: linux shell 获取参数 $,L