// getopt() sample. // // Last updated: <2022/07/18 21:06:55 +0900> #include #include 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; } }