Created
February 14, 2014 22:30
-
-
Save silverjam/9010797 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <stdarg.h> | |
#include <string.h> | |
#include <strings.h> | |
#include <unistd.h> | |
#define COUNTOF(arr) (sizeof(arr) / sizeof(arr[0])) | |
char* pathsearch(const char* program) | |
{ | |
char buffer[4096]; | |
char* path = strdup(getenv("PATH")); | |
char* path_start = path; | |
int path_length = strlen(path); | |
char* colon = NULL; | |
char* found_path = NULL; | |
while (path - path_start < path_length) | |
{ | |
colon = strchr(path, ':'); | |
if (colon != NULL) | |
*colon = '\0'; | |
buffer[0] = '\0'; | |
if (strlen(path) != 0) | |
snprintf(buffer, COUNTOF(buffer), "%s/%s", path, program); | |
if (colon != NULL) { | |
path = colon + 1; | |
} else { | |
break; | |
} | |
if (buffer[0] == '\0') | |
continue; | |
if(access(buffer, X_OK) == 0) { | |
found_path = buffer; | |
break; | |
} | |
} | |
free(path_start); | |
return found_path == NULL ? found_path : strdup(found_path); | |
} | |
int main() | |
{ | |
char* fullpath = pathsearch("ls"); | |
printf("%s\n", fullpath == 0 ? "<none>" : fullpath); | |
free(fullpath); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment