getopt的转变OPTARG [英] Getopt shift optarg

查看:365
本文介绍了getopt的转变OPTARG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用我的程序是这样的:

I need to call my program like this:

./program hello -r foo bar

我带你好出来的argv [1],但我有超​​值的酒吧麻烦,也应该我改变R:别的东西。

I take hello out of argv[1], but i am having trouble with value bar, also should i change "r:" to something else?

while((c = getopt(argc, argv, "r:")) != -1){
   switch(i){
   ...
   case 'r':
     var_foo = optarg;
     //shell like argument shift here?
     var_bar = optarg;
     break;
...}

我知道我可以通过的argv做到这一点,但有一种用getopt的类似的方式做到这一点是在bash?

I know I could do this with passing through argv, but is there a way to do it with getopt similar way as in bash?

感谢。

推荐答案

不在眼里的选项参数 getopt的。相反,GNU getopt的重新排列的位置参数,以便在处理结束时,你有的argv [3] 是你好和的argv [4] 是栏。基本上,你就大功告成了getopting的时候,你还有位置参数 [OPTIND,ARGC)来处理:

bar is not an option argument in the eyes of getopt. Rather, GNU getopt rearranges the positional arguments so that at the end of the processing, you have argv[3] being "hello" and argv[4] being "bar". Basically, when you're done getopting, you still have positional arguments [optind, argc) to process:

int main(int argc, char * argv[])
{
     {
         int c;
         while ((c = getopt(argc, argv, ...)) != -1) { /* ... */ }
     }

     for (int i = optind; i != argc; ++i)
     {
         // have positional argument argv[i]
     }
}

这篇关于getopt的转变OPTARG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆