Reputation: 77
I'm writing a program which needs to be able to parse command line arguments, and I would like to use getopt. I have no issues with getting it to work with the regular arguments, however I need it to be able to pick up an argument that is not specified with a flag. For example if I ran: ./prog -a a1 -b b2 foo
I would need to be able to get a1,a2 and foo. Right now it handles everything but the unspecified argument. Here is what I have:
while((command = getopt(argc, argv, "a:b:c:")) != -1){
switch(command){
case('a'):
input = fopen(optarg, "r");
if(input == NULL){
printf("Error opening file, exiting\n");
exit( -1 );
}
break;
case('b'):
output = fopen(optarg, "r");
if(output == NULL){
printf("Error opening file, exiting\n");
exit( -1 );
}
break;
case('c'):
keyword = optarg;
break;
case('?'):
if((optopt == 'a') || (optopt == 'b') || (optopt == 'c')){
fprintf(stderr, "Error, no argument specified for -%c\n", optopt);
exit( -1 );
} else
extra = optarg; // This is how I thought I needed to do it
break;
default:
fprintf(stderr,"Error in getopt");
break;
}// switch
} // while
Thanks!
Upvotes: 1
Views: 728
Reputation: 409166
After the loop, the optind
variable will be the index to the next non-option argument.
So do e.g.
if (optind < argc)
{
printf("Have extra arguments: ");
for (int i = optind; i < argc; ++i)
printf("%s ", argv[i]);
printf("\n");
}
to list all non-option arguments.
Upvotes: 2