有没有更好的方法来查找文件的名称,而不仅仅是循环遍历argv []寻找不是标志的参数 - ?
在这种情况下,可以按任何顺序输入标志(因此optind不会有帮助)。
即:
/ 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 } }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 } }最满意答案
从getopt()的手册页,
默认情况下,getopt()会在扫描时置换argv的内容,以便最终所有非选择都在最后。
因此,给出选项和非选项参数的顺序无关紧要。
使用getopt()来处理选项及其参数(如果有的话)。 之后,检查optind的值。
正如手册页所说,
变量optind是argv要处理的下一个元素的索引。
在您的命令中,似乎只有一个非选项参数。 如果在正确处理optind所有选项后就是这种情况,则optind必须等于argc-1 。
另外,在你给出的optstring , s后面有冒号。 这意味着如果选项-s存在,它必须有一个参数。
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]);注意:可以按任何顺序提供选项,但可能不会将一个选项的参数作为另一个选项的参数。
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 in argv.
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.
更多推荐
发布评论