<getopt.h> (POSIX/GNU) provides getopt for short options (-v, -o file) and getopt_long for long options (--verbose, --output=file). It handles argument parsing, optarg tracking, and stops at the first non-option argument or --.
Use it to parse command-line arguments portably instead of handling argv manually.
This example parses both short and long options, handling argument requirements.
// compile: gcc -o getoptexample getoptexample.c // run: ./getoptexample -v --output=out.txt file1.txt // description: parse short and long options with arguments #include <getopt.h> #include <stdio.h> int main(int argc, char* argv[]) { int verbose = 0; const char* outfile = "a.out"; int c; struct option opts[] = { {"verbose", no_argument, NULL, 'v'}, {"output", required_argument, NULL, 'o'}, {0, 0, 0, 0} }; while ((c = getopt_long(argc, argv, "vo:", opts, NULL)) != -1) { switch (c) { case 'v': verbose = 1; break; case 'o': outfile = optarg; break; case '?': return 1; } } printf("verbose=%d output=%s\n", verbose, outfile); for (int i = optind; i < argc; i++) printf(" input: %s\n", argv[i]); return 0; }
Short option parsing:
getopt(argc, argv, optstring): parse options (GNU extension, POSIX)optstring format: "ab:c::" means -a (no arg), -b (required arg), -c (optional arg)? on error, : on missing arg, or -1 when doneLong option parsing:
getopt_long(argc, argv, optstring, longopts, &longindex): parse long optionsstruct option { const char *name; int has_arg; int *flag; int val; };{0, 0, 0, 0}--verbose=value or --verbose valueArgument flags (for struct option.has_arg):
no_argument: option takes no argumentrequired_argument: option requires argumentoptional_argument: argument is optionalGlobal variables (set by getopt):
optarg: pointer to argument for current option (NULL if none)optind: index in argv of next element to process (initialize to 1)opterr: if 1 (default), print error messages to stderr on unknown optionsoptopt: option character that caused error (unknown option or missing arg)Usage pattern:
while ((opt = getopt_long(argc, argv, "abc:d::", longopts, &idx)) != -1) { switch (opt) { case 'a': /* handle -a */ break; case 'c': /* optarg has argument */ break; case 'd': /* optional arg in optarg */ break; case 0: /* long option, check longopts[idx] */ break; case '?': /* unknown option or missing arg */ break; } } // argv[optind] is first non-option argument