C语言中使用库函数解析命令行参数
在編寫需要命令行參數(shù)的C程序的時(shí)候,往往我們需要先解析命令行參數(shù),然后根據(jù)這些參數(shù)來啟動(dòng)我們的程序。
C的庫函數(shù)中提供了兩個(gè)函數(shù)可以用來幫助我們解析命令行參數(shù):getopt、getopt_long。
getopt可以解析短參數(shù),所謂短參數(shù)就是指選項(xiàng)前只有一個(gè)“-”(如-t),而getopt_long則支持短參數(shù)跟長參數(shù)(如"--prefix")。
?
getopt函數(shù)
#include<unistd.h> int getopt(int argc,char * const argv[],const char *optstring);extern char *optarg; //當(dāng)前選項(xiàng)參數(shù)字串(如果有) extern int optind; //argv的當(dāng)前索引值
各參數(shù)的意義:
argc:通常為main函數(shù)中的argc
argv:通常為main函數(shù)中的argv
optstring:用來指定選項(xiàng)的內(nèi)容(如:"ab:c"),它由多個(gè)部分組成,表示的意義分別為:
1.單個(gè)字符,表示選項(xiàng)。
2 單個(gè)字符后接一個(gè)冒號(hào):表示該選項(xiàng)后必須跟一個(gè)參數(shù)。參數(shù)緊跟在選項(xiàng)后或者以空格隔開。該參數(shù)的指針賦給optarg。
3 單個(gè)字符后跟兩個(gè)冒號(hào),表示該選項(xiàng)后可以跟一個(gè)參數(shù),也可以不跟。如果跟一個(gè)參數(shù),參數(shù)必須緊跟在選項(xiàng)后不能以空格隔開。該參數(shù)的指針賦給optarg。
?
調(diào)用該函數(shù)將返回解析到的當(dāng)前選項(xiàng),該選項(xiàng)的參數(shù)將賦給optarg,如果該選項(xiàng)沒有參數(shù),則optarg為NULL。下面將演示該函數(shù)的用法
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <string.h> 4 5 int main(int argc,char *argv[]) 6 { 7 int opt=0; 8 int a=0; 9 int b=0; 10 char s[50]; 11 while((opt=getopt(argc,argv,"ab:"))!=-1) 12 { 13 switch(opt) 14 { 15 case 'a':a=1;break; 16 case 'b':b=1;strcpy(s,optarg);break; 17 } 18 } 19 if(a) 20 printf("option a\n"); 21 if(b) 22 printf("option b:%s\n",s); 23 return 0; 24 } View Code編譯之后可以如下調(diào)用該程序
?
getopt_long函數(shù)
與getopt不同的是,getopt_long還支持長參數(shù)。
#include <getopt.h> int getopt_long(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex);前面三個(gè)參數(shù)跟getopt函數(shù)一樣(解析到短參數(shù)時(shí)返回值跟getopt一樣),而長參數(shù)的解析則與longopts參數(shù)相關(guān),該參數(shù)使用如下的結(jié)構(gòu)
struct option {//長參數(shù)名const char *name;/*表示參數(shù)的個(gè)數(shù)no_argument(或者0),表示該選項(xiàng)后面不跟參數(shù)值required_argument(或者1),表示該選項(xiàng)后面一定跟一個(gè)參數(shù)optional_argument(或者2),表示該選項(xiàng)后面的參數(shù)可選*/int has_arg;//如果flag為NULL,則函數(shù)會(huì)返回下面val參數(shù)的值,否則返回0,并將val值賦予賦予flag所指向的內(nèi)存int *flag;//配合flag來決定返回值int val; };參數(shù)longindex,表示當(dāng)前長參數(shù)在longopts中的索引值,如果不需要可以置為NULL。
下面是使用該函數(shù)的一個(gè)例子
1 #include <stdio.h> 2 #include <string.h> 3 #include <getopt.h> 4 5 int learn=0; 6 static const struct option long_option[]={ 7 {"name",required_argument,NULL,'n'}, 8 {"learn",no_argument,&learn,1}, 9 {NULL,0,NULL,0} 10 }; 11 12 int main(int argc,char *argv[]) 13 { 14 int opt=0; 15 while((opt=getopt_long(argc,argv,"n:l",long_option,NULL))!=-1) 16 { 17 switch(opt) 18 { 19 case 0:break; 20 case 'n':printf("name:%s ",optarg); 21 } 22 } 23 if(learn) 24 printf("learning\n"); 25 } View Code編譯之后可以如下調(diào)用該程序
轉(zhuǎn)載于:https://www.cnblogs.com/runnyu/p/4943704.html
總結(jié)
以上是生活随笔為你收集整理的C语言中使用库函数解析命令行参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何阅读学术论文、聆听学术报告 —— 叶
- 下一篇: Struts(八)Strits2访问se