[简单明了]c c++ getopt函数
来源:互联网 发布:淘宝客导购名称写什么 编辑:程序博客网 时间:2024/06/11 03:00
转自:http://speakingbaicai.blog.51cto.com/5667326/1074671
/*
原型:int getopt(int argc, char * const argv[], const char *optstring);
四个全局变量:
extern char *optarg; //指向选项的参数的指针。
extern int optind, //存储位置,下一次调用getopt的时,从optind存储的位置处重新开始检查选项。
extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中。
关于optstring:
如: optstring=ab:c::d::时,
1、ab:c::d::的意思是有四个选项-a -b -c -d;
2、其中b c d选项后面有冒号说明b c d后面必须跟参数;
3、b后一个冒号,则参赛和选项之间可有空格,也可没有;
4、c d后面有两个冒号,说明c d后面的参数必须紧跟在选项后面。
如:./a.out -a -b argOfb -cargOfc -dargOfd
如果写成:./a.out -a -b argOfb -c argOfc -dargOfd 则c选项后的参数实际为null
getopt的使用时的主要注意点:
1、getopt每调用一次,返回一个选项,注意是选项不是参数;
2、optarg存放getopt所返回的选项后的参数,选项后没有参数则为null(实际运行时没有或者optstring中的选项后没有:都视为null);
3、当再也检查不到optstring所包含的选项时返回-1;
4、当检查到不在optstring中的选项或缺少必要的参数时,返回?并将该选项存在optopt中。
总结:
在使用时,只需简记getopt返回选项,optarg指向参数即可。
*/
#include <unistd.h>
int main(int argc, char **argv)
{
int opt;
opterr = 0;
while( (opt = getopt(argc, argv, "ab:c::d::")) != -1 )
{
switch(opt)
{
case 'a':
printf("option=a, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case 'b':
printf("option=b, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case 'c':
printf("option=c, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case 'd':
printf("option=d, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case '?':
printf("option=?, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
default:
printf("option=default, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
}
}
return 0;
}
/*
- [简单明了]c c++ getopt函数
- c getopt函数用法
- C函数getopt使用
- C语言-getopt函数
- C语言 getopt()函数
- C语言getopt()函数
- C语言getopt()函数
- C语言中getopt()函数
- C语言getopt()函数的使用
- 《c和指针》笔记--getopt函数
- C语言中getopt函数用法
- C语言getopt()函数的使用
- C语言getopt()函数的使用
- C语言getopt()函数的使用
- C语言中的getopt()和getopt_long()函数
- C语言getopt函数的简单使用
- C语言getopt()函数的使用
- C语言getopt()函数的使用
- Find a way(bfs)
- Spring MVC工作流程
- html frameset框架
- 第九章 组织文件 笔记
- python003 Python3 基本数据类型
- [简单明了]c c++ getopt函数
- python flask 服务器端实现接口,post,get 方式,参数获取方法
- 集合中线程安全的类回顾+更改为线程安全的方法
- hdu2553八皇后问题(DFS)
- svn 回滚
- UVa11400 Lighting System Design
- UVa12563 Jin Ge Jin Qu hao
- MariaDB更改密码
- python笔记2-django建项目