Edited down the code a little bit.

This commit is contained in:
Bruce Hill 2019-02-15 02:05:50 -08:00
parent 1d395a814a
commit e48f973be9

30
arg.c
View File

@ -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 <value>
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 <value>
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;