getopt函数的功能

来源:互联网 发布:mac pro怎么截图 编辑:程序博客网 时间:2024/05/16 15:02
头文件: #include<unistd.h>

定义函数
int getopt(int argc,char * const argv[ ],const char * optstring);

函数说明 
getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个 数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错 信息,则只要将全域变量opterr设为0即可。

返回值 如果找到符合的参数则返回此参数字母,如果参数不包含在参数optstring 的选项字母则返回“?”字符,分析结束则返回-1。
范例 #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);
}
执行  
$./aaa –b
option b:b
$./aaa –c
other option:c
$./aaa –a
other option :?
$./aaa –a12345
option a:’12345'

==========================淫荡的分割线=====================================

另一篇

#include <unistd.h>
#include <getopt.h>

extern char *optarg; //指向optstring中有':'的參數在使用時,其後面緊接著的設定值字串。
extern int optind; //表示argv[]中第一個不屬於getopt的參數索引。
extern int opterr; //1: 表示若誤用未列在optstring中的字元當參數,且optstring的第一個字元不是':'時,
        向stderr顯示錯誤訊息。預設為1,若設為0:表不顯示錯誤訊息。
extern int optopt; //指示哪個參數字元的處理出錯,若是用到沒有列在optstring中的字元,
        則以'?'字元表示(若optstring的第一個字元是':',則以':'字元取代'?'字元)。

getopt( int argc, char **argv,
   "ab:c:deq");  <--稱為optstring,後面加':'表示該字元參數在使用時,後面需給設定值。

[功能]:處理"-h"形式的單一字元參數。

[Return Value]
 某字元值:表成功找到該字元 參數。
 ':':表示需要設定值的參數,沒給設定值。
 '?':表示字元不在optstring中。
 '-1':表示需要被找字元已經沒了。

還有
getopt_long()和get_opt_long)only(),處理"--help"形式的長字串參數。

原创粉丝点击