aboutsummaryrefslogtreecommitdiff
path: root/lib/fs.c
diff options
context:
space:
mode:
authorJoseph Hunkeler <jhunkeler@gmail.com>2020-06-05 17:00:51 -0400
committerJoseph Hunkeler <jhunkeler@gmail.com>2020-06-05 17:00:51 -0400
commit389d0b2badf4a9cd33ed91a928b91475fb0d0a4f (patch)
treee7118bd11dc3647784d529643eafd0a28f85c244 /lib/fs.c
parentf76fed00c9c9289b354e7f8dd6f14ea699ef16a2 (diff)
downloadspmc-389d0b2badf4a9cd33ed91a928b91475fb0d0a4f.tar.gz
Move find.c functions into fs.c
Diffstat (limited to 'lib/fs.c')
-rw-r--r--lib/fs.c72
1 files changed, 71 insertions, 1 deletions
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;
+}