2022/07/18(月) [n年前の日記]
#1 [prog] getoptについて調べてる
C/C++で書かれているコマンドラインツール(?)の中で、コマンドラインオプションの解析をしたい。
ググってみた感じでは、getopt() や getopt_long() を使うと、多少は簡単に処理を書けるらしい。試してみた。
環境は Windows10 x64 21H2 + MSYS2 + MinGW64 + g++ 12.1.0。
_getopt_sample.cpp
コンパイル。
オプションを指定して実行してみる。
ヘルプメッセージは自分で列挙するしかないのだろうか…?
ググってみた感じでは、getopt() や getopt_long() を使うと、多少は簡単に処理を書けるらしい。試してみた。
環境は Windows10 x64 21H2 + MSYS2 + MinGW64 + g++ 12.1.0。
_getopt_sample.cpp
// getopt() sample.
#include <stdio.h>
#include <getopt.h>
void usage(char *name)
{
printf("Usage:\n");
printf(" %s -i IN.png -o OUT.png [-d N]\n", name);
printf("\n");
printf(" -i FILE, --input FILE input png image file.\n");
printf(" -o FILE, --output FILE output png image file.\n");
printf(" -d N, --dither N dither map. N = 2/4/8 (2x2, 4x4, 8x8)\n");
printf(" -h, --help display help message\n");
printf("\n");
}
int main(int argc, char **argv)
{
// parse option
char *infile = NULL;
char *outfile = NULL;
int dither = 4;
struct option longopts[] = {
{"help", no_argument, NULL, 'h'},
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"dither", required_argument, NULL, 'd'},
{0, 0, 0, 0}};
int opt;
int longindex;
while ((opt = getopt_long(argc, argv, "hi:o:d:", longopts, &longindex)) != -1)
{
switch (opt)
{
case 'i': // input image filename
infile = optarg;
break;
case 'o': // output image filename
outfile = optarg;
break;
case 'd': // dither map size, 2 or 4 or 8
switch (optarg[0])
{
case '2':
dither = 2;
break;
case '4':
dither = 4;
break;
case '8':
dither = 8;
break;
default:
printf("Error : Unknown dither mode = %s\n\n", optarg);
dither = -1;
break;
}
break;
case 'h': // help
usage(argv[0]);
return 0;
default:
break;
}
}
if (optind < argc)
{
for (; optind < argc; optind++)
printf("Unknown option : %s\n", argv[optind]);
usage(argv[0]);
return 1;
}
printf("infile : %s\n", infile);
printf("outfile : %s\n", outfile);
printf("dither : %d\n", dither);
if (infile == NULL || outfile == NULL || dither == -1)
{
usage(argv[0]);
return 1;
}
}
コンパイル。
g++ getopt_sample.cpp -o getopt_sample.exe
オプションを指定して実行してみる。
$ ./getopt_sample.exe --help Usage: D:\...\getopt_sample.exe -i IN.png -o OUT.png [-d N] -i FILE, --input FILE input png image file. -o FILE, --output FILE output png image file. -d N, --dither N dither map. N = 2/4/8 (2x2, 4x4, 8x8) -h, --help display help message $ ./getopt_sample.exe -i in.png -o out.png -d 2 infile : in.png outfile : out.png dither : 2
- getopt() を使う場合、#include <getopt.h> を記述。
- getopt() は、-a や -b 等の短いオプションを解析する際に使える。
- getopt_long() は、--input 等の長いオプションを解析する際に使える。
ヘルプメッセージは自分で列挙するしかないのだろうか…?
◎ 参考ページ。 :
[ ツッコむ ]
以上です。