C getopt long
ナビゲーションに移動
検索に移動
C getopt_long
2つのdashで始まる、いわゆる長いoptionを受け付ける。
- #include <unistd.h>
- #define _GNU_SOURCE
- #include <getopt.h>
- int getopt_long(int argc, char * const argv[],
- const char *optstring,
- const struct option *longopts, int *longindex);
- longopts は struct option の要素からなる配列の、先頭要素へのpointer
- 配列の最後の要素は、全て 0 で埋められていなければならない。
option 構造体
member | 説明 |
---|---|
name | 長いoptionの名前 |
has_arg | optionが引数を取るかどうかを指定。取らない:0、必ず取る:1、省略可能:2 |
flag | NULLを指定した場合、optionが見つかると、valで指定した値を返す。NULL以外を指定した場合、optionが見つかると、0を返し、flagが示す変数に、valの値を書き込む |
val | optionが見つかったときに、返す値 |
- #include <stdio.h>
- #include <unistd.h>
- #define _GNU_SOURCE#include <getopt.h>
- int main(int argc, char *argv[])
- {
- struct option lngopt[] = {
- {"optionA", 0, NULL, 0},
- {"optionB", 1, NULL, 0},
- {"optionC", 2, NULL, 0},
- {0, 0, 0, 0}
- };
- int opt;
- int option_index = 0;
- while((opt = getopt_long(argc, argv, "bc:a", lngopt, &option_index)) != -1){
- if (opt == 0) {
- printf("option %s",lngopt[option_index].name);
- if (optarg){
- printf(" with arg %s" ,optarg);
- }
- printf("\n");
- }
- }
- }
- # ./a.out --optionA --optionB=bbbb --optionC=cccc
- option optionA
- option optionB with arg bbbb
- option optionC with arg cccc
この本からの覚書。
© 2006 矢木浩人