c - 命令中命令行选项的不同顺序影响我的输出

标签 c getopt-long

我正在用 c 语言编写一个程序,它接受诸如 --version 、--download 之类的命令行参数。

当我这样做时:

$program --version --download file

程序输出版本并下载文件。但是当我这样做时:

$program --download --version file

程序将 --version 视为 --download 的参数。

我使用了 getopt_long() 函数来解析命令行参数。这是我的代码片段:

while ((ch = getopt_long(argc, argv, "d:g:hv", longoptions, &optindex)) != -1 )
{
    switch(ch)
    {
            case 'd' :
                if ( optarg )
                    printf("Downloading %s...\n" , optarg);
                iso(optarg);
                break ;

            case 'g' :
                if ( optarg )
                    printf("Downloading glug-mirror automation script for %s ...\n", optarg);
                getscript(optarg);
                break ; 

            case 'v' : 
                printf("glug version 1.0.0 ( NIT Hamirpur)\n");
                break ;

            case 'h' :
                usage(status);
                break ;

            default :
                status  = 2 ; 
               usage(status);
    }
}

最佳答案

getoptlong() 正在做它应该做的事情。

  • 格式字符串"d:g:hv" 表示参数dg 需要一个值。
  • 在命令行参数之后指定的任何内容都被视为传递给它的值。

你应该运行你的程序

$program --download file --version

检查这个 detailed example演示使用 getoptlong() 的各个方面。


How rm can handle the differing position of its cmd-line params?

显然是因为 rm 的参数(rv 等)不接受任何值作为参数。因此 directory 不会传递给它们中的任何一个,而是一个单独的 cmd 行参数。您可以从 source-code of rm 确认这一点.

要为您的程序做类似的事情,您需要将 optstring 修改为 "dghv" 并处理参数 "file"分别。

关于c - 命令中命令行选项的不同顺序影响我的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18544245/

相关文章:

c - 如何在 C 中一次性提供第一个输入文件的输出作为第二个输入文件?

c - Raw Socket Linux 发送/接收数据包

c - 从 ADC 样本到 C 语言的 .WAV 文件

c - 使用 getopt 时出错

c - 使用 C 中的 getopt_long 解析终端中的选项参数

c - main() 是 C 中的预定义函数吗?

c - 从字符串中读取个位数整数

perl - Perl Getopt::Long 中的未知选项

perl - 如何使用 Getopt::Long[::Descriptive] 处理由任意数字组成的选项?

c - 为什么结构选项数组在使用 getopt_long 时需要一个额外的虚拟条目