2015年4月30日木曜日

コマンドライン引数を取得するCのサンプルコード


自分用メモ。

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

int main(int argc, char** argv) {

  int aopt = 0;
  int bopt = 0;
  int copt = 0;
  char *bparam = NULL;
  char *cparam = NULL;

  struct option longopts[] = {
      {"aaa", no_argument,       NULL, 'a'},
      {"bbb", required_argument, NULL, 'b'},
      {"ccc", optional_argument, NULL, 'c'},
      {0, 0, 0, 0}
  };

  int opt = 0;
  int longindex = 0;
  while ((opt = getopt_long(argc, argv, "ab:c::", longopts, &longindex)) != -1) {
    printf("index: %d, option: %s\n", longindex, longopts[longindex].name);
    switch (opt) {
    case 'a':
      aopt = 1;
      break;
    case 'b':
      bopt = 1;
      bparam = optarg;
      break;
    case 'c':
      copt = 1;
      cparam = optarg;
      break;
    default:
      printf("error %c \n", opt);
      exit(1);
    }
  }

  printf("--aaa(-a) = %d\n", aopt);
  printf("--bbb(-b) = %d: %s\n", bopt, bparam);
  printf("--ccc(-c) = %d: %s\n", copt, cparam);

  int i;
  for(i = optind; i < argc; i++) {
    printf("arg: %s \n", argv[i]);
  }
}


$ ./a.out --aaa --bbb="hoge" --ccc="piyo"
index: 0, option: aaa
index: 1, option: bbb
index: 2, option: ccc
--aaa(-a) = 1
--bbb(-b) = 1: hoge
--ccc(-c) = 1: piyo


--をつけたロングオプションの場合は、=を省略できるが、
--cccは引数をオプション扱いにしているので
最後のpiyoはロングオプションの引数扱いにはならない点が注意が必要である。
$ ./a.out --bbb "hoge" --ccc "piyo"
index: 1, option: bbb
index: 2, option: ccc
--aaa(-a) = 0
--bbb(-b) = 1: hoge
--ccc(-c) = 1: (null)
arg: piyo