2009年2月13日 星期五

getopt - getopt_long - 命令行參數的分析

在實際程序之中我們經常要對命令行參數進行分析. 比如我們有一個程序a可以接受許多參數.一個可能的情況是
a -d print --option1 hello --option2 world
那我們如何對這個命令的參數進行分析了?.經常用函數是getopt和getopt_long.
==============================================================
int getopt(int argc,char const **argv, const char *optstring);
==============================================================
int getopt_long(int argc,char const **argc, const char *optstring,const struct option *longopts, int *longindex);
==============================================================

這裡有一個getopt的範例程式
main.c

#include <stdio.h>
#include <unistd.h>
int main(int argc,char **argv)
{
int ch; 
opterr = 0;
while((ch = getopt(argc,argv,"a:bcde"))!= -1) 
switch(ch)
{
case 'a':
printf("option a:'%s'\n",optarg);
break;
case 'b':
printf("option b :b\n");
break;
default:
printf("other option :%c\n",ch);
}
printf("optopt +%c\n",optopt);
}

執行方式:
$ ./getopt –b
option b:b
$ ./getopt –c
other option:c
$ ./getopt –a
other option :?
$ ./getopt –a12345
option a:'12345'


[2014/12/11 補充]
若參數後面要加數值的話,
則要加:

若不用另外加數值的話,則不需要加:

[2015/02/12 補充]
若想抓的參數是沒有接在-c這種後面的話,則可以使用optind
argv[optind]

而若有多個這種類型的參數的話,則可以使用迴圈
例如:
# ./a.out text.txt text2.txt

程式碼為:
for(; optind < argc; optind++)
{
  puts(argv[optind]);
}

參考資料:
命令行參數的分析
getopt(分析命令行參數)
C語言 getopt用法

沒有留言: