getopt_long () is what you are looking for, here is a simple use case:
static const struct option opts[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {"message", required_argument, 0, 'm'}, {0, 0, 0, 0 } }; int optidx; char c; while ((c = getopt_long(argc, argv, "vhm:", opts, &optidx)) != -1) { switch (c) { case 'v': print_version(); break; case 'h': help(argv[0]); break; case 'm': printf("%s\n", optarg); break; case '?': help(argv[0]); return 1; default: if (optopt == 'c') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint(optopt)) fprintf(stderr, "Unknown option -%c.\n", optopt); else fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt); return 1; } } while (optind < argc) { ; ++optind; }
user1551592
source share