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

MyMemoWiki

「C getopt long」の版間の差分

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
(ページの作成:「==C getopt_long== 2つのdashで始まる、いわゆる長いoptionを受け付ける。 #include <unistd.h> #define _GNU_SOURCE #include <getopt.h> int getopt_…」)
 
 
(同じ利用者による、間の1版が非表示)
1行目: 1行目:
==C getopt_long==
+
==[[C getopt_long]]==
 
2つのdashで始まる、いわゆる長いoptionを受け付ける。
 
2つのdashで始まる、いわゆる長いoptionを受け付ける。
  #include <unistd.h>
+
  #include &lt;unistd.h&gt;
  #define _GNU_SOURCE
+
  #define _GNU_SOU[[R]]CE
  #include <getopt.h>
+
  #include &lt;getopt.h&gt;
 
  int getopt_long(int argc, char * const argv[],
 
  int getopt_long(int argc, char * const argv[],
 
                   const char *optstring,
 
                   const char *optstring,
29行目: 29行目:
 
|}
 
|}
  
  #include <stdio.h>
+
  #include &lt;stdio.h&gt;
  #include <unistd.h>
+
  #include &lt;unistd.h&gt;
  #define _GNU_SOURCE#include <getopt.h>
+
  #define _GNU_SOU[[R]]CE#include &lt;getopt.h&gt;
 
   
 
   
 
  int main(int argc, char *argv[])
 
  int main(int argc, char *argv[])

2020年2月16日 (日) 04:23時点における最新版

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

この本からの覚書。