From 0c62349440c8231705d41a389d198434e45acb27 Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Sun, 31 Dec 2023 01:29:14 +0100 Subject: Add binexists() --- cbs.h | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/cbs.h b/cbs.h index d12a97d..47f0031 100644 --- a/cbs.h +++ b/cbs.h @@ -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) { -- cgit v1.2.3