在C中通过getopt解析命令行参数

在C中通过getopt解析命令行参数,c,getopt,C,Getopt,正在尝试分析命令行参数,然后将其打印出来。。。我如何使用getopt实现这一点 我需要getopt为以后的代码开发打下基础 #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main (int argc, char **argv) { char *cvalue = NULL; int c;

正在尝试分析命令行参数,然后将其打印出来。。。我如何使用getopt实现这一点

我需要getopt为以后的代码开发打下基础

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int main (int argc, char **argv)
 {
     char *cvalue = NULL;
     int c;

     while ((c = getopt (argc, argv, "n1n2n3n4c:")) != -1)              
         switch (c):
             case n1:
             case n2:
             case n3:
             case n4:
                 for(int i=0; i<argc;i++)
                 {
                     printf("Option: d%", argv[i]);
                 }
             default: break;


     printf ("n1flag = %d, n2flag = %d, n3flag = %d, n4flag = %d cvalue = %s\n",
              n1flag, n2flag, n3flag, n4flag, cvalue);

     for (index = optind; index < argc; index++)
         printf ("Non-option argument %s\n", argv[index]);

     return 0;
 }
#包括
#包括
#包括
#包括
int main(int argc,字符**argv)
{
char*cvalue=NULL;
INTC;
而((c=getopt(argc,argv,“n1n2n3n4c:”)!=-1)
开关(c):
案例n1:
案例n2:
案例n3:
案例n4:

对于(int i=0;igetopt使用单个字符作为选项,因此不能定义n1、n2、n3、n4等。相反,您需要为它们指定唯一的单个字符


请参阅getopt手册页:

您还可以查看。作为Brian答案的补充,如果您想要-nX选项,您将使用需要参数的单个-n选项,并验证您收到的参数(例如,当您的选项为“n”时,optarg为“5”,但-n5无效)否则,考虑使用GETOPTTHYONGYONE——一个为X窗口系统所需的样式所创建的GNU函数(例如:“显示:X.Y”将是选项-显示,和X.Y将是选项参数)。如果这仍然对你不起作用,也许你可以创建自己的参数分析器。