はじめての C

[Learning GNU C]

13-3. argp の機能を さらに使う

これは 長めの プログラムで 4つの グローバル変数を 使い 自分の プログラムに 関する 情報を 保持する。

Example 13-3. better_argp.c

#include <stdlib.h>
#include <argp.h>

const char *argp_program_version = "simple_argp 0.1";
const char *argp_program_bug_address =
"";

static char doc[] =
"short program to show the use of argp\nThis program does little";

static char args_doc[] = "ARG1 ARG2";

/* initialise an argp_option struct with the options we expect */
static struct argp_option options[] =
{
{"verbose", 'v', 0, 0, "Produce verbose output"},
{"output", '0', "FILE", 0, "Output to FILE"},
{ 0 }
};

/* Used by 'main' to communicate with 'parse_opt'. */
struct arguments {
char *args[2]; /* ARG1 & ARG2 */
int silent, verbose;
char *output_file;
};

/* Parse a single option */
static error_t
parse_opt(int key, char *arg, struct argp_state *state) {
/* Get the INPUT argument from 'argp_parse', which we
know is a pointer to our arguments structure. */
struct arguments *arguments = state->input;

switch (key) {
case 'q': case 's':
arguments->silent = 1;
break;
case 'v':
arguments->verbose = 1;
break;
case 'o':
arguments->output_file = arg;
break;
case ARGP_KEY_ARG:
if (state->arg_num >= 2)
/* Too many arguments.*/
argp_usage (state);
arguments->args[state->arg_num] = arg;
break;
case ARGP_KEY_END:
if (state->arg_num < 2)
/* Not enough arguments. */
argp_usage (state);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}

/* Our argp parser */
static struct argp argp = {options, parse_opt, args_doc, doc};

int
main(int argc, char **argv)
{
struct arguments arguments;

/* Default values */
arguments.silent = 0;
arguments.verbose = 0;
arguments.output_file = "-";

/* Parse out arguments: every option seen by 'parse_opt' will
be reflected in 'arguments'. */
argp_parse (&argp, argc, argv, 0, 0, &arguments);

printf("ARG1 = %s\nARG2 = %s\nOUTPUT_FILE = %s\n"
"VERBOSE = %s\nSILENT = %s\n",
arguments.args[0], arguments.args[1],
arguments.output_file,
arguments.verbose ? "yes" : "no",
arguments.silent ? "yes" : "no");

exit(0);
}

これって とても 簡単だね?

13-4. 環境変数 environment variable

省略。 その 4つの 引数形式の 使い方と 環境変数を 理解する 別の 方法とを 説明、小さな 例題を 示す。



argp は 標準ライブラリ getopt の 機能を 拡張し エラー処理も 備えた スグレモノ。
$ less /usr/include/argp.h
例題の better_argp.c は もちろん コンパイルして 実行できます。
$ cc -o better_argp better_argp.c
$ ./better_argp --help
Usage: better_argp [OPTION ...] ARG1 ARG2
short program to show the use of argp
This program does little

-O. --output=FILE Output to FILE
-v, --verbose Produce verbose output
-?, --help Give this help list
--usage Give a short usage message
-V, --version Print program version

Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.

Report bugs to .
$ ./better_argp lets showtime
ARG1 = lets
ARG2 = showtime
OUTPUT_FILE = -
VERBOSE = no
SILENT = no
$

も一つ 使い方が わかってない ...oLr