如何获得不以“ - ”或“ - ”开头的参数

时间:2010-04-15 19:50:08

标签: c command-line command-line-arguments

我有一个需要命令行参数的程序:

./my_program -m256M -tm -t some_other_file

“some_other_file”参数没有绑定到-t(-t它只是另一个功能)所以我不能把它作为任何标志的optarg,我也不能认为它是列表中的最后一个参数

我该怎么做?

由于

2 个答案:

答案 0 :(得分:4)

getopt(_long)以这种方式置换argv中的参数,当没有参数时它理解为left(当它返回-1时)所有解析的参数都在未解析的参数之前。所以你可以使用全局变量optind,它将getopt设置为argv中第一个参数的索引,它没有解析它以便找到你的程序的任何其他参数。假设除了getopt已知的参数之外还有一个这样的some_other_file,伪代码将是:

while ((ret = getopt_long(argc, argv, ...)) != -1) {
    /* do something with ret */
}
if (optind >= argc) {
    /* error, no some_other_file */
} else {
    file_str = argv[optind];
    /* do something else */
}

这个方法可以扩展为任意数量的无连字符参数,这些参数保证全部保留在argv中,以便它们被传递给程序,并且所有这些参数都在getopt理解的任何参数之后,所以很简单从optind到argc-1的循环可用于列出这些未解析的参数。

答案 1 :(得分:2)

这就是你想要的吗?

int main(int argc, char* argv[]){
//...
int i=1;

for(; i<argc; i++){
   if(argv[i][0] != '-'){
      printf("%s\n", argv[i]);
      //break; //if you dont want all arguments that don't start with - or --
   }
}

//...
return 0;
}

  

$ gcc dsad.c&amp;&amp; ./a.out -m256M -tm -t some_other_file more_file
  some_other_file
  more_file
  $ gcc dsad.c&amp;&amp; ./a.out -m256M -tm -t
  $ gcc dsad.c&amp;&amp; ./a.out -m256M -tm -t some_other_file - 另一个   some_other_file