-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipex_util.c
88 lines (79 loc) · 2.06 KB
/
pipex_util.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
81
82
83
84
85
86
87
88
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex_util.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mring <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/07 16:11:39 by mring #+# #+# */
/* Updated: 2024/05/10 16:13:48 by mring ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
int ft_strchr_i(const char *s, int c)
{
unsigned int i;
i = 0;
while (s[i])
{
if (s[i] == (char) c)
return (i);
i++;
}
if (s[i] == (char) c)
return (i);
return (-1);
}
char *join_path(char *path, char *bin)
{
char *joined;
int i;
int j;
joined = malloc(sizeof(char)
* (ft_strchr_i(path, 0) + ft_strchr_i(bin, 0) + 2));
i = 0;
j = 0;
while (path[j])
joined[i++] = path[j++];
joined[i++] = '/';
j = 0;
while (bin[j])
joined[i++] = bin[j++];
joined[i] = 0;
return (joined);
}
char *ft_strndup(char *str, unsigned int n)
{
char *s;
unsigned int i;
i = 0;
s = malloc(sizeof(char) * (n + 1));
while (i < n)
s[i++] = *str++;
s[n] = 0;
return (s);
}
char *get_path(char *cmd, char **envp)
{
char *path;
char *dir;
char *bin;
int i;
i = 0;
while (envp[i] && ft_strncmp(envp[i], "PATH=", 5))
i++;
if (!envp || !envp[i])
return (join_path("/usr/bin/", cmd));
path = envp[i] + 5;
while (path && ft_strchr_i(path, ':') > -1)
{
dir = ft_strndup(path, ft_strchr_i(path, ':'));
bin = join_path(dir, cmd);
free(dir);
if (access(bin, F_OK) == 0)
return (bin);
free(bin);
path += ft_strchr_i(path, ':') + 1;
}
return (cmd);
}