I would like to make a third argument possible, as shown here: (filename at any position like this)
program -a 3 <filename> -b 6
program -a 3 -b 6 <filename>
How can I do this with getopt and save this string in the variable file?
int main(int argc, char *const *argv) {
int a = 0; int b = 0; int i = 0;
char *A; char *B;
char *file = NULL;
int c;opterr = 0;
while ((c = getopt (argc, argv, "a:b:")) != -1) {
switch (c) {
case 'a': a = 1; A = optarg; break;
case 'b': b = 1; B = optarg; break;
case '?':
if (optopt == 'c') fprintf (stderr, "Option -%c requires an argument.", optopt);
else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.", optopt);
else fprintf (stderr,"Unknown option character `\\x%x'.",optopt);
default: file = optarg; break; }}
strcpy(&file,*(argv + i));
return 0;
}
The getopt function expects all arguments to be before all non-arguments. So processing program -a 3 <filename> -b 6 is not possible with getopt. Either the filename has to be at the end or there has to be an option letter associated with it.
Regarding reading the filename, you would do it after the getopt loop. The optind variable contains the index of the next argument not yet processed, so can subtract this value from argc and add it to argv to process the remaining arguments starting from 0.
argc -= optind;
argv += optind;
file = argv[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With