C 这些代码的作用是什么?
我在一本书中看到了这段源代码:C 这些代码的作用是什么?,c,C,我在一本书中看到了这段源代码: #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(c
#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;
}
我知道什么是argc和argv,但在这两行中它们发生了什么,什么是“optind”
解释一下
谢谢。这是一个全局变量,由
getopt
使用
从手册中:
函数的作用是:解析命令行参数。它的论点
argc和argv是传递给main()的参数计数和数组
程序调用上的函数
变量optind是要处理的下一个元素的索引
在argv。系统将该值初始化为1
该代码只是更新了argc和argv,以指向其余的参数(
-
选项已跳过)。关于如何操作:
optind是在此代码之后将被忽略的argv元素数:
argc -= optind; // reduces the argument number by optind
argv += optind; // changes the pointer to go optind items after the first one
argc(计数)由optind减少
并且指向argv的第一个元素的指针也相应升级
关于原因:
参见Karoly的答案。getopt库提供了几个函数来帮助解析命令行参数 当您调用
getopt
时,它“吃”了数量可变的参数(取决于命令行选项的类型);参数“eat”的数量在optind
全局变量中表示
您的代码使用
optind
来调整argv
和argc
以跳转刚刚使用的参数。运行此代码时,您可以将其作为./executable\u file:name-d some\u参数执行
当调用getopt时,它开始扫描命令行中写入的内容。argc=3,argv[0]=./可执行文件:名称argv[1]=-d argv[2]=某个参数。
getopt将获得optind=2时的选项d,该选项是下一个参数的索引,即argv[2]。
因此optind+argv将指向argv[2]
一般情况下,optind将具有下一个的索引。或者,如果您安装了正确的手册页,
man optind将为您提供相同的信息。
argc -= optind; // reduces the argument number by optind
argv += optind; // changes the pointer to go optind items after the first one