#include <unistd.h> extern char *optarg; extern int optind, extern int opterr, extern int optopt; int getopt(int argc, char * const argv[], const char *optstring);
定義了四個全局變量:optarg是選項的參數指針,optind記錄目前查找的位置,當opterr = 0時,getopt不向stderr輸出錯誤信息。當命令選項字符不包括在optstring中或者缺少必要的參數時,該選項存儲在optopt中,getopt返回 '?'
getopt調用一次,返回一次選項,當檢查不到參數時,返回-1,同時,optind儲存第一個不包含選項的命令行參數。 optstring參數可以有以下元素。 1.單個字符:表示選項 2.單個字符後接一個冒號:表示該選項必須跟一個參數,參數緊跟在選項後,或以一個空格隔開,將參數的指針賦給optarg。 3.單個字符後跟兩個冒號:表示該選項必須跟一個參數,且不能用空格隔開。 例子:#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int opt = 0;
while ((opt = getopt(argc, argv, "if:?lr::")) != -1)
{
switch(opt)
{
case 'i':
case 'l':
printf("option: %c\n", opt);
break;
case 'f':
printf("filename: %s\n", optarg);
break;
case 'r':
printf("arg:%s\n", optarg);
break;
case ':':
printf("option needs a value\n");
break;
case '?':
printf("unknow option: %c\n", optopt);
break;
}
}
for (; optind < argc; optind++)
{
printf("argument: %s\n", argv[optind]);
ar
return 0;
}
二、getoptlong
getoptlong就是添加了對長選項支持的getopt,getoptlong比getopt多兩個參數,struct option *longopts和int *longindex,後者用到的少,一般置為NULL。直接來看struct option 結構
struct option
{
char *name;
int has_arg;
int *flag;
int val;
};
name表示的是長參數名,has_arg有三個值,當has_arg = no_argument(即0)時,表示該參數後面不跟參數值,當has_arg = required_argument(即1)時,表示參數後面一定跟參數值,當has_arg = optional_argument(即2)時,表示該參數後面可跟參數值,也可不跟。flag 當這個指針為空的時候,函數直接將val的數值從getopt_long的返回值返回出去,當它非空時,val的值會被賦到flag指向的整型數中,而函數返回值為0 。 val 用於指定函數找到該選項時的返回值,或者當flag非空時指定flag指向的數據的值。
定義option試例:
struct option longopts[] =
{
{"initialize", 0, NULL, 'i'},
{"filename", 1, NULL, 'f'},
{"list", 0, NULL, 'l'},
{"restart", 0, NULL, 'r'}
};
例子:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define _GNU_SOURCE
#include <getopt.h>
int main(int argc, char **argv)
{
int opt;
struct option longopts[] =
{
{"initialize", 0, NULL, 'i'},
{"filename", 1, NULL, 'f'},
{"list", 0, NULL, 'l'},
{"restart", 0, NULL, 'r'}
};
while ((opt = getopt_long(argc, argv, ":if:lr", longopts, NULL)) != -1)
{
switch(opt)
{
case 'i':
case 'l':
case 'r':
printf("option: %c\n", opt);
break;
case 'f':
printf("filename: %s\n", optarg);
break;
case ':':
printf("option needs a value\n");
break;
case '?':
printf("unknow option: %c\n", optopt);
break;
}
}
for (; optind < argc; optind++)
{
printf("argument: %s\n", argv[optind]);
}
return 0;
}