什么是用于创建C / C ++在Unix / Linux的命令行工具的最佳做法?(What is t

2019-08-03 12:16发布

我目前任务是我们内部开发团队使用创造一些命令行帮助工具。 不过,我想知道创建UNIX命令行工具的最佳实践。 我试图观看GIT中的源代码用于如何相应读取参数和显示消息的示例。 不过,我正在寻找一个明确的模板创建工具,安全地读取参数,并显示标准的“帮助”信息如果不正确的参数或用户类型--help我想说明的帮助信息。 是否有用于读取标准库-abcFGH--parameter和交换哪些过程开始基于传递的参数?

命令行:

git

要么

git --help

输出:

usage: git [--version] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
       [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
       [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
       [-c name=value] [--help]
       <command> [<args>]
...

命令行:

MyTool CommandName --CommandArgs

输出:

无论是具体的命令一样。


我迄今为止的工作:

码:

int main(int argc, char **argv)
{
    if(argc < 2)
    helpMessage();
    char* commandParameter = argv[1];
    if (strncmp(argv [1],"help", strlen(commandParameter)) == 0)
        helpMessage();
    else if (strncmp(argv [1],"pull", strlen(commandParameter)) == 0)
        pull();
    else
        helpMessage();
}

什么是理想的做法是这样的:

码:

int main(int argc, char **argv)
{
    MagicParameters magicParameters = new MagicParameters(argv);
    switch(magicParameters[1])
    {
        case command1:
            Command1();
            break;
        case ...

        case help:
        default:
            HelpMessage();
            break;
    }
}

Answer 1:

getopt_long()是你在找什么,这里是最简单的用法的例子:

   static const struct option opts[] = {
        {"version",   no_argument,    0, 'v'},
        {"help",      no_argument,    0, 'h'},
        {"message", required_argument, 0, 'm'},
        /* And so on */
        {0,      0,                   0,  0 }   /* Sentiel */
    };
    int optidx;
    char c;

    /* <option> and a ':' means it's marked as required_argument, make sure to do that.
     * or optional_argument if it's optional.
     * You can pass NULL as the last argument if it's not needed.  */
    while ((c = getopt_long(argc, argv, "vhm:", opts, &optidx)) != -1) {
        switch (c) {
            case 'v': print_version(); break;
            case 'h': help(argv[0]); break;
            case 'm': printf("%s\n", optarg); break;
            case '?': help(argv[0]); return 1;                /* getopt already thrown an error */
            default:
                if (optopt == 'c')
                    fprintf(stderr, "Option -%c requires an argument.\n",
                        optopt);
                else if (isprint(optopt))
                    fprintf(stderr, "Unknown option -%c.\n", optopt);
                else
                    fprintf(stderr, "Unknown option character '\\x%x'.\n",
                        optopt);
               return 1;
        }
    }
    /* Loop through other arguments ("leftovers").  */
    while (optind < argc) {
        /* whatever */;
        ++optind;
    }


Answer 2:

看看在getopt的图书馆。



文章来源: What is the best practice for creating a unix/linux command-line tool in C/C++?