C中的CLI参数

Raj*_*jiv 1 c command-line-interface command-line-arguments

我们正在开发一个程序,它应该接受同一个参数的多个输入.例如.

program1 -A arg1 -A arg2 -A arg3 -B arg4 -B arg5 -B arg6

更复杂的是,-A和-B参数具有1:1的关系.所以arg1映射到arg4,所以一个.

那么上面的例子是最好的方法可以提供多个相同的参数列表吗?或者这是可接受的方式?

Dim*_*tri 5

C语言提供函数getopt来解析命令行选项.的 getopt_long功能是GNU扩展,将分析,提供比更多的功能的命令行选项的getopt如多字符选项解析.你可以在这里找到文档:http://linux.die.net/man/3/getopt_long或者只是一个人getopt_long.让我举个例子.假设您有一个程序有3个选项(-h表示帮助消息,-i表示显示整数,-s表示字符串).首先,您必须声明一个struct选项.此结构将包含程序所需的所有选项,并按以下方式定义:

    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.
};
Run Code Online (Sandbox Code Playgroud)

作为您的程序有很多选项,您必须声明一个struct选项数组:

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}};
Run Code Online (Sandbox Code Playgroud)

您可以阅读以下选项:

 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");
   }

    }
Run Code Online (Sandbox Code Playgroud)

别忘了包含"getopt.h"

祝好运