本文共 3595 字,大约阅读时间需要 11 分钟。
getopt.h是GnuLib库中一个重要的头文件,广泛应用于各种软件和套件中。它定义了处理命令行选项的基本功能,为程序的参数解析提供了强有力的支持。
getopt.h文件主要定义了以下内容:
struct option结构体,用于描述长选项(即以--开头的选项)。optarg、optind、opterr、optopt等变量,用于存储解析过程中的参数信息。getopt(int argc, char *const argv[], const char *optstring): 解析短选项(如-o、-i等)。getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex): 解析长选项(如--help、--datadir等)。getopt_long_only(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex): 专门用于处理长选项的简化版本。getopt函数是最常用的选项解析函数,其参数包括:
argc:主程序传入的命令行参数个数。argv:存储命令行参数的数组。optstring:一个字符串,包含所有有效的短选项字符。在optstring中,每个字符可以有以下两种表示方式:
::表示该选项有对应的参数,参数会被存储在optarg变量中。getopt函数的执行过程:
argv数组中的每个参数。-开头,检查其后是否有有效的选项字符。optarg、optind等)。argv数组已遍历完毕,getopt返回-1,表示解析完成。#include#include int main(int argc, char *const argv[]) { static struct option long_options[] = { {0}, {1}, {2}, ... }; int option_index = 0; int opt = getopt(argc, argv, "abc"); // 根据返回值进行相应的处理}
getopt_long函数扩展了getopt的功能,能够处理长选项。其参数包括:
longopts:一个struct option数组,存储所有长选项的信息。longindex:一个指针,用于记录当前解析的是longopts数组中的哪个选项。struct option结构体包含以下成员:
name:长选项的名称。has_arg:选项是否有参数(可选值:no_argument、required_argument、optional_argument)。flag:如果为NULL,表示该选项是一个布尔标志;否则,表示该选项有一个值。val:该选项的值。#includestatic struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"datadir", required_argument, 0, 'd'}, {"int8", no_argument, 0, 'i'}, {"fp16", no_argument, 0, 'f'}, {"useILoop", no_argument, 0, 'l'}, {"useDLACore", required_argument, 0, 'u'}, {"batch", required_argument, 0, 'b'}, {nullptr, 0, nullptr, 0}};int option_index = 0;int arg = getopt_long(argc, argv, "hd:iu", long_options, &option_index);
TensorRT框架中常见一个参数解析的例子:
#include#include namespace samplesCommon { bool parseArgs(Args &args, int argc, char *argv[]) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"datadir", required_argument, 0, 'd'}, {"int8", no_argument, 0, 'i'}, {"fp16", no_argument, 0, 'f'}, {"useILoop", no_argument, 0, 'l'}, {"useDLACore", required_argument, 0, 'u'}, {"batch", required_argument, 0, 'b'}, {nullptr, 0, nullptr, 0} }; int option_index = 0; while (true) { int arg = getopt_long(argc, argv, "hd:iuflb", long_options, &option_index); if (arg == -1) { break; } switch (arg) { case 'h': args.help = true; return true; case 'd': if (optarg) { args.dataDirs.push_back(optarg); } else { std::cerr << "ERROR: --datadir requires option argument" << std::endl; return false; } case 'i': args.runInInt8 = true; break; case 'f': args.runInFp16 = true; break; case 'l': args.useILoop = true; break; case 'u': if (optarg) { args.useDLACore = std::stoi(optarg); } break; case 'b': if (optarg) { args.batch = std::stoi(optarg); } break; default: return false; } } return true; }}
getopt.h头文件为程序员提供了强大的选项解析工具,支持处理短选项和长选项,并允许自定义参数解析逻辑。通过合理使用这些函数,开发者可以实现更加灵活和用户友好的命令行参数解析方案。
转载地址:http://xatm.baihongyu.com/