2 * arg - A simple C program by Bruce Hill for parsing command line arguments
3 * Licensed under the MIT license (see LICENSE for details).
5 * Example: arg --foo a b --foo=blah --baz -xyz
6 * - Prints "blah" and exits with success
7 * Example: arg --nope a b --foo=blah --baz -xyz
8 * - Prints nothing and exits with failure
9 * Example: arg -y a b --foo=blah --baz -xyz
10 * - Prints nothing and exits with success
15 const int EXIT_SUCCESS = 0;
16 const int EXIT_NO_MATCH = 1;
17 const int EXIT_BAD_USAGE = -1;
19 int main(int argc, char **argv)
23 fprintf(stderr, "Usage: arg <flag> ...\n");
24 return EXIT_BAD_USAGE;
26 size_t flaglen = strlen(flag);
27 int ischarflag = flag[0] == '-' && flaglen == 2;
28 for (int i = 2; i < argc; i++) {
30 if (strncmp(arg, flag, flaglen) == 0) {
31 if (arg[flaglen] == '\0') { // --flag ...
32 if (argv[i+1] && argv[i+1][0] != '-') // --flag <value>
33 puts(argv[i+1]); // value of the flag
35 } else if (arg[flaglen] == '=') { // --flag=<value>
36 puts(&arg[flaglen+1]);
40 if (ischarflag && arg[0] == '-' && arg[1] != '-') {
41 // If flag is single-character, e.g. -f, look for it among other
42 // single character flags like -xfy.
43 for (char *c = &arg[1]; *c; c++) {