linux 中解析命令行参数 (getopt_long用法)

  1. #include<stdio.h>
  2. #include<getopt.h>
  3. char *l_opt_arg;
  4. char * const short_options= "nbl:" ;
  5. struct optionlong_options[]={
  6. {"name" ,0,NULL, 'n' },
  7. {"bf_name" ,0,NULL, 'b' },
  8. {"love" ,1,NULL, 'l' },
  9. {0,0,0,0},
  10. };
  11. int main( int argc, char *argv[])
  12. {
  13. int c;
  14. while ((c=getopt_long(argc,argv,short_options,long_options,NULL))!=-1)
  15. {
  16. switch (c)
  17. {
  18. case 'n' :
  19. printf("MynameisXL.\n" );
  20. break ;
  21. case 'b' :
  22. printf("HisnameisST.\n" );
  23. break ;
  24. case 'l' :
  25. l_opt_arg=optarg;
  26. printf("Ourloveis%s!\n" ,l_opt_arg);
  27. break ;
  28. }
  29. }
  30. return 0;
  31. }

[root@localhost liuxltest]# gcc -o getopt getopt.c

[root@localhost liuxltest]# ./getopt -n -b -l forever
My name is XL.
His name is ST.
Our love is forever!
[root@localhost liuxltest]#

[root@localhost liuxltest]# ./getopt -nb -l forever
My name is XL.
His name is ST.
Our love is forever!
[root@localhost liuxltest]# ./getopt -nbl forever
My name is XL.
His name is ST.
Our love is forever!

你可能感兴趣的:(C++,c,linux,gcc,C#)