-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_path.c
More file actions
108 lines (97 loc) · 2.43 KB
/
get_path.c
File metadata and controls
108 lines (97 loc) · 2.43 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dhuss <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/10 09:30:13 by dhuss #+# #+# */
/* Updated: 2024/07/19 12:01:09 by dhuss ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
int find_path(char *envp[])
{
int i;
i = 0;
while (envp[i] != NULL)
{
if (ft_strncmp("PATH=", envp[i], 5) == 0)
return (i);
i++;
}
return (-1);
}
char *concatenate_path_cmd(char *path, char *cmd)
{
char *slash;
char *full_path;
slash = ft_strjoin(path, "/");
if (!slash)
return (NULL);
full_path = ft_strjoin(slash, cmd);
free(slash);
return (full_path);
}
char **add_slash_cmd(char **split_paths, char *cmd)
{
int i;
char **append;
i = 0;
append = allocate_append_array(split_paths);
if (!append)
{
clear_all(split_paths);
return (NULL);
}
while (split_paths[i] != NULL)
{
append[i] = concatenate_path_cmd(split_paths[i], cmd);
if (!append[i])
{
clear_all_double(split_paths, append);
return (NULL);
}
i++;
}
append[i] = NULL;
return (append);
}
char *check_cmd(char **cmd)
{
int i;
i = 0;
while (cmd[i] != NULL)
{
if ((access(cmd[i], F_OK) == 0) && (access(cmd[i], X_OK) == 0))
return (cmd[i]);
i++;
}
return (NULL);
}
char *get_path(char *cmd, char *envp[])
{
t_get_path gp;
gp.append = NULL;
if (envp[0] == NULL)
return (NULL);
gp.i = find_path(envp);
if (gp.i == -1)
return (NULL);
if (envp[gp.i] == NULL)
error_custom(E_CUSTOM_ARGC, NULL);
gp.move = ft_strchr(envp[gp.i], '/');
gp.split_paths = ft_split(gp.move, ':');
if (!gp.split_paths)
return (NULL);
gp.append = add_slash_cmd(gp.split_paths, cmd);
if (gp.split_paths)
clear_all(gp.split_paths);
gp.path = check_cmd(gp.append);
if (gp.path == NULL)
{
clear_all(gp.append);
return (cmd);
}
return (gp.path);
}