似乎无法使用 C 的 getopt() 访问多个选项

Cant seem to access multiple options using getopt() for C

TL;DR - 我的问题是我似乎无法同时使用这两个选项。只有“-n”在工作。我也希望“-h”起作用。

我正在尝试创建一个程序,基本上打印出“.txt”或“.log”文件的最后几个字母。但是,我 运行 遇到了使用 getopt() 的问题。我正在尝试使用命令行访问不同的案例,但我只能访问第一个案例

我已经尝试在 "nLh" 之后包含冒号 (:),但它最终会输出 "segmentation fault"(核心已转储)”错误。

Ex1: ./print.out -h(失败)

我传入的内容

./print.out -h

预期输出

用法:./print.out -n

实际产量

段错误(核心转储)

Ex2: ./print.out -n 60 (成功)

我传入的内容

./print.out -n 60

预期输出

txt 文件中的随机文本文件...txt 文件中的随机文本文件

实际产量

txt 文件中的随机文本文件...txt 文件中的随机文本文件

    if(argc >1)
    {   
        while ((option =getopt(argc,argv,"nLh"))!=-1)
        {
            switch (option)
            {
                case 'n':

                    if( isExtensionTXTorLog && charactersRead >0)
                    {
                    }

                    else if( argc == 3 && !isExtensionTXTorLog)
                    {   
                    }
                    else
                    {
                        exit(2);
                    }
                    break;
                case 'L':
                    break;
                case 'h':
                    printUsage();
                    break;
                case '?':
                    exit(0);
                    break;
                default:
                    break;
            }
        }

    }
    else
    {
        accessDefault(buffer);
        return 0;
    }

您使用 optind 的方式有误。 optind 用于获取非选项参数 after 解析所有选项。要使用参数解析选项,请使用 n:,然后读取 optarg 变量

看看这个最小的例子:

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

int main(int argc, char *argv[])
{
    char option;
    int n_param;

    while ((option =getopt(argc,argv,"n:h"))!=-1)
    {
        //Variable initialization
        switch (option)
        {
            case 'n':
                n_param = atoi(optarg);
                printf("Param N: %d\n", n_param);
                break;
            case 'h':
                printf("Help\n");
                exit(0);
                break;
            case '?':
                printf("Unrecognized option\n");
                exit(0);
                break;
            default:
                break;
        }
    }

    for (int index = optind; index < argc; index++)
        printf ("Non-option argument %s\n", argv[index]);

    return 0;
}

示例:

./a.out ARG1 -n 50 ARG2  

输出:

Param N: 50
Non-option argument ARG1
Non-option argument ARG2