LoginSignup
0
1

More than 5 years have passed since last update.

[C言語] getopt

Last updated at Posted at 2017-05-23

C言語でコマンドライン引数をパースする getopt を毎回忘れるので、備忘録です。

ショートオプションはPOSIXに準拠しているが、ロングオプションはGNU拡張のようです。

getopt_long() and getopt_long_only():
These functions are GNU extensions.

コード

#include <stdio.h>
#include <getopt.h>

void
usage()
{
    fprintf(stderr,
        "p: port number"
        );
}

void
cmdline_parse(int argc, char **argv)
{
    int port = 34400; // global or paramterに変更

    int ret = 0;
    while ( (ret = getopt(argc, argv, "hp:")) != -1 )
    {
        if (ret == -1)
            break;

        switch (ret) {
        case 'p':
            port = atoi(optarg);
            break;
        case 'h':
            usage();
            exit(1);
            break;

        case '?': // unknown option
        default:
            break;
        }
    }
}

オプション

getopt の第3引数にオプションを指定する。
1. 引数から値を取る場合は アルファベット:
2. 引数から値を取っても取らなくても良い場合は アルファベット::
3. 非オプション文字列を検出するとただちにプログラムを終了する場合は +アルファベット
4. 非オプション文字は文字コード1の文字として扱われる -アルファベット

※2と3と4は、試してないです。

参照ページ

http://www.fireproject.jp/feature/c-language/basic-library/getargs.html
http://www.fireproject.jp/feature/c-language/basic-library/getopt_long.html

0
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
0
1