logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

getopt_long.c (923B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 202405L
  5. #include <getopt.h> // getopt_long
  6. #include <stdio.h> // puts
  7. #include <stdlib.h> // abort
  8. int
  9. main(int argc, char *argv[])
  10. {
  11. int optidx = 0;
  12. char *file = NULL;
  13. // clang-format off
  14. static struct option opts[] = {
  15. {"help", no_argument, NULL, 'h'},
  16. {"file", required_argument, NULL, 'f'},
  17. {"iso-8601", optional_argument, NULL, 'I'},
  18. {0, 0, 0, 0}
  19. };
  20. // clang-format on
  21. for(int c = -1; (c = getopt_long(argc, argv, ":hf:I::", opts, &optidx)) != -1;)
  22. {
  23. switch(c)
  24. {
  25. case 'h':
  26. puts("Help!");
  27. return 1;
  28. break;
  29. case 'f':
  30. file = optarg;
  31. break;
  32. case 'I':
  33. if(optarg) puts(optarg);
  34. return 2;
  35. break;
  36. default:
  37. abort();
  38. }
  39. }
  40. if(file) puts(file);
  41. return 0;
  42. }