学习解析命令行参数函数 —— getopt函数
背景
工作的过程中,我们需要根据命令行参数来决定程序运行的过程。因此我们可以使用getopt函数来满足我们的工作需要。
函数简介
函数原型如下:
int getopt(int argc, char * const argv[], const char *optstring);
如果getopt函数找到一个选项字符,则返回该字符,更新外部变量optind和一个静态变量nextchar,以便下次调用getopt函数可以使用下一个选项字符或argv中 带-符号的参数恢复扫描。如果没有更多选项字符,getopt()返回-1。 那么optind是第一个argv中带-的参数的索引。
optstring是一个包含合法选项字符的字符串。
补充说明:
extern char *optarg;
extern int optind, opterr, optopt;
变量optind是要在argv中处理的下一个元素的索引。 系统将该值初始化为1.调用者可以将其重置为1,以重新扫描相同的argv,或扫描新的参数向量时。
如果getopt()不识别选项字符,则会向stderr打印一条错误消息,将该角色存储在optopt中,并返回'?'。调用程序可以通过将opterr设置为0来阻止错误消息。
测试代码
以下代码存放在test.c文件中
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int flags, opt;
char *tvalue;
flags = 0;
//解析argc、argv参数,argv参数要求t后面需要有参数值,参数n后面可以不接参数值
while ((opt = getopt(argc, argv, "nt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
tvalue = optarg;// -t 后从参数值存储在optarg全局变量中
break;
case '?': /* 如果不是-n 或-t参数 ,返回’?’ */
fprintf(stderr, "Usage: %s [-t tvalue] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
//用于查看opterr, optind,optopt变量
printf("opterr=%d; optind=%d ;optopt=%d\n", opterr, optind,optopt);
if (optind >= argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
printf("name argument = %s\n", argv[optind]);
exit(EXIT_SUCCESS);
}
编译生成测试程序
gcc test.c
总结
我们可以使用getopt函数来解析命令行参数。
参考资料
以上资料是根据在Linux终端上运行man getopt的信息总结而来的。