I am writing the following code for a command called fp
which exists within a framework for handling these commands that's already in place. I'm fairly new to C and I'm trying to parse some the arguments for this command using getopt_long(). Currently the arguments don't do anything other than print the arguments name and increment a variable to see how many of them were recognized by getopt. Here is the relevant code:
//Define options for getopt_long
int opt = 0;
static struct option long_options[] = {
{"watchdog_timer", optional_argument, NULL, 'w'},
{"emergency_hold", optional_argument, NULL, 'e'},
{"braking_wait", optional_argument, NULL, 'r'},
{"pusher_timeout", optional_argument, NULL, 't'},
{"pusher_state_accel_min", optional_argument, NULL, 'a'},
{"pusher_state_min_timer", optional_argument, NULL, 'm'},
{"pusher_distance_min", optional_argument, NULL, 'd'},
{"primary_braking_accel_min", optional_argument, NULL, 'b'},
{NULL, 0, NULL, 0}
};
//Parse arguments
int long_index = 0;
int test = 0;
while ((opt = getopt_long(argc, argv, "wertamdb",
long_options, &long_index )) != -1){
switch (opt){
case 'w':
note("w");
test++;
break;
case 'e':
note("e");
test++;
break;
case 'r':
note("r");
test++;
break;
case 't':
note("t");
test++;
break;
case 'a':
note("a");
test++;
break;
case 'm':
note("m");
test++;
break;
case 'd':
note("d");
test++;
break;
case 'b':
note("b");
test++;
break;
default:
return snprintf(outbuf, outbufc, "Invalid Argument(s)\n");
}
}
return snprintf(outbuf, outbufc, "Args = %d", test);
I then run the code that allows me to enter this command and this is the output that I get (any line beginning with fp
is input, every other line is output:
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
[NOTE] 101
[NOTE] e
[NOTE] 114
[NOTE] r
[NOTE] 116
[NOTE] t
[NOTE] 97
[NOTE] a
[NOTE] 109
[NOTE] m
[NOTE] 100
[NOTE] d
[NOTE] 98
[NOTE] b
Args = 7
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
[NOTE] 109
[NOTE] m
[NOTE] 100
[NOTE] d
[NOTE] 98
[NOTE] b
Args = 3
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
[NOTE] 100
[NOTE] d
[NOTE] 98
[NOTE] b
Args = 2
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
[NOTE] 98
[NOTE] b
Args = 1
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
Args = 0
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
Args = 0
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
Args = 0
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
Args = 0
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
Args = 0
fp -w 1 -e 1 -r 1 -t 1 -a 1 -m 1 -d 1 -b 1
Args = 0
For some reason, getopt seems to recognize fewer and fewer of the of the arguments the more times the command is entered. I also double checked to make sure all of the arguments are coming through in argv. Any idea what may cause this? Like I said I haven't worked much with C and I expect this to be something simple I'm missing.