轉載請註明出處:http://blog.csdn.net/zhangyang0402/archive/2010/06/15/5671554.aspx
getopt函數只能解析短選項,getopt_long除了接受短選項,還能解析長選項。因此,getopt_long函數在linux命令行程序中使用得最廣泛。
1. 函數原型
#include <getopt.h>
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
2. 參數
(1)argc
(2)argv
(3)optstring:短選項字符集合。若只有長選項,則置爲空字符串(“”)
(4)longopts:指向struct option數組的第一個元素,結構體option定義如下
struct option
{
const char *name; //長選項名稱
int has_arg; //是否有參數no_argument(0) required_argument(1) optional_argument(2)
int *flag; //指定長選項的返回結果:NULL 返回val;非空返回0
int val; //返回的值或裝載flag指向的變量
};
注:struct option 數組最後一個元素用0填充
(5)longindex 非空的話,指向長選項的索引
3. 返回值
對短選項,返回對應的選項字符;
對長選項,若flag爲NULL,返回val;否則返回0
4. 測試
這裏只測試長選項,至於短選項的處理則和getopt函數相同
mygetoptlong.c
執行結果:
$ ./mygetoptlong --input infile --all --output outfile --version --help file
option "input": infile
option "all":
option "output": outfile
option "version":
option "help":
Usage: ./mygetoptlong [--input infile] [--all] [--output outfile] [--version] [--help] [file]
non-opotion arguments below:
file