命令行处理库 - getopt的 [英] command line processing library - getopt
问题描述
有人可以帮助我的getopt函数?
Can someone help me with the getopt function?
当我做主要如下:
char *argv1[] = {"testexec","-?"};
char *argv2[] = {"testexec","-m","arg1"};
int cOption;
/* test for -? */
setvbuf(stdout,(char*)NULL,_IONBF,0);
printf("\n argv1 ");
while (( cOption = getopt (2, argv1, "m:t:n:fs?")) != -1) {
switch(cOption){
case 'm':
printf("\n -m Arg : %s \n",optarg);
break;
case '?':
printf("\n -? Arg ");
break;
case 'n':
printf("\n -n Arg : %s \n",optarg);
break;
}
}
printf("\n argv2 ");
while (( cOption = getopt (3, argv2, "m:t:n:fs?")) != -1) {
switch(cOption){
case 'm':
printf("\n -m Arg : %s \n",optarg);
break;
case '?':
printf("\n -? Arg : %s \n",optarg);
break;
case 'n':
printf("\n -n Arg : %s \n",optarg);
break;
}
}
我上运行RHEL3此code,它使用旧的libc版本。我不知道哪一个是准确的。
I'm running this code on rhel3 which uses old libc version. I don't know which one to be exact.
现在,问题是getopt的不与argv2工作的第二次。
但是,如果我注释掉与argv1第一getopt的呼叫,它的工作原理。
Now the problem is getopt doesn't work the second time with argv2. But if I comment out the first getopt call with argv1 , it works.
谁能告诉我我在做什么错在这里?
Can someone tell me what am I doing wrong here?
推荐答案
argv1和2必须以0结尾:
argv1 and 2 must end in 0:
char* argv1[] = {"par1", "par2", 0};
的修改的:OK,我读了getopt的手册页,我发现这一点:
Edit: OK, I read the getopt man page and I found this:
变量OPTIND是argv中要处理的下一个元素的索引。系统初始化该值
1。调用者可以将其重置为1重启相同的argv扫描,扫描或一个新的参数向量时。
The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector.
所以,在getopt的在两个电话之间做出OPTIND = 1使它正常工作。
So, making optind=1 between the two calls at getopt makes it work as expected.
这篇关于命令行处理库 - getopt的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!