コマンドライン入力を解析するためのコードを書いています。getopt_long の使用方法は次のとおりです。
int c = 0;
static struct option long_options[] =
{
{"mode", 1, NULL, 'm'},
{"help", 0, NULL, 'h'},
{0, 0, 0, 0}
};
while ((c = getopt_long(argc, argv, "mh", long_options, NULL))!=-1)
{
switch(c)
{
case 0:
{
cerr<<"Usage: ./program <-m> <-h>"<<endl;
exit(1);
break;
}
case 'm':
{
if (!strcmp(optarg, "small"))
mode = 0;
else if (!strcmp(optarg, "medium"))
mode = 1;
else if (!strcmp(optarg, "large"))
mode = 2;
else{
cerr<<"Invalid mode "<<optarg<<endl;
exit(1);
}
break;
}
case 'h':
{
cerr<<"See man page for help."<<endl;
exit(0);
}
default:
{
cerr<<"Unrecognized argument!"<<endl;
exit(1);
}
}
}
私は以下をテストしました:
1)
./program
プログラムは while ループに入りません。変数 c は -1 であることが検査されます。
2)
./program -h
うまくいきます。
3)
./program -m small
プログラムは、strcmp() からセグメンテーション フォールトをスローして終了します。
助けてくれてありがとう。