-
Notifications
You must be signed in to change notification settings - Fork 0
/
which.c
67 lines (56 loc) · 1.15 KB
/
which.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "main.h"
/**
* _which - locates and returns a path to an executable, if it exists
* @exec: name of executable to locate
*
* Return: path of executable or NULL if it doesn't exist within $PATH
*/
char *_which(char *exec)
{
char *executable;
char *path, *curr;
list_t *path_list, *temp;
struct stat st;
executable = strcpycat("/", exec);
path = _getenv("PATH");
path_list = make_env(path);
temp = path_list;
while (temp)
{
curr = strcpycat(temp->str, executable);
if (stat(curr, &st) == 0)
{
free(executable);
free_list(path_list);
return (curr);
}
free(curr);
temp = temp->next;
}
free(executable);
free_list(path_list);
return (NULL);
}
/**
* make_env - creates linked list of all paths in $PATH
* @str: environmental variable string (ex. "...:/usr/bin:/usr:/bin:...")
*
* Return: Pointer to new linked list
*/
list_t *make_env(char *str)
{
list_t *env = NULL;
char *buffer = strdup(str);
char *nodeStr;
int i = 0;
nodeStr = strtok(buffer, ":");
add_node_end(&env, nodeStr);
while (nodeStr != NULL)
{
nodeStr = strtok(NULL, ":");
add_node_end(&env, nodeStr);
i++;
}
free(buffer);
return (env);
}