diff --git a/arg.c b/arg.c index daba76b..f8d7de7 100644 --- a/arg.c +++ b/arg.c @@ -24,26 +24,22 @@ int main(int argc, char **argv) return EXIT_BAD_USAGE; } size_t flaglen = strlen(flag); - // Look for: --flag=val, --flag val, --flag, -f=val, -f val, or -f + int ischarflag = flag[0] == '-' && flaglen == 2; for (int i = 2; i < argc; i++) { char *arg = argv[i]; - if (strncmp(arg, flag, flaglen) != 0) continue; - if (arg[flaglen] == '\0') { // --flag ... - if (argv[i+1] && argv[i+1][0] != '-') // --flag - puts(argv[i+1]); // value of the flag - return EXIT_SUCCESS; - } else if (arg[flaglen] == '=') { // --flag=... - puts(&arg[flaglen+1]); - return EXIT_SUCCESS; + if (strncmp(arg, flag, flaglen) == 0) { + if (arg[flaglen] == '\0') { // --flag ... + if (argv[i+1] && argv[i+1][0] != '-') // --flag + puts(argv[i+1]); // value of the flag + return EXIT_SUCCESS; + } else if (arg[flaglen] == '=') { // --flag=... + puts(&arg[flaglen+1]); + return EXIT_SUCCESS; + } } - } - // If flag is single-character without a value, e.g. -f, look for it - // among other single character flags like -xfy. - if (flag[0] == '-' && flaglen == 2) { - for (int i = 2; i < argc; i++) { - char *arg = argv[i]; - if (arg[0] != '-' || arg[1] == '-') - continue; // skip foo and --foo + if (ischarflag && arg[0] == '-' && arg[1] != '-') { + // If flag is single-character without a value, e.g. -f, look + // for it among other single character flags like -xfy. for (char *c = &arg[1]; *c; c++) { if (*c == flag[1]) return EXIT_SUCCESS;