1
1

More than 5 years have passed since last update.

getopt

Last updated at Posted at 2015-01-15

ヘッダ <unistd.h>


int getopt(int argc, char *const argv, const char *options)

argvに格納されたオプション・リストから次の文字を取得し、その1文字を返す。
取得する文字がなくなった場合-1を返す。その場合、optind と argc を比較し、オプションの終端に達したかチェックすること。

options には利用するオプション文字を指定しておく。
options に指定しておいた文字列が argv に存在しない場合'?'が返る。

コロン(:)が付けられたオプション文字には引数を必要とする。(-p name)
オプションに引数を要する場合、optarg にそのオプションの引数が格納される。

2つのコロン(::)が付けられたオプション文字は任意の指定を許可する(GNU 拡張)

int opterr

不正なオプションが指定された場合 非ゼロの値が設定され、標準エラー出力にメッセージを出力する。
明示的にゼロを設定するとgetopt()はエラーメッセージを出力しないが、'?'文字はエラーを指し示している。

int optopt

不正なオプションが指定された場合にその文字を格納する。

int optind

argv の次のインデックスを指す。初期値として1が与えられる。
getopt()は一回の呼び出しにより、すべてのオプションを走査する。
この値をチェックすることで残りのオプションを調べられる。

char* optarg

オプションに引数を要する場合、そのオプションへの引数を手当てする。

サンプル

オプションに引数を要するオプション

int main(int argc, char* argv[])
{
    int c = getopt(argc, argv, "a:");

    if(argc==1) {
        fprintf(stderr, "require option: %c\n", optopt);
        return 1;
    }
    if(c=='?' || optind!=3) {
        return 1; /* エラーメッセージは自動的に手当される */
    }

    const char* a = optarg;
    fopen(a, "w");
    ....
    return 0;
}

オプション -a -b -c や -abc を許可する。("abc"は順不同)
同時に指定されるとマズイことになるオプションに気をつける。


int main(int argc, char* argv[])
{
    int c;
    while( (c=getopt(argc, argv, "abc")) != -1) { ... }
    return 0;
}

GNU C Library -getopt
http://www.gnu.org/software/libc/manual/html_node/Getopt.html

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1