getopt()会在最后一次执行时将argv变量进行排序,将参数(“d:t”)中提到的变量排序到最前面。这样后面的argc、argv变量通过optind计算就会非常清楚,经过遍历getopt()之后的参数就是没有被指定顺序的。
#include<stdio.h>
#include<unistd.h>
void print_arg(int argc, char *argv[])
{
int i = 0;
printf("----START PRINT----\n");
for (i = 0; i< argc; i++)
{
printf("%d\t%s\n", i, argv[i]);
}
}
int main(int argc, char *argv[])
{
char *delivery = "";
int thick = 0;
int count = 0;
char ch;
while((ch = <span style="color:#CC33CC;">getopt(argc, argv, "d:t")</span>) != EOF)
{
print_arg(argc, argv);
switch(ch)
{
case 'd':
delivery = optarg;
break;
case 't':
thick = 1;
break;
default:
fprintf(stderr, "Unknown option: '%s'\n", optarg);
return 1;
}
}
print_arg(argc, argv);
argc -= optind;
argv += optind;
printf("OPTIND:%d\n", optind);
print_arg(argc, argv);
return 0;
}
程序执行的结果:
x_think@swork0:~$ gcc p152.c -o p152 && ./p152 -d now Anchovies Pineapple -t
----START PRINT----
0 ./p152
1 -d
2 now
3 Anchovies
4 Pineapple
5 -t
----START PRINT----
0 ./p152
1 -d
2 now
3 Anchovies
4 Pineapple
5 -t
----START PRINT----
0 ./p152
1 -d
2 now
3 -t
4 Anchovies
5 Pineapple
OPTIND:4
----START PRINT----
0 Anchovies
1 Pineapple
----START PRINT----
0 ./p152
1 -d
2 now
3 Anchovies
4 Pineapple
5 -t
----START PRINT----
0 ./p152
1 -d
2 now
3 Anchovies
4 Pineapple
5 -t
----START PRINT----
0 ./p152
1 -d
2 now
3 -t
4 Anchovies
5 Pineapple
OPTIND:4
----START PRINT----
0 Anchovies
1 Pineapple
代码片段来自 Head First C, by David Griffiths and Dawn Griffiths. Copyright © 2012 David Griffiths and Dawn Griffiths. All rights reserved. ISBN: 978-1-449-39991-7 引用时有删节