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; return EXIT_BAD_USAGE;
} }
size_t flaglen = strlen(flag); 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++) { for (int i = 2; i < argc; i++) {
char *arg = argv[i]; char *arg = argv[i];
if (strncmp(arg, flag, flaglen) != 0) continue; if (strncmp(arg, flag, flaglen) == 0) {
if (arg[flaglen] == '\0') { // --flag ... if (arg[flaglen] == '\0') { // --flag ...
if (argv[i+1] && argv[i+1][0] != '-') // --flag <value> if (argv[i+1] && argv[i+1][0] != '-') // --flag <value>
puts(argv[i+1]); // value of the flag puts(argv[i+1]); // value of the flag
return EXIT_SUCCESS; return EXIT_SUCCESS;
} else if (arg[flaglen] == '=') { // --flag=... } else if (arg[flaglen] == '=') { // --flag=...
puts(&arg[flaglen+1]); puts(&arg[flaglen+1]);
return EXIT_SUCCESS; return EXIT_SUCCESS;
}
} }
} if (ischarflag && arg[0] == '-' && arg[1] != '-') {
// If flag is single-character without a value, e.g. -f, look for it // If flag is single-character without a value, e.g. -f, look
// among other single character flags like -xfy. // 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
for (char *c = &arg[1]; *c; c++) { for (char *c = &arg[1]; *c; c++) {
if (*c == flag[1]) if (*c == flag[1])
return EXIT_SUCCESS; return EXIT_SUCCESS;