int getopt(int argc, char * const argv[], const char *optstring);
获取命令行信息,并读取命令行中的选项;
(命令行组成或许存在盲区,这是某位博主的这是他的博客)
Option就是选项,Option argument是参数:

每读取到一个选项,会返回一个int整型,这个整型不是选项位置,而是选项对应的ASCII码值;
这个函数附带了一些全局变量,这些全局变量中的optarg会对应着解析到的某个选项对应的参数;
./program -a -b argb --c=argc -d -e arge foo bar
#include
#include
#include
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "ab:c::de")) != -1) {
switch (opt) {
case 'a':
printf("Option -a\n");
break;
case 'b':
printf("Option -b with argument '%s'\n", optarg);
break;
case 'c':
// 注意:如果选项c后面有参数,它必须紧跟在c后面
if (optarg) {
printf("Option -c with argument '%s'\n", optarg);
} else {
printf("Option -c (no argument)\n");
}
break;
case 'd':
printf("Option -d\n");
break;
case 'e':
// 注意:选项e后面的'arge'不是选项e的参数,而是非选项参数
printf("Option -e\n");
break;
case '?':
// getopt会打印错误消息,但我们也可以在这里添加自定义处理
fprintf(stderr, "Unknown option: %c\n", optopt);
exit(EXIT_FAILURE);
default:
abort(); // 其他情况下,应该不会发生
}
}
// optind现在是第一个非选项参数的索引
// 在这个例子中,它是"foo"的索引
for (int i = optind; i < argc; i++) {
printf("Non-option argument: %s\n", argv[i]);
}
return 0;
}
Option -a
Option -b with argument 'argb'
Option -c (no argument) // 因为-c后面没有直接跟随参数
Option -d
Option -e
Non-option argument: foo
Non-option argument: bar
注意,尽管命令行中包含–c=argc这样的长选项格式,但getopt只处理短选项(单个字符的选项)。如果你需要处理长选项,可能需要使用getopt_long函数或手动解析它们。