• 命令行参数解析getopt


    命令行解析参数

    GNU C提供的函数getopt、getopt_long、getopt_long_only函数来解析命令行参数

    https://github.com/tylov/STC/blob/master/docs/coption_api.md

    STC coption: Command line argument parsing

    This describes the API of the coption_get() function for command line argument parsing.

    See getopt_long for a similar posix function.

    Types

    typedef enum {
        coption_no_argument,
        coption_required_argument,
        coption_optional_argument
    } coption_type;
    
    typedef struct {
        const char *name;
        coption_type type;
        int val;
    } coption_long;
    
    typedef struct {
        int ind;            /* equivalent to posix optind */
        int opt;            /* equivalent to posix optopt */
        const char *optstr; /* points to the option string, if any */
        const char *arg;    /* equivalent to posix optarg */
        ...
    } coption;

    Methods

    coption         coption_init(void);
    int             coption_get(coption *opt, int argc, char *argv[],
                                const char *shortopts, const coption_long *longopts);

    Example

    #include <stdio.h>
    #include <stc/coption.h>
    
    int main(int argc, char *argv[]) {
        coption_long longopts[] = {
            {"foo", coption_no_argument,       'f'},
            {"bar", coption_required_argument, 'b'},
            {"opt", coption_optional_argument, 'o'},
            {0}
        };
        const char* shortopts = "xy:z::123";
        if (argc == 1) 
            printf("Usage: program -x -y ARG -z [ARG] -1 -2 -3 --foo --bar ARG --opt [ARG] [ARGUMENTS]\n", argv[0]);
        coption opt = coption_init();
        int c;
        while ((c = coption_get(&opt, argc, argv, shortopts, longopts)) != -1) {
            switch (c) {
                case '?': printf("error: unknown option: %s\n", opt.optstr); break;
                case ':': printf("error: missing argument for %s\n", opt.optstr); break;
                default:  printf("option: %c [%s]\n", opt.opt, opt.arg ? opt.arg : ""); break;
            }
        }
        printf("\nNon-option arguments:");
        for (int i = opt.ind; i < argc; ++i)
            printf(" %s", argv[i]);
        putchar('\n');
    }
        return 0;
    }
  • 相关阅读:
    解决GIT可视化工具Sourcetree拉取失败问题
    记录常用Git命令
    vue开发移动端使用rem的适配方案
    使用HBuilderX实现打包vue项目成app
    使用vue+webpack从零搭建项目
    整理最近面试问道的问题
    模块化之seaJs学习和使用
    理解Object.defineProperty的作用
    vue生命周期
    使用gulp编译sass
  • 原文地址:https://www.cnblogs.com/sinferwu/p/16295411.html
Copyright © 2020-2023  润新知