getopt函数的使用
时间:2015-08-09 00:29:15
收藏:0
阅读:276
函数说明 getopt()用来分析命令行参数。参数argc和argv分别代表参数个数和内容,跟main()函数的命令行参数是一样的。参数
optstring为选项字符串, 告知 getopt()可以处理哪个选项以及哪个选项需要参数,如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果在处理期间遇到了不符合optstring指定的其他选项getopt()将显示一个错误消息,并将全域变量optarg设为“?”字符,如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int opt;
while((opt = getopt(argc,argv,":if:lr"))!= -1)
{
switch(opt)
{
case 'i':
case 'l':
case 'r':
printf("option :%c\n",opt);
break;
case 'f':
printf("filename: %s\n",optarg);
break;
case ':':
printf("option neads a value\n");
break;
case '?':
printf("unknown option:%c\n",optopt);
break;
}
}
for(; optind < argc; optind++)
{
printf("argument : %s\n",argv[optind]);
exit(0);
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/u011046042/article/details/47363495
评论(0)