5

このソース コードを本で見ました。

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


int main(int argc, char *argv[])
{
    char *delivery = "";
    int thick = 0;
    int count = 0;
    char ch;

    while ((ch = getopt(argc, argv, "d: t")) != EOF)
        switch(ch)
        {
            case 'd':
                delivery = optarg;
                break;

            case 't':
                thick = 1;
                break;

            default:
                fprintf(stderr, "Unknown option: '%s'\n", optarg);
                return 1;
        }

        argc -= optind;
        argv += optind;

        if (thick)
            puts("Thick Crust.");

        if (delivery[0])
            printf("To be deliverd %s\n", delivery);

        puts("Ingredients: ");

        for (count = 0; count < argc; count++)
            puts(argv[count]);

    return 0;
}

以下を除くソース全体を理解できます。

argc -= optind;
argv += optind;

argc と argv が何であるかは知っていますが、この 2 行で何が起こっているのか、「optind」とは何かを説明してください。

ありがとうございました。

4

4 に答える 4

4

このgetoptライブラリには、コマンド ライン引数の解析に役立ついくつかの関数が用意されています。

それを呼び出すgetoptと、可変数の引数を「食べる」(コマンドラインオプションのタイプに応じて)。「食べられた」引数の数は、optindグローバル変数で示されます。

あなたのコードは調整され、消費されたばかりの引数をジャンプするためargvargc使用されます。optind

于 2012-08-16T12:28:50.850 に答える
3

it's a global variable used by getopt.

From the manual:

The getopt() function parses the command-line arguments. Its arguments argc and argv are the argument count and array as passed to the main() function on program invocation.

The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1.

That code just updates argc and argv to point to the rest of the arguments (- options skipped).

于 2012-08-16T12:25:12.303 に答える
2

方法について:

optind は、このコードの後に​​無視される argv の要素の数です。

argc -= optind; // reduces the argument number by optind 
argv += optind; // changes the pointer to go optind items after the first one

argc (カウント) は optind によって削減されます

それに応じて、argv の最初の要素へのポインターがアップグレードされます。

理由について:

Karolyの答えを見てください。

于 2012-08-16T12:26:21.550 に答える
0

このコードの実行中に、 ./executable_file:name -d some_argument として実行できます

getopt が呼び出されると、コマンド ラインに書かれている内容のスキャンが開始されます。argc = 3, argv[0]=./executable_file:name argv[1]=-d argv[2]=some_argument . getopt は、次の argv[2] のインデックスである optind = 2 の時点でオプション d を取得します。したがって、optind+argv は argv[2] を指します。

一般に、optind は次のインデックスを持ちます。

于 2014-12-04T12:32:49.460 に答える