问题
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
}
}
回答1:
From the man page of getopt()
,
By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end.
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 of optind
.
As the man page says,
The variable
optind
is the index of the next element to be processed inargv
.
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 to argc-1
.
Also, in the optstring
you have given, there is colon following s
. That means if the option -s
is there, it must have an argument.
while ((option = getopt(argc, argv, optstring)) != EOF) {
switch (option) {
case 'r':
//do something
break;
case 's':
//etc etc
}
}
//Now get the non-option argument
if(optind != argc-1)
{
fprintf(stderr, "Invalid number of arguments.");
return 1;
}
fprintf(stdout, "\nNon-option argument: %s", argv[optind]);
Note: The options may be provided in any order but the argument of one option may not be given as the argument of another.
来源:https://stackoverflow.com/questions/46210580/c-using-a-file-argument-with-getopt