c/c++语言开发共享Getopt转移optarg

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

./program hello -r foo bar 

我从argv [1]中打招呼,但我在价值栏上遇到麻烦,我也应该将“r:”更改为其他内容吗?

 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类似的方式做到这一点?

谢谢。

    getopt眼中, bar不是一个选项参数。 相反,GNU getopt 重新排列位置参数,以便在处理结束时, argv[3]为“hello”, argv[4]为“bar”。 基本上,当你完成getopting时,你仍然有位置参数[optind, argc)来处理:

     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] } } 

    这取决于你是否使用GNU getopt() ,如果你是,是否在环境中设置了POSIXLY_CORRECT

    经典(意思是非GNU getopt() ),所有选项参数必须在任何非选项(文件名)参数之前。 这意味着你有四个非选项参数。

    如果你有GNU getopt()并且没有设置POSIXLY_CORRECT ,那么它将在命令行的任何地方处理选项参数。 在这种情况下,你有一个选项, -r使用参数值foo ,以及两个非选项参数( hellobar )。

    要让Classic getopt()识别-r ,你必须要求第一个(非选项)参数,然后才调用getopt()

     int main(int argc, char **argv) { char *cmd = argv[1]; int opt; argv[1] = argv[0]; argv++; argc--; while ((opt = getopt(argv, argc, "r:")) != EOF) { switch (opt) { case 'r': ...capture optarg... break; default: ...report error.... break; } } for (int i = optind; i < argc; i++) process_non_option_argument(cmd, argv[i]); return(0); } 

    如果启用它,GNU getopt也可以返回非选项参数。 除此之外, bar参数将始终被视为非选项参数。

      以上就是c/c++开发分享Getopt转移optarg相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/544958.html

      (0)
      上一篇 2021年1月9日
      下一篇 2021年1月9日

      精彩推荐