Getopt:命令行解析函数
来源:互联网 发布:手机微店淘宝搬家2016 编辑:程序博客网 时间:2024/05/22 00:51
涉及到名词:命令+选项+选项参数+操作数
# cat -n 10 /etc /passwd
cat是命令名,-n是选项,10是选项参数,/etc/passwd是操作数。
函数原型:
int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt;
opterr,默认是非零1,如果调用出错时看opterr的值,如果非零就打印错误信息。若果是0就不打印。所以可以在调用前设置opterr=0,抑制getopt内部的错误信息的输出。
optopt,当调用选项在optstring中没有时,opt存放该invalid选项;另外,要是optstring字串中后面接冒号的需要选项参数的选项在调用时没有选项参数,则optopt保存该missing argument的选项。
optarg,当选项需要选项参数时,选项参数会保存在optarg中。
optind,index 下标值,本次调用后argv数组中第一个非选项(包含选项参数)的下标值。
返回值:
1、 正常情况返回解析出来的选项字符,optstring解析完后返回-1。
2、 Invalid参数返回’?’。
3、 Missing argument返回依赖于optstring字串的首字符是否为冒号,如果是冒号则返回冒号,否则返回’?’。
为了便于区分是invalid还是missing argument,建议optstring以冒号开头。
例程:
#include <stdio.h>#include <getopt.h>int main(int argc, char **argv){char result;//opterr = 0;while(-1 != (result = getopt(argc, argv, ":ln:q:m:"))){switch(result){case 'l':printf("This option is 'l'\n");break;case 'n':printf("This option is 'n' which need argument %s\n", optarg);break;case 'q':printf("This option is 'q' which need argument %s\n", optarg);break;case 'm':printf("This option is 'm' which need argument %s\n", optarg);break;case '?':printf("Optioin '%c' is a unknown argument\n", (char)optopt);break;case ':':printf("Option '%c' missing a argument\n", (char)optopt);break;default:break;}}return 0;}
运行结果:
[root@localhost test]# ./a.out -n
Option 'n' missing a argument
[root@localhost test]# ./a.out -m
Option 'm' missing a argument
[root@localhost test]# ./a.out -l
This option is 'l'
- Getopt:命令行解析函数
- 命令行参数解析函数--getopt
- getopt函数和getopt_long函数 解析命令行
- getopt函数和getopt_long函数 解析命令行
- 学习解析命令行参数函数-getopt函数
- 命令行程序选项解析函数—getopt
- getopt(win32) -- 命令行参数解析函数
- 解析命令行选项参数的 getopt函数
- 命令行程序选项解析函数—getopt
- 命令行程序选项解析函数—getopt
- 解析命令行选项参数函数getopt()
- 命令行参数解析函数:getopt和getopt_long
- 【Ubuntu操作系统】命令行解析函数getopt/getopt_long
- 命令行选项参数解析-getopt函数
- linux命令行参数解析函数 getopt
- linux下命令行解析getopt函数
- getopt函数传入命令行
- 常用命令行解析函数——getopt/getopt_long
- weblogic.common.T3StartupDef
- 快速將檔案、圖片二進位檔案塞入資料表
- Boost学习系列6 - 多线程 (上)
- 利用SqlBulkCopy快速大批量导入数据
- WCF手工编写客户端代理
- Getopt:命令行解析函数
- 推荐11本对程序员最有影响力的书籍
- SQL查询优化技术
- 电子&IC常用网站
- JAVA期中作业——弹球游戏 +砖块
- 一体一魂
- 初学ios(一)
- 空间圆弧作图算法,基于OpenGL实现!
- .net网站开发中Session问题经常失效处理的解决办法