tgrekov-pipex
HIVE pipex May 2024
Loading...
Searching...
No Matches
get_paths.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* get_paths.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tgrekov <tgrekov@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/04/22 05:53:12 by tgrekov #+# #+# */
9/* Updated: 2024/05/20 12:27:38 by tgrekov ### ########.fr */
10/* */
11/* ************************************************************************** */
12
20#include <libft.h>
21#include "../utils/utils.h"
22
31static int compare(void *a, void *b)
32{
33 int len;
34 int blen;
35
36 if (a == b)
37 return (0);
38 if (!a || !b)
39 return (1);
40 len = ft_strlen((char *) a);
41 blen = ft_strlen((char *) b) - 1;
42 if (blen > len)
43 len = blen;
44 return (ft_strncmp((char *) a, (char *) b, len));
45}
46
53static void *copy(void *str)
54{
55 char *str2;
56
57 if (!str)
58 return (0);
59 str2 = ft_strjoin((char *) str, "/");
60 if (!str2)
61 err("malloc()", 0);
62 return (str2);
63}
64
73char **get_paths(char **envp)
74{
75 char **paths;
76 char **paths_uniq;
77
78 while (*envp)
79 {
80 if (!ft_strncmp("PATH=", *envp, 5))
81 {
82 paths = ft_split(*envp + 5, ':');
83 if (!paths)
84 return (err("malloc()", 0));
85 paths_uniq = (char **) dedupe(
86 (void **) paths,
87 compare, copy);
88 arr_free((void **) paths);
89 return (paths_uniq);
90 }
91 envp++;
92 }
93 return (0);
94}
void ** arr_free(void **arr)
Free each element in a null-terminated array, and then the array itself.
Definition arr_free.c:29
void ** dedupe(void **arr, int(*compare)(void *, void *), void *(*copy)(void *))
Create new null-terminated array containing only unique values from arr, checked with compare,...
Definition dedupe.c:35
void * err(const char *str, void *retval)
Wrapper around perror() that always returns retval.
Definition err.c:29
char ** ft_split(char const *s, char c)
Split string s by characer c into allocated array of strings, with NULL as the last element.
Definition ft_split.c:72
char * ft_strjoin(char const *s1, char const *s2)
Allocates enough space for and appends string s2 to string s1 and returns the new string.
Definition ft_strjoin.c:30
size_t ft_strlen(const char *str)
Get length of str.
Definition ft_strlen.c:28
int ft_strncmp(const char *s1, const char *s2, size_t n)
Compare up to n characters of string s1 with string s2.
Definition ft_strncmp.c:33
static void * copy(void *str)
Duplicate a path string and append a forward slash.
Definition get_paths.c:53
char ** get_paths(char **envp)
Create a null-terminated, unique array of paths from the environment pointer envp....
Definition get_paths.c:73
static int compare(void *a, void *b)
Compare path string a against path string b, which will always have a trailing forward slash.
Definition get_paths.c:31