Files
42_INT_07_minishell/srcs/parsing/expansions/ft_strdup_quotes.c
2021-11-14 11:05:58 +01:00

71 lines
2.0 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strdup_quotes.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lperrey <lperrey@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/13 04:35:06 by lperrey #+# #+# */
/* Updated: 2021/11/14 06:01:45 by lperrey ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
enum e_in_quote_state
{
NOT_IN = 0,
IN_QUOTES = '\'',
IN_DQUOTES = '\"'
};
static int quote_state_change(int *quote_state, const char *s);
/* Duplicate a string minus the quoting characters ['] and ["]*/
char *ft_strdup_quotes(const char *s)
{
unsigned int i;
unsigned int i_dup;
char *dup;
int quote_state;
dup = ft_calloc(ft_strlen(s) + 1, 1);
if (!dup)
return (NULL);
i = 0;
i_dup = 0;
quote_state = 0;
while (s[i])
{
while (quote_state_change(&quote_state, &s[i]))
i++;
if (s[i])
dup[i_dup++] = s[i++];
}
return (dup);
}
static int quote_state_change(int *quote_state, const char *s)
{
if (s[0] == '\'' && *quote_state != IN_DQUOTES)
{
if (*quote_state == IN_QUOTES)
*quote_state = 0;
else if (ft_strchr(&s[1], '\'')) // if closed quotes
*quote_state = IN_QUOTES;
else
return (0);
return (1);
}
else if (s[0] == '\"' && *quote_state != IN_QUOTES)
{
if (*quote_state == IN_DQUOTES)
*quote_state = 0;
else if (ft_strchr(&s[1], '\"')) // if closed quotes
*quote_state = IN_DQUOTES;
else
return (0);
return (1);
}
return (0);
}