Linux/Uinx 系统编程:getopt()函数用法
getopt()
函数描述
 getopt()函数是用来分析命令行参数的,该函数由Unix标准库提供,包含在<unistd.h>头文件中。
函数原型
#include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
各参数说明
- argc:通常由main函数直接传入,表示参数的数量。
- argv:通常也由main函数直接传入,表示参数的字符串变量数组。
- optstring:由所有合法的选项字符组成的字符串。比如你的程序允许的选项是- -E和- -n,那么- optstring的值就是- "En"。
执行过程
 当给定getopt()命令参数的数量 (argc)、指向这些参数的数组 (argv) 和选项字串 (optstring) 后,getopt()将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有可识别的选项,将返回-1,此任务就完成了。
底层实现
 getopt()函数通过解析命令行参数,返回找到的下一个短选项,如果遇到无法识别的选项则返回’?'。当没有更多短选项时它返回-1,并且设置全局变量optind的值指向argv中所有段选项之后的第一个元素。
执行示例
#include <stdio.h>
#include <unistd.h>int main (int argc, char **argv) {int i;int option;/* parse short options */while ((option = getopt(argc, argv, "bEnsTv")) != -1) {switch (option) {case 'b':puts("Put line numbers next to non-blank lines");break;case 'E':puts("Show the ends of lines as $");break;case 'n':puts("Put line numbers next to all lines");break;case 's':puts("Suppress printing repeated blank lines");break;case 'T':puts("Show tabs as ^I");break;case 'v':puts("Verbose");break;default: /* '?' */puts("What's that??");}}/* print the rest of the command line */puts("------------------------------");for (i = optind; i < argc; i++) {puts(argv[i]);}return 0;
}
这个演示程序没有实现cat命令的所有选项,但它只是能够解析命令行。每当发现一个合法的命令行选项,它就打印出相应的提示消息。
返回值
 getopt()函数在成功解析一个选项时返回该选项的字符(因为字符可以转为整数)。若解析完毕,则返回-1。
执行结果
 执行结果取决于getopt()函数是否成功解析了所有的命令行选项。如果成功,那么所有的命令行选项将被解析,如果失败,那么getopt()函数将返回’?'。
optarg
optarg是一个全局变量,用于存储命令行参数的值。它通常与getopt函数一起使用,用于解析命令行参数。getopt函数可以帮助我们解析命令行参数,并将其转换为可用的选项和参数。而optarg则用于存储选项的参数值。
例如,如果我们有一个命令行工具,它接受一个选项-a,该选项需要一个参数,我们可以使用getopt和optarg来获取这个参数。当我们在命令行中运行tool -a argument时,getopt函数会解析选项-a,并将argument的值存储在optarg中。
下面举个例子方便getopt和optarg的关系和理解:
#include <stdio.h>
#include <unistd.h>int main(int argc, char *argv[]) {int opt;while ((opt = getopt(argc, argv, "a:")) != -1) {switch (opt) {case 'a':printf("Option -a has argument %s\n", optarg);break;default:printf("Unknown option\n");}}return 0;
}
在上面的例子中,定义了一个选项-a,该选项需要一个参数(由a:表示)。当我们运行./program -a argument时,getopt函数会解析选项-a,并将argument的值存储在optarg中。然后,我们可以在程序中使用这个值。。