-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_path.c
80 lines (67 loc) · 1.38 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "shell.h"
/**
* find_exec - Checks if a command exists in "PATH" or it's an executable
* @arg: The command passed
*
* Return: The executable's absolute path, or NULL if it's not found or an
* error occured
*/
char *find_exec(char *arg)
{
struct stat st;
char *dir, *dir_pos, *path, *path_cp;
int cmd_len, dir_len;
path = getenv("PATH");
if (path)
{
cmd_len = _strlen(arg);
path_cp = _strdup(path);
dir = strtok(path_cp, ":");
while (dir)
{
dir_len = _strlen(dir);
dir_pos = malloc(sizeof(char) * (cmd_len + dir_len + 2));
if (dir_pos == NULL)
{
free(path_cp);
return (NULL);
}
_strcpy(dir_pos, dir);
dir_pos[(_strlen(dir_pos) + 1)] = '\0';
_strcat(dir_pos, "/");
_strcat(dir_pos, arg);
_strcat(dir_pos, "\0");
if (stat(dir_pos, &st) == 0)
{
free(path_cp);
return (dir_pos);
}
free(dir_pos);
dir = strtok(NULL, ":");
}
free(path_cp);
}
return (NULL);
}
/**
* find_path - Checks if a command exists in "PATH" or it's an executable
* @cmd: The command passed
*
* Return: The executable's absolute path, or NULL if it's not found or an
* error occured
*/
char *find_path(char *cmd)
{
struct stat st;
char *cmd_cp, *exec;
exec = find_exec(cmd);
if (exec == NULL)
{
cmd_cp = _strdup(cmd);
if (stat(cmd_cp, &st) == 0)
return (cmd_cp);
free(cmd_cp);
return (NULL);
}
return (exec);
}