使用optparse 替代解决 getopt 不可重入的问题

download

源码

概述

Optparse is a public domain, portable, reentrant, embeddable,
getopt-like option parser. It’s a single header file and can be
trivially dropped into any project. It supports POSIX getopt option
strings, GNU-style long options, argument permutation, and subcommand
processing.

使用

optparse_long替代getopt_long

example:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define OPTPARSE_IMPLEMENTATION
#define OPTPARSE_API static
#include "optparse.h"
int main(int argc, char **argv)
{
struct optparse_long longopts[] = {
    {"amend", 'a', OPTPARSE_NONE},
    {"brief", 'b', OPTPARSE_NONE},
    {"color", 'c', OPTPARSE_REQUIRED},
    {"delay", 'd', OPTPARSE_OPTIONAL},
    {0}
};
bool amend = false;
bool brief = false;
const char *color = "white";
int delay = 0;
char *arg;
int option;
struct optparse options;

optparse_init(&options, argv);
while ((option = optparse_long(&options, longopts, NULL)) != -1) {
    switch (option) {
    case 'a':
        amend = true;
        break;
    case 'b':
        brief = true;
        break;
    case 'c':
        color = options.optarg;
        break;
    case 'd':
        delay = options.optarg ? atoi(options.optarg) : 1;
        break;
    case '?':
        fprintf(stderr, "%s: %s\n", argv[0], options.errmsg);
        exit(EXIT_FAILURE);
    }
}
/* Print remaining arguments. */
while ((arg = optparse_arg(&options)))
    printf("%s\n", arg);
    return 0;
}

使用optparse替代getopt

example:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define OPTPARSE_IMPLEMENTATION
#define OPTPARSE_API static
#include "optparse.h"

int main(int argc, char **argv)
{
    bool amend = false;
    bool brief = false;
    const char *color = "white";
    int delay = 0;
    char *arg;
    int option;
    struct optparse options;
    optparse_init(&options, argv);
      while ((option = optparse(&options, "abc:d::")) != -1) {
        switch (option) {
        case 'a':
            amend = true;
            break;
        case 'b':
            brief = true;
            break;
        case 'c':
            color = options.optarg;
            break;
        case 'd':
            delay = options.optarg ? atoi(options.optarg) : 1;
            break;
        case '?':
            fprintf(stderr, "%s: %s\n", argv[0], options.errmsg);
            exit(EXIT_FAILURE);
        }
    }
      /* Print remaining arguments. */
    while ((arg = optparse_arg(&options)))
        printf("%s\n", arg);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值