为什么我的optind总是大于argc?

liken218 2003-10-20 04:36:31
我写了个命令,命令的格式是test <file>
在main里我取到的optind为什么总是argc?

能给我讲讲optind和argc吗?
...全文
442 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
liken218 2003-10-20
  • 打赏
  • 举报
回复
如果是那就怪了,在内核中iptables-save.c的代码如下
int main(int argc, char *argv[])
{
const char *tablename = NULL;
int c;

program_name = "iptables-save";
program_version = NETFILTER_VERSION;

#ifdef NO_SHARED_LIBS
init_extensions();
#endif

while ((c = getopt_long(argc, argv, "bc", options, NULL)) != -1) {
switch (c) {
case 'b':
binary = 1;
break;

case 'c':
counters = 1;
break;

case 't':
/* Select specific table. */
tablename = optarg;
break;
case 'd':
do_output(tablename);
exit(0);
}
}


if (optind < argc) {
fprintf(stderr, "Unknown arguments found on commandline");
exit(1);
}

return !do_output(tablename);
}

就是说这个指令执行的时候,只要它后面加上选项则在if (optind < argc) 处就一定执行出错!
liken218 2003-10-20
  • 打赏
  • 举报
回复
那如果你的指令支持选项option
如 ./a.out -t myfile
则输出应该是
argc=3 optind=2
是吗?
elife 2003-10-20
  • 打赏
  • 举报
回复
你是不是这点弄错了: argv[0]是程序路径, 因此test <file>
argc=2 optind=1
elife 2003-10-20
  • 打赏
  • 举报
回复
optind
Name
optind -- external variable used in getopt()
Synopsis
extern int optind;


Description
optind holds the current index of the array argr[], which contains the command line options being parsed by getopt.

我的测试程序是对的啊
extern int optind;

int main(int argc)
{
int x = 10, y;

printf("argc=%d optind=%d\n", argc, optind);
}

./a.out 1 2
argc=3 optind=1

23,110

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧