(我不是在为这个投票。感谢@SteveFriedl。)
由于我从未听说过getopt() 并且一直为这种事情编写自己的解析器而感到内疚,请参阅下面的示例。
请注意,getopt 似乎只接受单字符参数名称。例如,您可以使用-f hello.text,但不能使用-filename hello.txt。 optind 和 optarg 是在 unistd.h 中声明的(呃)全局变量。
(请注意,通过argv[] 自己实现这一点并不难,这可能会产生更灵活的解决方案。)
Shamelessly lifted from Geeks for Geeks:
// copied from https://www.geeksforgeeks.org/getopt-function-in-c-to-parse-command-line-arguments/
// Program to illustrate the getopt()
// function in C
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int opt;
// put ':' in the starting of the
// string so that program can
//distinguish between '?' and ':'
while((opt = getopt(argc, argv, “:if:lrx”)) != -1)
{
switch(opt)
{
case ‘i’:
case ‘l’:
case ‘r’:
printf(“option: %c\n”, opt);
break;
case ‘f’:
printf(“filename: %s\n”, optarg);
break;
case ‘:’:
printf(“option needs a value\n”);
break;
case ‘?’:
printf(“unknown option: %c\n”, optopt);
break;
}
}
// optind is for the extra arguments
// which are not parsed
for(; optind < argc; optind++){
printf(“extra arguments: %s\n”, argv[optind]);
}
return 0;
}
那么,
./a.out -i -f file.txt -lr -x 'hero'
生产
option: i
filename: file.txt
option: l
option: r
unknown option: x
extra arguments: hero