minishell/src/utils/ft_split_safe.c
2025-03-02 22:15:46 +01:00

53 lines
1.6 KiB
C

/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split_safe.c :+: :+: */
/* +:+ */
/* By: whaffman <whaffman@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2025/03/02 21:58:06 by whaffman #+# #+# */
/* Updated: 2025/03/02 22:11:34 by whaffman ######## odam.nl */
/* */
/* ************************************************************************** */
#include "minishell.h"
static void *free_arr_safe(t_minishell *msh, int n, char ***arr)
{
while (n-- > 0)
{
free_safe(msh, (void **) &(*arr)[n]);
}
free_safe(msh, (void **) *arr);
return (NULL);
}
char **ft_split_safe(t_minishell *msh, char const *s, char c)
{
char **result;
int n;
int i;
int j;
result = malloc_safe(msh, (ft_count_words(s, c) + 1) * sizeof(char *));
if (!result)
return (NULL);
i = 0;
n = 0;
while (s[i])
{
j = 0;
while (s[i] == c)
i++;
while (s[i + j] && s[i + j] != c)
j++;
if (j)
result[n] = ft_substr_safe(msh, s, i, j);
if (j && !result[n++])
return (free_arr_safe(msh, n, &result));
i += j;
}
result[n] = NULL;
return (result);
}