extern char *optarg;
extern int optind, // 初始化值爲1,下一次調用getopt時,從optind存儲的位置重新開始檢查選項。
extern int opterr, // 初始化值爲1,當opterr=0時,getopt不向stderr輸出錯誤信息。
extern int optopt; // 當命令行選項字符不包括在optstring中或者選項缺少必要的參數時,
// 該選項存儲在optopt中, getopt返回'?’。
int getopt(int argc, char * const argv[], const char *optstring);
1) 單個字符,表示選項,
2) 單個字符後接一個冒號”:”,表示該選項後必須跟一個參數值。參數緊跟在選項後或者以空格隔開。該參數的指針賦給optarg。
3) 單個字符後跟兩個冒號”::”,表示該選項後必須跟一個參數。參數必須緊跟在選項後不能以空格隔開。該參數的指針賦給optarg。(這個特性是GNU的擴張)。
如果optstring中的字符串以'+'加號開頭或者環境變量POSIXLY_CORRE被設置。那麼一遇到不包含選項的命令行參數,getopt就會停止,返回-1。
#include <stdio.h>
#include <getopt.h>
char *l_opt_arg;
char* const short_options = "nbl:";
struct option long_options[] = {
{ "name", 0, NULL, 'n' },
{ "bf_name", 0, NULL, 'b' },
{ "love", 1, NULL, 'l' },
{ 0, 0, 0, 0},
};
int main(int argc, char *argv[])
{
int c;
while((c = getopt_long (argc, argv, short_options, long_options, NULL)) != -1)
{
switch (c)
{
case 'n':
printf("My name is XL./n");
break;
case 'b':
printf("His name is ST./n");
break;
case 'l':
l_opt_arg = optarg;
printf("Our love is %s!/n", l_opt_arg);
break;
}
}
return 0;
}