標準庫函數:getopt
標頭檔 #include <unistd.h>
int getopt(int argc, char * const argv[],const char *optstring);
解釋:take the argc and argv as passed to main function (argc和argv參數與int main(int argc,char * argv[])相同)
and an options specifier string that tells
getopt函數 what options are defined for the program and whether they have associated values.
the optstring is simply a list of characters,each representing a single character option.
if a character is followed by a colon(冒號),it indicatess that the option has an associated value that
will be taken as the next argument.
舉例:getopt(argc,argv,"if:lr");
it allows for simple options -i,-l,-r and -f(後緊跟一個filename參數)
假設執行程式名為test
./test -lrf:i
則argc=2 argv[0]="./test" argv[1]="-lrf:i" (已驗證)
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc,char*argv[])
{
int opt;
while((opt=getopt(argc,argv,"if:lr")) != -1)
{
switch(opt)
{
case 'i':
printf("i: %d\n",optind);
printf("option: %c\n",opt);
break;
case 'l':
printf("l: %d\n",optind);
printf("option: %c\n",opt);
break;
case 'r':
printf("r: %d\n",optind);
printf("option: %c\n",opt);
break;
case 'f':
printf("f: %d\n",optind);
printf("filename: %s\n",optarg);
break;
}
}
printf("final optind: %d",optind);
for(;optind<argc;++optind)
printf("argument: %s\n",argv[optind]);
exit(0);
}
假設執行程式名為aaa
./aaa -i -lr 'hello world' -f fred.c
輸出如下:
i: 2
option: i
l: 2
option: l
r: 3
option: r
f: 6
filename: fred.c
5
argument: hello world
分析:
man 3 getopt 擷取協助
The variable optind is the index of the next element to be processed in
argv. The system initializes this value to 1. The caller can reset it
to 1 to restart scanning of the same argv, or when scanning a new argu‐
ment vector.
If getopt() finds another option character, it returns that character,
updating the external variable optind and a static variable nextchar so
that the next call to getopt() can resume the scan with the following
option character or argv-element.
If there are no more option characters, getopt() returns -1. Then
optind is the index in argv of the first argv-element that is not an
option.
意思是:變數optind(初始值為1)是argv的索引,代表下個元素(待處理)。
如果getopt找到可選項字元,則getopt返回這個字元並更新(註:不一定add)
optind。
如果不再有可選項字元,則getopt返回-1。
optind就是第一個argv元素(不是可選項)的索引(這句話很重要 說明最後optind會
被修改)。
重要:By default, getopt() permutes(排列) the contents of argv as it scans, so that
eventually all the nonoptions are at the end.
分析上面的例子:
argv指向{"./aaa","-i","-lr","hello world","-f","fred.c"}
i=2 意思是下一個待處理的元素在argv中的索引是2
l=2意思同i,因為l的下一個待處理元素是r,而r的索引是2
r=3 即r之後的元素在argv的索引是3
f=6 因為f後跟的fred.c的索引是5,fred.c是f的參數,所以f=6
由於f之後不再有可選項,所以getopt返回-1,而optind則是hello world在argv中的索引(註:
非可選項已被調整到可選項後面 所以其索引為5 即 ./aaa -i -lr -f fred.c 'hello world')