Skip to content

Instantly share code, notes, and snippets.

@silverjam
Created February 14, 2014 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silverjam/9010797 to your computer and use it in GitHub Desktop.
Save silverjam/9010797 to your computer and use it in GitHub Desktop.
#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