-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_path.c
74 lines (65 loc) · 1.68 KB
/
check_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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nenvoy <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/26 15:37:44 by nenvoy #+# #+# */
/* Updated: 2021/11/26 15:37:44 by nenvoy ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
static void ft_free(char **arr)
{
size_t i;
i = 0;
while (arr[i])
free(arr[i++]);
free (arr);
}
static void *multi_free(char **paths, char *cmd, char *path)
{
char *tmp;
ft_free(paths);
free(path);
tmp = cmd;
free(tmp);
return (cmd);
}
static int find_path(char **envp)
{
int i;
i = 0;
while (envp[i])
{
if (!ft_strncmp(envp[i], "PATH=", 5))
return (i);
i++;
}
return (i);
}
char *check_path(char *command, char **envp)
{
char **paths;
char *path;
char *cmd;
int i;
i = 0;
paths = ft_split(envp[find_path(envp)] + 5, ':');
while (paths[i])
{
path = ft_strjoin(paths[i], "/");
cmd = ft_strjoin(path, command);
if (access(cmd, F_OK) == 0)
return (multi_free(paths, cmd, path));
else
{
free(path);
free(cmd);
i++;
}
}
ft_free(paths);
return (0);
}