getopt函式
函式功能:用來解析命令列引數,引數argc和ar**分別代表引數個數和內容,跟main()函式裡的命令列引數一樣
函式所在標頭檔案:#include
函式原型定義:int
getopt
(int argc,
char
*const ar**,
const
char
*optstring )
引數optstring: 為選項字串,告知getopt可以處理那個選項以及哪個選項需要引數,如果選項字串裡的字母後接著冒號:「:」,則表示還有相關的引數,全域變數optarg即會指向此額外引數,如果在處理期間遇到了不符合optstring指定的其他選項,getopt
()將會顯示乙個錯誤訊息,並將全域性域變數設定為「?」字元,將全域性域變數opterr設定為0則將不會列印出錯資訊。
引數optarg:指向當前選項引數的指標
引數optopt:表示最後乙個未知選項
#include
"head.h"
// 標頭檔案在這裡哦,三個;
intmain
(int argc,
char
**ar**)
}return0;
}1../a.out -a -b -c -c123 [0]
//索引:0 1 2 3 4 5
opt a found!
ind =
2//找到a時a被解析,跳向下乙個索引輸出;
opt b found!
ind =
4// -c 為b的引數,會被解析,跳向下乙個索引並輸出;
arg for b =
-copt c found!
ind =
5arg for c =
123usage :
./a.out -a -b barg -c[carg]!2.
./a.out -a -b -c123 [1]
// 索引:0 1 2 3
opt a found!
ind =
2// 找到a時a被解析,跳向下乙個索引輸出;
opt b found!
ind =
4// -c123 為b 的引數被解析,跳向下一索引;
arg for b =
-c123
usage :
./a.out -a -b barg -c[carg]
!
Linux命令列解析函式getopt
include include int main int argc,char argv return 0 a.out a x a,no opt a.out a b x a,no opt b,opt x a.out ab x c xx a,no opt b,opt x c,opt xx應緊跟c後面 a...
linux下命令列解析getopt函式
命令列引數解析函式 getopt getopt 函式宣告如下 include int getopt int argc,char const argv,const char optstring extern char optarg extern int optind,opterr,optopt 該函式...
Linux下命令列解析函式getopt簡單使用
以前寫一些除錯程式的時候解析命令都是使用strtok作分割再判斷,偶然間看到由乙個getopt函式,可以很快的實現這個功能。include int getopt int argc,char const ar const char optstring extern char optarg extern...