getopt( )和 getopt_long( )

有关系统调用getopt:
声明:
         #include <unistd.h>
         int getopt(int argc, char *const argv[], const char *optstring);

         extern char *optarg;
         extern int optind, opterr, optopt;

使用方法:在while循环中反复调用,直到它返回-1。每当找到一个有效的选项字母,它就返回这个字母。如果选项有参数,就设置optarg指向这个参数。
当程序运行时,getopt()函数会设置控制错误处理的几个变量:
char *optarg ──如果选项接受参数的话,那么optarg就是选项参数。
int optind──argv的当前索引,当while循环结束的时候,剩下的操作数在argv[optind]到argv[argc-1]中能找到。
int opterr──当这个变量非零(默认非零)的时候,getopt()函数为"无效选项”和“缺少选项参数”这两种错误情况输出它自己的错误消息。可以在调用getopt()之前设置opterr为0,强制getopt()在发现错误时不输出任何消息。

int optopt──当发现无效选项的进修,getopt()函数或者返回'?'字符,或者返回字符':'字符,并且optopt包含了所发现的无效选项字符。

 

范例 #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’
posted @ 2013-07-20 11:30  herry_tu  阅读(169)  评论(0编辑  收藏  举报