From 389d0b2badf4a9cd33ed91a928b91475fb0d0a4f Mon Sep 17 00:00:00 2001 From: Joseph Hunkeler Date: Fri, 5 Jun 2020 17:00:51 -0400 Subject: Move find.c functions into fs.c --- lib/fs.c | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) (limited to 'lib/fs.c') diff --git a/lib/fs.c b/lib/fs.c index 0cdda41..98a18e6 100644 --- a/lib/fs.c +++ b/lib/fs.c @@ -764,4 +764,74 @@ char **file_readlines(const char *filename, size_t start, size_t limit, ReaderFn fclose(fp); } return result; -} \ No newline at end of file +} + +/** + * Determine whether `pattern` is present within a file + * @param filename + * @param pattern + * @return 0=found, 1=not found, -1=OS error + */ +int find_in_file(const char *filename, const char *pattern) { + int result = 1; // default "not found" + + FILE *fp = fopen(filename, "rb"); + if (!fp) { + return -1; + } + + long int file_len = get_file_size(filename); + if (file_len == -1) { + fclose(fp); + return -1; + } + char *buffer = (char *)calloc((size_t) file_len, sizeof(char)); + if (!buffer) { + fclose(fp); + return -1; + } + size_t pattern_len = strlen(pattern); + + fread(buffer, (size_t) file_len, sizeof(char), fp); + fclose(fp); + + for (size_t i = 0; i < (size_t) file_len; i++) { + if (memcmp(&buffer[i], pattern, pattern_len) == 0) { + result = 0; // found + break; + } + } + free(buffer); + return result; +} + +/** + * Get the full path of a shell command + * @param program + * @return success=absolute path to program, failure=NULL + */ +char *find_executable(const char *program) { + int found = 0; + char *result = NULL; + char *env_path = NULL; + env_path = getenv("PATH"); + if (!env_path) { + return NULL; + } + char **search_paths = split(env_path, ":"); + + char buf[PATH_MAX]; + for (int i = 0; search_paths[i] != NULL; i++) { + sprintf(buf, "%s%c%s", search_paths[i], DIRSEP, program); + if (access(buf, F_OK | X_OK) == 0) { + found = 1; + break; + } + memset(buf, '\0', sizeof(buf)); + } + if (found) { + result = strdup(buf); + } + split_free(search_paths); + return result; +} -- cgit