subopt.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* Parsing of Suboptions Example
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <unistd.h>
  17. int do_all;
  18. const char *type;
  19. int read_size;
  20. int write_size;
  21. int read_only;
  22. enum
  23. {
  24. RO_OPTION = 0,
  25. RW_OPTION,
  26. READ_SIZE_OPTION,
  27. WRITE_SIZE_OPTION,
  28. THE_END
  29. };
  30. const char *mount_opts[] =
  31. {
  32. [RO_OPTION] = "ro",
  33. [RW_OPTION] = "rw",
  34. [READ_SIZE_OPTION] = "rsize",
  35. [WRITE_SIZE_OPTION] = "wsize",
  36. [THE_END] = NULL
  37. };
  38. int
  39. main (int argc, char **argv)
  40. {
  41. char *subopts, *value;
  42. int opt;
  43. while ((opt = getopt (argc, argv, "at:o:")) != -1)
  44. switch (opt)
  45. {
  46. case 'a':
  47. do_all = 1;
  48. break;
  49. case 't':
  50. type = optarg;
  51. break;
  52. case 'o':
  53. subopts = optarg;
  54. while (*subopts != '\0')
  55. switch (getsubopt (&subopts, mount_opts, &value))
  56. {
  57. case RO_OPTION:
  58. read_only = 1;
  59. break;
  60. case RW_OPTION:
  61. read_only = 0;
  62. break;
  63. case READ_SIZE_OPTION:
  64. if (value == NULL)
  65. abort ();
  66. read_size = atoi (value);
  67. break;
  68. case WRITE_SIZE_OPTION:
  69. if (value == NULL)
  70. abort ();
  71. write_size = atoi (value);
  72. break;
  73. default:
  74. /* Unknown suboption. */
  75. printf ("Unknown suboption `%s'\n", value);
  76. break;
  77. }
  78. break;
  79. default:
  80. abort ();
  81. }
  82. /* Do the real work. */
  83. return 0;
  84. }