getopt_long.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* Getopt tests */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <getopt.h>
  6. int main (int argc, char **argv)
  7. {
  8. int c;
  9. int digit_optind = 0;
  10. while (1)
  11. {
  12. int this_option_optind = optind ? optind : 1;
  13. int option_index = 0;
  14. static struct option long_options[] =
  15. {
  16. {"add", 1, 0, 0},
  17. {"append", 0, 0, 0},
  18. {"delete", 1, 0, 0},
  19. {"verbose", 0, 0, 0},
  20. {"create", 0, 0, 0},
  21. {"file", 1, 0, 0},
  22. {0, 0, 0, 0}
  23. };
  24. c = getopt_long (argc, argv, "abc:d:0123456789",
  25. long_options, &option_index);
  26. if (c == EOF)
  27. break;
  28. switch (c)
  29. {
  30. case 0:
  31. printf ("option %s", long_options[option_index].name);
  32. if (optarg)
  33. printf (" with arg %s", optarg);
  34. printf ("\n");
  35. break;
  36. case '0':
  37. case '1':
  38. case '2':
  39. case '3':
  40. case '4':
  41. case '5':
  42. case '6':
  43. case '7':
  44. case '8':
  45. case '9':
  46. if (digit_optind != 0 && digit_optind != this_option_optind)
  47. printf ("digits occur in two different argv-elements.\n");
  48. digit_optind = this_option_optind;
  49. printf ("option %c\n", c);
  50. break;
  51. case 'a':
  52. printf ("option a\n");
  53. break;
  54. case 'b':
  55. printf ("option b\n");
  56. break;
  57. case 'c':
  58. printf ("option c with value `%s'\n", optarg);
  59. break;
  60. case 'd':
  61. printf ("option d with value `%s'\n", optarg);
  62. break;
  63. case '?':
  64. break;
  65. default:
  66. printf ("?? getopt returned character code 0%o ??\n", c);
  67. }
  68. }
  69. if (optind < argc)
  70. {
  71. printf ("non-option ARGV-elements: ");
  72. while (optind < argc)
  73. printf ("%s ", argv[optind++]);
  74. printf ("\n");
  75. }
  76. exit (0);
  77. }