Link Search Menu Expand Document

サマリ:base64のソースコードリーディング初回

base64を読もう①

勉強になるかわからないけど、base64のコードを読んでみようと思い立ちました。 最後まできちんと理解できるように頑張ります。

多分、取り留めもないメモになるのだろうけれども..。

base64.c

まずはstaticな変数を先に確認しておくことにします。

static struct option const long_options[] =
{
  {"decode", no_argument, 0, 'd'},
  {"wrap", required_argument, 0, 'w'},
  {"ignore-garbage", no_argument, 0, 'i'},

  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {NULL, 0, NULL, 0}
};

ところで、struct optionとは何者でしょうか。その答えはgetopt.hにありました。

/* Describe the long-named options requested by the application.
   The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
   of `struct option' terminated by an element containing a name which is
   zero.

   The field `has_arg' is:
   no_argument		(or 0) if the option does not take an argument,
   required_argument	(or 1) if the option requires an argument,
   optional_argument 	(or 2) if the option takes an optional argument.

   If the field `flag' is not NULL, it points to a variable that is set
   to the value given in the field `val' when the option is found, but
   left unchanged if the option is not found.

   To have a long-named option do something other than set an `int' to
   a compiled-in constant, such as set a value from `optarg', set the
   option's `flag' field to zero and its `val' field to a nonzero
   value (the equivalent single-letter option character, if there is
   one).  For long options that have a zero `flag' field, `getopt'
   returns the contents of the `val' field.  */

struct option
{
#if defined (__STDC__) && __STDC__
  const char *name;
#else
  char *name;
#endif
  /* has_arg can't be an enum because some compilers complain about
     type mismatches in all the code that assumes it is an int.  */
  int has_arg;
  int *flag;
  int val;
};

/* Names for the values of the `has_arg' field of `struct option'.  */

#define	no_argument		0
#define required_argument	1
#define optional_argument	2

nameにlong_nameを、has_argに引数が存在するか、引数自体がオプショナルかといった情報をセットする。flagvalの使い方と関係性が今ひとつ理解できていないので、読み切ってからの宿題にする。

まずはここまで。

理解できたこと

  • optionは引数ととるかどうかなどを細かく規定できる
  • optionの規定はgetopt.h

宿題

  • struct optionflagvalを理解する

今日はここまで。 良い天気になりますように。

眠い。


Back to top

Copyright © 2021- Akira Otaka All rights reserved.