0

getopt 関数を使用して解析する方法はありますか:

./prog -L -U

以下と同じ:

./prog -LU    

これは私の試みです(動作していません):

while ((c = getopt(argc, argv, "LU")) != -1) {
    switch (c) {
    case 'L':
        // L catch
        break;
    case 'U':
        // U catch
        break;
    default:
        return;
    }
}

この単純な例では 2 つのパラメーターしかありませんが、私のプロジェクトでは 6 つのパラメーターのすべての組み合わせが必要です。例: -Lor -LURGHXor -LU -RG -Hetc.getopt()これを処理できますか? それとも、それを行うには複雑なパーサーを作成する必要がありますか?

4

3 に答える 3

2

中括弧がないことを除けば、あなたのコードは私にとってはうまくいきます:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv) {
    int c;
    while ((c = getopt(argc, argv, "LU")) != -1) {
        switch (c) {
        case 'L':
            // L catch
            printf("L\n");
            break;
        case 'U':
            // U catch
            printf("U\n");
            break;
        default:
            break;
        }
    }
    return 0;
}
$ ./a.out -LU
L
U
$ ./a.out -L
L
$
于 2013-03-11T01:26:12.507 に答える
2

それはあなたが望むように正確に動作します:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char** argv) 
{
    int c;

    while ((c = getopt(argc, argv, "LU")) != -1) {
        switch (c) {
        case 'L':
            puts("'L' option");
            break;
        case 'U':
            // U catch
            puts("'U' option");
            break;
        default:
            puts("shouldn't get here");
            break;
        }
    }

    return 0;
}

そしてそれをテストします:

precor@burrbar:~$ gcc -o test test.c
precor@burrbar:~$ ./test -LU
'L' option
'U' option
precor@burrbar:~$ ./test -L -U
'L' option
'U' option

getopt()は、 POSIX "Utiltiy Syntax Guidelines"に従うPOSIX 標準関数であり、次の内容が含まれます。

ガイドライン 5: オプション引数のないオプションは、1 つの区切り文字「-」の後ろにグループ化されている場合に受け入れられる必要があります。

于 2013-03-11T01:24:15.570 に答える
2

getopt それを処理できるようですそしてそれはします

以下は、このプログラムがさまざまな引数の組み合わせで出力する内容を示すいくつかの例です。

% testopt
aflag = 0, bflag = 0, cvalue = (null)

% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)

% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)
于 2013-03-11T01:16:44.890 に答える