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
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* u_path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rbousset <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/14 17:19:27 by rbousset #+# #+# */
/* Updated: 2020/02/14 17:19:29 by rbousset ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include <libft.h>
#include <stddef.h>
#include <dirent.h>
#ifdef __linux__
# include <linux/limits.h>
#else
# include <limits.h>
#endif
#include "s_struct.h"
#include "u_path.h"
#include "u_vars.h"
static void u_get_fullpath(char fullpath[],
const char p_path[],
const char d_name[],
size_t dstsize)
{
const size_t path_len = ft_strlen(p_path);
const size_t name_len = ft_strlen(d_name);
fullpath[0] = C_NUL;
if (path_len + name_len < dstsize)
{
(void)ft_memcpy(fullpath, p_path, path_len * sizeof(char));
*(fullpath + (path_len)) = '/';
(void)ft_memcpy(fullpath + path_len + 1, d_name,
name_len * sizeof(char));
*(fullpath + (path_len + name_len + 1)) = '\0';
}
}
static char u_read_dir(DIR *dir,
struct s_path s,
const char com[],
char fullpath[])
{
struct dirent *ent;
while ((ent = readdir(dir)) != NULL)
{
if (ft_strncmp(com, ent->d_name, ft_strlen(com) + 1) == 0)
{
u_get_fullpath(fullpath, s.tok_path, ent->d_name, s.dstsize);
closedir(dir);
if (fullpath[0] == C_NUL)
return (1);
return (0);
}
}
return (-1);
}
unsigned char u_search_in_path(char fullpath[],
const char com[],
size_t dstsize,
t_msh *msh)
{
char tmp[ARG_MAX];
struct s_path s;
DIR *dir;
char ret;
if (u_get_var_value(tmp, "$PATH", ARG_MAX, msh) != 0)
return (2);
s.dstsize = dstsize;
s.tok_path = ft_strtok(tmp, ":");
while (s.tok_path != NULL)
{
if ((dir = opendir(s.tok_path)) != NULL)
{
ret = u_read_dir(dir, s, com, fullpath);
if (ret == 0 || ret == 1)
return (ret);
closedir(dir);
}
s.tok_path = ft_strtok(NULL, ":");
}
return (2);
}
|