c - getopt 如何设置默认值

标签 c getopt

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>


int main(int argc, char **argv) {
    int o;
    int w = 10;

    while ((o = getopt(argc, argv, "w")) != -1) {
        switch (o) {
            case 'w' :
                w = atoi(optarg);
                break;



        }

    }
    printf("%d\n", w);
}

基本上,如果没有输入任何内容,我希望 -w 具有。

考虑这些用例

$ gcc -Wall fileabove.c
$ ./a.out 
10
$ ./a.out -w
10
$ ./a.out -w14
14

我无法让第二个工作。有什么方法可以使用 getopt 来获得预期的结果吗?

最佳答案

假设您正在使用 GNU getopt,以下内容应该可以工作:

    while ((o = getopt(argc, argv, "w::")) != -1) {
        switch (o) {
            case 'w' :
                if (optarg) {
                    w = atoi(optarg);
                }
                break;

以下 : 将该选项标记为需要参数。双 : 使参数可选(这是 GNU 扩展)。如果没有参数,optargNULL

关于c - getopt 如何设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49021769/

相关文章:

c - C %f 的 printf 在小数点后留下 6 个 0

C大写转小写

bash - 使用 getopt 解析长参数会跳到第一个值

c - 是否可以重复getopt

python - Python 的 argparse 可以像 gnu getopt 一样置换参数顺序吗?

c++ - getopt加入参数

c - 在 C 中编程以读取参数

c - 按 '/' 拆分字符串失败,C

c - 单元测试 C 库,内存管理

c - Valgrind/内存错误