diff options
author | Thomas Voss <mail@thomasvoss.com> | 2023-12-31 01:29:14 +0100 |
---|---|---|
committer | Thomas Voss <mail@thomasvoss.com> | 2023-12-31 01:29:14 +0100 |
commit | 0c62349440c8231705d41a389d198434e45acb27 (patch) | |
tree | 098d6b25520d471c82ddcfaccd2758928937a29b | |
parent | 2fe098bb8baf4af6ceec0f13b25fb31e8b4a5982 (diff) |
Add binexists()
-rw-r--r-- | cbs.h | 30 |
1 files changed, 30 insertions, 0 deletions
@@ -160,6 +160,10 @@ typedef struct { size_t _len, _cap; } cmd_t; +/* Returns whether or not a binary of the given name exists in the users + environment as defined by $PATH. */ +static bool binexists(const char *); + /* cmdadd() adds the variadic string arguments to the given command. Alternatively, the cmdaddv() function adds the n strings pointed to by p to the given command. */ @@ -378,6 +382,32 @@ _next_powerof2(size_t n) return n + 1; } +bool +binexists(const char *name) +{ + char *p, *path; + + if (!(path = getenv("PATH"))) + diex("PATH environment variable not found"); + + if (!(path = strdup(path))) + die("strdup"); + p = strtok(path, ":"); + while (p) { + char buf[PATH_MAX]; + snprintf(buf, sizeof(buf), "%s/%s", p, name); + if (fexists(buf)) { + free(path); + return true; + } + + p = strtok(NULL, ":"); + } + + free(path); + return false; +} + void cmdaddv(cmd_t *cmd, char **xs, size_t n) { |