我在一本书上看到这个源代码:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *delivery = "";
int thick = 0;
int count = 0;
char ch;
while ((ch = getopt(argc, argv, "d: t")) != EOF)
switch(ch)
{
case 'd':
delivery = optarg;
break;
case 't':
thick = 1;
break;
default:
fprintf(stderr, "Unknown option: '%s'\n", optarg);
return 1;
}
argc -= optind;
argv += optind;
if (thick)
puts("Thick Crust.");
if (delivery[0])
printf("To be deliverd %s\n", delivery);
puts("Ingredients: ");
for (count = 0; count < argc; count++)
puts(argv[count]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我可以理解整个来源,除了:
argc -= optind;
argv += optind;
Run Code Online (Sandbox Code Playgroud)
我知道 argc 和 argv 是什么,但是这两行中它们发生了什么,什么是“optind” 请解释一下。
谢谢你。
该getopt库提供了几个函数来帮助解析命令行参数。
当您调用getopt它“吃”可变数量的参数时(取决于命令行选项的类型);“吃掉”的参数数量在optind全局变量中指示。
您的代码会调整argv并argc使用optind来跳转刚刚消耗的参数。