-
Notifications
You must be signed in to change notification settings - Fork 1
/
findpath.c
43 lines (35 loc) · 811 Bytes
/
findpath.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
#include "shell.h"
/**
* findpath - searches through the directories to find a command
*
* Return: absolute path to the command if found, else NULL
*/
char *findpath(void)
{
int i = 0;
char *path_val = _getenv("PATH");
char **path_dir, *abs_path;
if (_strncmp(command[0], "./", 2) == 0 || command[0][0] == '/' || _strncmp(command[0], "../", 3))
{
if (access(command[0], F_OK) == 0)
return _strdup(command[0]);
}
if (!path_val)
return (NULL);
path_dir = strtoarr(path_val, ':');
for (i = 0; path_dir[i]; i++)
{
abs_path = malloc(1024);
_strcpy(abs_path, path_dir[i]);
_strcat(abs_path, "/");
_strcat(abs_path, command[0]);
if (access(abs_path, F_OK) == 0)
{
free_array(path_dir);
return (abs_path);
}
free(abs_path);
}
free_array(path_dir);
return (NULL);
}