对于程序员来说,在linux上用的最多的就是通过命令行来运行程序,但是很多人都不是很清楚命令行的书写格式规范,所以当输入错误的时候,shell就会提示输入错误之类的信息。
我们可以自己编写命令行参数解析程序,但是其实linux已经提供了一个函数来实现相关的功能,这个函数就是getopt函数。
函数原型及相关外部变量声明
extern char *optarg; // 如果一个选项后面接有一个参数值, 则 optarg 就会指向该参数值
extern int optind, // 初始化值为1,被设置为下一个待处理参数的索引。用来记录 getopt 的进度。
extern int opterr, // 初始化值为1,当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt; // 当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,
// 该选项将存储在optopt中, getopt 返回'?’
函数说明
getopt() 用来分析命令行参数,也就是主要用来分析命令行参数中的选项的。参数 argc 和 argv 是由 main() 传递的参数个数和内容。参数 optstring 表示选项指定符字符串。该字符串告诉 getopt 哪些选项可用,以及它们是否有关联值。每调用一次 getopt() 函数,返回一个选项,如果该选项有参数(关联值),则 optarg 指向该参数(关联值)。
函数 getopt() 认为 optstring 中,以 '-’ 开头的字符(注意!不是字符串!!)就是命令行参数选项,有的参数选项后面可以跟参数值。optstring 中的格式规范如下:
1) 单个字符,表示选项,
2) 单个字符后接一个冒号“ :”,表示该选项后必须跟一个参数值(关联值)。参数紧跟在选项后或者以空格隔 开。该参数的指针赋给optarg。
3) 单个字符后跟两个冒号 ” :: ”,表示可选值选项,该选项后如果跟一个参数。参数必须紧跟在选项后不能以空 格隔开。该参数的指针赋给 optarg。
4.有的linux版本会在第一个非选项参数处停下来,返回-1并设置optind的值;有的linux版本能够处理出现在程 序参数中的任意位置的选项,在这种情况下,getopt实际上重写了argv[]数组,将参数都集中在了一起。
返回值
程序范例
#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 needs a value\n"); break; case '?': printf("unknown option: %c\n", optopt); break; } } for(; optind < argc; optind++) { printf("argument: %s\n", argv[optind]); } exit(0); }
程序输出
$ ./argopt -i -lr 'hi there' -f fred.c -q
option: i
option: l
option: r
filename: fred.c
unknown option: q
argument: hi there