C 语言提供函数getopt 来解析命令行选项。 getopt_long 函数是一个 GNU 扩展,它解析提供比 getopt 更多功能的命令行选项,例如多字符选项解析。你可以在这里找到文档:http://linux.die.net/man/3/getopt_long 或者只是一个男人 getopt_long。
让我举个例子。假设您有一个具有 3 个选项的程序(-h 用于帮助消息,-i 用于显示整数,-s 用于显示字符串)。首先,你必须声明一个struct options。此结构将包含您的程序需要的所有选项,并且定义如下:
struct option {
const char *name; // the option name
int has_arg; // if your option has an argument - no_argument (equivalent to 0) if no option and required_argument otherwise (1)
int *flag; // specifies how results are returned for a long option. If flag is NULL, then getopt_long() returns val
int val; // is the value to return, or to load into the variable pointed to by flag.
};
由于你的程序有很多选项,你必须声明一个结构体选项数组:
struct option options[] = {
{"help", no_argument, NULL, 'h'}, // for the help msg
{"int", 1, required_argument, 'i'}, // display an int
{"string", required_argument, NULL, 's'}, // displays a string
{NULL, 0, NULL, 0}};
你的选择如下:
int main(int argc, char* argv[]){
char opt;
while ((opt = getopt_long (argc, argv, "his:", options, NULL)) != -1) {
switch(opt){
case 'h': printf("Help message \n"); exit(0);
case 'i': printf("Int options = %d\n", optarg);break;
case 's': printf("String option = %s\n", optarg); break;
default: printf("Help message\n");
}
}
不要忘记包含 "getopt.h"
祝你好运