首页 > 解决方案 > C中的函数getopt与char * const *指针

问题描述

我想让第三个参数成为可能,如下所示:(文件名在任何位置,像这样)

program -a 3 <filename> -b 6
program -a 3 -b 6 <filename>

我怎样才能做到这一点getopt并将这个字符串保存在变量中file

int main(int argc, char *const *argv) {

   int a = 0;   int b = 0; int i = 0;  
   char *A;     char *B;
   char *file = NULL;

   int c;opterr = 0; 
  
   while ((c = getopt (argc, argv, "a:b:")) != -1)  {
     switch (c) {

       case 'a': a = 1; A = optarg; break;
       case 'b': b = 1; B = optarg; break;

       case '?': 
         if (optopt == 'c')             fprintf (stderr, "Option -%c requires an argument.", optopt);
         else if (isprint (optopt))     fprintf (stderr, "Unknown option `-%c'.", optopt);
         else                           fprintf (stderr,"Unknown option character `\\x%x'.",optopt);

       default: file = optarg; break; }}

   
   strcpy(&file,*(argv + i));

  return 0;
}

标签: cgetopt

解决方案


getopt函数期望所有参数都在所有非参数之前。所以处理program -a 3 <filename> -b 6是不可能的getopt。文件名必须在末尾,或者必须有一个与之关联的选项字母。

关于读取文件名,您将在 getopt 循环之后进行。该optind变量包含下一个尚未处理的参数的索引,因此可以减去该值argc并添加它以argv处理从 0 开始的剩余参数。

argc -= optind;
argv += optind;
file = argv[0];

推荐阅读