tstgetopt.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <getopt.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. int
  6. main (int argc, char **argv)
  7. {
  8. static const struct option options[] =
  9. {
  10. {"required", required_argument, NULL, 'r'},
  11. {"optional", optional_argument, NULL, 'o'},
  12. {"none", no_argument, NULL, 'n'},
  13. {"color", no_argument, NULL, 'C'},
  14. {"colour", no_argument, NULL, 'C'},
  15. {NULL, 0, NULL, 0 }
  16. };
  17. int aflag = 0;
  18. int bflag = 0;
  19. char *cvalue = NULL;
  20. int Cflag = 0;
  21. int nflag = 0;
  22. int idx;
  23. int c;
  24. int result = 0;
  25. while ((c = getopt_long (argc, argv, "abc:", options, NULL)) >= 0)
  26. switch (c)
  27. {
  28. case 'a':
  29. aflag = 1;
  30. break;
  31. case 'b':
  32. bflag = 1;
  33. break;
  34. case 'c':
  35. cvalue = optarg;
  36. break;
  37. case 'C':
  38. ++Cflag;
  39. break;
  40. case '?':
  41. fputs ("Unknown option.\n", stderr);
  42. return 1;
  43. default:
  44. fprintf (stderr, "This should never happen!\n");
  45. return 1;
  46. case 'r':
  47. printf ("--required %s\n", optarg);
  48. result |= strcmp (optarg, "foobar") != 0;
  49. break;
  50. case 'o':
  51. printf ("--optional %s\n", optarg);
  52. result |= optarg == NULL || strcmp (optarg, "bazbug") != 0;
  53. break;
  54. case 'n':
  55. puts ("--none");
  56. nflag = 1;
  57. break;
  58. }
  59. printf ("aflag = %d, bflag = %d, cvalue = %s, Cflags = %d, nflag = %d\n",
  60. aflag, bflag, cvalue, Cflag, nflag);
  61. result |= (aflag != 1 || bflag != 1 || cvalue == NULL
  62. || strcmp (cvalue, "foobar") != 0 || Cflag != 3 || nflag != 1);
  63. for (idx = optind; idx < argc; idx++)
  64. printf ("Non-option argument %s\n", argv[idx]);
  65. result |= optind + 1 != argc || strcmp (argv[optind], "random") != 0;
  66. return result;
  67. }