首页 > 编程知识 正文

getcolvalue用法,getopt源码

时间:2023-05-05 17:29:26 阅读:155988 作者:2059

intgetopt(intargc,char * const argv[],const char *optstring ); intgetopt_long(intargc,char * const argv[],const char *optstring,const struct option *longopts,int *longindex )

从最简单的getopt讲起,getopt函数的前两个参数,就是main函数的argc和argv,这两者直接传入即可,要考虑的就只剩下第三个参数。

传递上述optstring后,getopt函数必须依次检查命令行中是否指定了-a、-b、-c和-d,并多次调用getopt函数,直到返回-1。 如果选中指定了以上参数之一,函数将返回指定的参数名称或字符

最后一个参数d后面有冒号,表示参数d可以指定-d 100或-d user等值

optind表示要处理的下一个参数的argv下标值。

如果指定opterr=0,则即使getopt、getopt_long和getopt_long_only发生错误,标准输出流中也不会输出错误消息

optstring是参数选项 :比如 char *optstring = “abcd:”;

其中,longopts是指由option结构组成的数组,该数组中的每个元素都显示“长参数”的名称和性质,例如--name。 struct option { const char *name; int has_arg; int *标志; int val; (; name是参数的名称has_arg指示是否具有参数值,该值是可选的。 no_argument表示这个长参数没有参数,也就是说没有数值。 例如,--name,required_argument表示此长参数必须具有参数,即必须具有数值。例如,--name 100 ) optional_argument 指示该长参数后面的参数是可选的,include unistd.h # include stdlib int digit _ oot (即,可以同时存在--name和--name 100 ) int option_index=0; char * optstring=' a : b : c : d '; staticstructoptionlong _ options [ ]={ ' req arg ',required_argument,NULL,' r'},{'noarg ',no _ argument whid=-1 ) printf(opt=%cn ),opt ); printf(optarg=%s(n ),optarg ); printf(optind=%d(n ),optind ); printf(argv[optind - 1]=%sn ),argv[optind-1]; printf(option_index=%dn ),option_index ); }返回0; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。