forked from yazgiraldoa/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_path.c
47 lines (40 loc) · 959 Bytes
/
find_path.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
#include "shell.h"
/**
* find_path - function that searches the PATH in user environment,
* tokenize the PATH, concatenates the command to every tokenized path
* and checks if the command exists.
* @tokens: An array of pointers with all arguments.
* Return: if command exists, returns the full path.
*/
char *find_path(char **tokens)
{
int i = 0, j = 0;
char *path = NULL, *new_path = NULL, **path_tokenized = NULL;
for (i = 0; environ[i]; i++)
{
if (_strncmp(environ[i], "PATH", 4) != NULL)
{
path = _strdup(environ[i]);
break;
}
}
if (path == NULL)
return (NULL);
path_tokenized = tokenizer(path, "=:");
for (j = 1; path_tokenized[j]; j++)
{
new_path = _strdup(path_tokenized[j]);
_strcat(new_path, "/");
_strcat(new_path, tokens[0]);
if (access(new_path, F_OK) == 0)
{
free(path);
free(path_tokenized);
return (new_path);
}
free(new_path);
}
free(path);
free(path_tokenized);
return (NULL);
}