logo

utils-std

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

which.c (1529B)


  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 200809L
  5. #include <limits.h> // PATH_MAX
  6. #include <stdbool.h>
  7. #include <stdio.h> // fprintf
  8. #include <stdlib.h> // getenv
  9. #include <string.h> // strtok
  10. #include <unistd.h> // access, getopt
  11. int
  12. main(int argc, char *argv[])
  13. {
  14. bool opt_a = false, opt_s = false;
  15. int missing = 0;
  16. char *path = getenv("PATH");
  17. if(path == NULL)
  18. {
  19. fputs("which: error: $PATH environment unset", stderr);
  20. return 1;
  21. }
  22. for(int c = -1; (c = getopt(argc, argv, "as")) != -1;)
  23. {
  24. switch(c)
  25. {
  26. case 'a':
  27. opt_a = true;
  28. break;
  29. case 's':
  30. opt_s = true;
  31. break;
  32. case '?':
  33. fprintf(stderr, "which: error: Unrecognised option: '-%c'\n", optopt);
  34. return 1;
  35. default:
  36. abort();
  37. }
  38. }
  39. argc -= optind;
  40. argv += optind;
  41. if(argc <= 0) return 1;
  42. for(int i = 0; i < argc; i++)
  43. {
  44. char *cmd = argv[i];
  45. bool found = false;
  46. char *state = NULL;
  47. char *hay = strdup(path);
  48. if(hay == NULL)
  49. {
  50. perror("which: error: Failed duplicating $PATH");
  51. return 1;
  52. }
  53. for(char *tok = strtok_r(hay, ":", &state); tok != NULL; tok = strtok_r(NULL, ":", &state))
  54. {
  55. char buf[PATH_MAX] = "";
  56. snprintf(buf, PATH_MAX, "%s/%s", tok, cmd);
  57. if(access(buf, X_OK) == 0)
  58. {
  59. if(!opt_s) puts(buf);
  60. found = true;
  61. if(!opt_a) break;
  62. }
  63. }
  64. if(!found) missing++;
  65. free(hay);
  66. }
  67. return missing;
  68. }