getopt概述
getopt只支持短參數,例如-a
-b
int getopt(int argc, char * const argv[], const char *optstring);
需要解釋的幾個概念
(1)參數optstring
,表示程序支持的參數,例如char *optstr = "a::b:c:di:p:";
就表示當前程序支持的參數有:-a
-b
-c
-d
-i
-p
冒號的意思
單個字符a 表示選項a沒有參數 格式:-a即可,不加參數
單字符加冒號b: 表示選項b有且必須加參數 格式:-b 100或-b100,但-b=100錯
單字符加2冒號c:: 表示選項c可以有,也可以無 格式:-c200,其它格式錯誤
(2)變量optarg,這是庫中定義好的一個變量,保存了參數后面的值,比如有參數-b 100
,當getopt函數返回b
的時候,此時optarg存儲的就是100
(3)getopt函數的返回值:char類型的參數所對應的int值,比如-b 100
,getopt函數返回的就是字符b
對應的int值
(4)另外幾個與optarg類似的幾個變量
optind —— 再次調用 getopt() 時的下一個 argv指針的索引。
optopt —— 最后一個未知選項。
opterr —— 如果不希望getopt()打印出錯信息,則只要將全域變量opterr設為0即可。
用法
getopt_long
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts,int *longindex);
這是getopt函數的加強版,getopt不支持長選項(例如:--ipaddr
這種),getopt_long除了支持getopt的所有功能之外,還支持長選項。
短選項的用法與getopt完全一樣。
getopt_long函數的第四個參數(longopts)與第三個參數(optstring)功能一致,optstring用於支持短選項,longopts則用於支持長選項。
longopts是一個結構體數組,每個結構體表示一個支持的選項
struct option {
const char *name; /* 參數名稱 */
int has_arg; /* 是否帶有參數*/
int *flag; /* flag=NULL時,返回value;不為空時,*flag=val,返回0 */
int val; /* 指定函數匹配到*name表示的選項后,getopt_long函數的返回值,或flag非空時指定*flag的值 */
};
假設有例子:
代碼實例
更實際的使用例子:
#include <cstring>
#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>
//long opt
char ip[20];
char port[20];
//short opt
char age[20];
char name[20];
int main(int argc, char *argv[]) {
int opt = 0;
int opt_index = 0;
//a means age, n means name
char *optstr= "a:n:";
static struct option long_options[] = {
{"ip", required_argument, NULL, 1},
{"port",required_argument, NULL, 2},
{NULL, 0, NULL, 0},
};
while((opt =getopt_long_only(argc,argv,optstr,long_options,&opt_index))!= -1){
switch(opt){
//ip
case 1:
memcpy(ip,optarg,strlen(optarg));
break;
//port
case 2:
memcpy(port,optarg,strlen(optarg));
break;
//age
case 'a':
memcpy(age,optarg,strlen(optarg));
break;
//name
case 'n':
memcpy(name,optarg,strlen(optarg));
break;
}
}
printf("ip:%s, addr:%s, age:%s, name:%s\n", ip, port, age, name);
return 0;
}
執行結果:
不帶-*
的參數
比如cat a.txt
這種類型
假設有例子app -port 9900 a.txt
在getopt函數返回-1
之后,再去打印argv[optind]
就是跟在最后邊的a.txt