2

getopt()短いオプションに期待するように動作していません。

例: パラメータが欠落している以下のプログラムを呼び出す:

有効なケース:testopt -d dir -a action -b build

エラーケース:testopt -d -a action -b build

エラーメッセージのオペランドが見つからないことを期待していたので、これはエラーをスローしませんでした-d

  • これは既知のバグですか?
  • もしそうなら、利用可能な標準的な修正はありますか?

私のコード:

#include <unistd.h>
/* testopt.c                       */
/* Test program for testing getopt */
int main(int argc, char **argv)
{
    int chr;
    while ( ( chr = getopt(argc, argv, ":d:a:b:") ) != -1 )
    {
            switch(chr)
            {
                    case 'a':
                            printf("Got a...\n");
                            break;
                    case 'b':
                            printf("Got b...\n");
                            break;
                    case 'd':
                            printf("Got d...\n");
                            break;
                    case ':':
                            printf("Missing operand for %c\n", optopt);
                            break;
                    case '?':
                            printf("Unknown option %c\n", optopt);
                            break;
            }
    }
    printf("execution over\n");
    return 0;
}
4

3 に答える 3

4

getopt()thinks-aは の引数で-dあり、オプションではありません。

試してみてくださいtestopt -a action -b build -d- 引数の欠落について文句を言うべきです。

-d有効な値を持つオプション(および他のすべてのオプション)を確認する必要がありoptargます-最初にダッシュがないもの。

于 2008-11-05T09:35:28.127 に答える
0

マニュアルページによると、引数の欠落を示すためにgetopt()returnを作成するには、オプション文字列をコロンで開始する必要があります。':'デフォルトは を返しているようです'?'

于 2008-11-05T09:16:20.023 に答える
0

上記のコードは、Red Hat で gcc 3.4.5 を使用して、私にとっては問題なく動作します。

$ ./a.out -d test
Got d...
execution over

$ ./a.out -d
Missing operand for d
execution over

あなたの環境は?

更新: わかりました、qrdl はスポットです。getopt() がそのように機能するのはなぜですか?

于 2008-11-05T10:26:38.460 に答える