Is there a better way to find the name of a file than just looping through argv[] looking for an argument that isn't a flag - ?
In this case, the flags can be entered in any order (so optind isn't going to help).
ie:
/program -p file.txt -s
/program -p -s file.txt -b
/program file.txt -p -s -a
int main (int argc, char *argv[]){
char option;
const char *optstring;
optstring = "rs:pih";
while ((option = getopt(argc, argv, optstring)) != EOF) {
switch (option) {
case 'r':
//do something
break;
case 's':
//etc etc
}
}
From the man page of
getopt()
,So the order in which the options and non-option arguments are given doesn't matter.
Use
getopt()
to take care of the options and their arguments (if any). After that, check the value ofoptind
.As the man page says,
In your command, it seems that there is only one non-option argument. If that's the case after all the options have been correctly processed,
optind
must be equal toargc-1
.Also, in the
optstring
you have given, there is colon followings
. That means if the option-s
is there, it must have an argument.Note: The options may be provided in any order but the argument of one option may not be given as the argument of another.