| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

C getopt long

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

C getopt_long

2つのdashで始まる、いわゆる長いoptionを受け付ける。

  1. #include <unistd.h>
  2. #define _GNU_SOURCE
  3. #include <getopt.h>
  4. int getopt_long(int argc, char * const argv[],
  5. const char *optstring,
  6. 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が見つかったときに、返す値
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #define _GNU_SOURCE#include <getopt.h>
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7. struct option lngopt[] = {
  8. {"optionA", 0, NULL, 0},
  9. {"optionB", 1, NULL, 0},
  10. {"optionC", 2, NULL, 0},
  11. {0, 0, 0, 0}
  12. };
  13. int opt;
  14. int option_index = 0;
  15. while((opt = getopt_long(argc, argv, "bc:a", lngopt, &option_index)) != -1){
  16. if (opt == 0) {
  17. printf("option %s",lngopt[option_index].name);
  18. if (optarg){
  19. printf(" with arg %s" ,optarg);
  20. }
  21. printf("\n");
  22. }
  23. }
  24. }
  1. # ./a.out --optionA --optionB=bbbb --optionC=cccc
  2. option optionA
  3. option optionB with arg bbbb
  4. option optionC with arg cccc

この本からの覚書。