I'm trying to use the getopt function for the first time only I'm having problems with arguments that aren't flags. For instance, in my code when a unknown argument is given I want to use it as a input file. When I run this with only a file name it is not printed, if I first use a flag, any flag, then I can print it.
How can I fix this?
Thanks
#include <stdio.h>
#include <getopt.h>
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{"algorithm", required_argument, 0, 'a'},
{0, 0, 0, 0}
};
int main(int argc, char *argv[]) {
int c;
int option_index = 0;
while(42) {
c = getopt_long(argc, argv, "hi:o:a:", long_options,
&option_index);
if(c == -1)
break;
switch(c) {
case 'h': /* --help */
printf("--help flag\n");
break;
case 'i': /* --input */
printf("--input flag\n");
break;
case 'o': /* --output */
printf("--output flag\n");
break;
case 'a': /* --algorithm */
printf("--algorithm flag \n");
break;
default: /* ??? */
fprintf(stderr, "Invalid option");
return 1;
}
if(optind < argc) {
printf("other arguments: ");
while(optind < argc) {
printf ("%s ", argv[optind]);
optind++;
}
printf("\n");
}
}
return 0;
}