42_minishell/redirection/redirection.c
2023-04-11 17:01:19 +00:00

116 lines
2.7 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* redirection.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/27 13:44:22 by cchauvet #+# #+# */
/* Updated: 2023/04/11 16:19:24 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "redirection_private.h"
int ft_replace_file(t_data *data, char **tab)
{
size_t i;
char *redirection;
i = 0;
while (tab[i] != NULL)
{
if (ft_is_in("<>", tab[i][0]))
{
i++;
redirection = ft_env_filler(data, tab[i]);
if (redirection == NULL)
return (1);
free(tab[i]);
tab[i] = redirection;
ft_quote_remover(tab[i]);
}
i++;
}
return (0);
}
static void ft_skip(char *str, size_t *i, ssize_t *start)
{
while (str[*i] == str[*start])
(*i)++;
while (str[*i] == ' ')
(*i)++;
while (str[*i] != '\0' && (str[*i] != ' '
|| ft_is_in_quote(str, *i)))
(*i)++;
}
static void ft_remove_redirection(char *cmd_str)
{
size_t i;
ssize_t start;
i = 0;
while (cmd_str[i] != '\0')
{
start = -1;
while ((ft_is_in_quote(cmd_str, i) || !ft_is_in("<>", cmd_str[i]))
&& cmd_str[i] != '\0')
i++;
if (ft_is_in("<>", cmd_str[i]))
start = i;
else
continue ;
ft_skip(cmd_str, &i, &start);
if (start != -1)
{
ft_strshift(cmd_str + start, -1 * (i - start));
i = start;
}
}
}
int ft_set_redirection(t_data *data, t_cmd *cmd, char **tab)
{
size_t i;
i = 0;
while (tab[i + 1] != NULL)
{
if (ft_check_redirection(data, cmd, tab[i], tab[i + 1]))
return (1);
i++;
}
if (ft_is_in("<>", tab[i][0]))
{
ft_eprintf("minishell: %s: must be followed by a file\n", tab[i]);
return (1);
}
return (0);
}
int ft_redirection(t_data *data, t_cmd *cmd, char *cmd_str)
{
char **tab;
cmd->fd_in[0] = -1;
cmd->fd_in[1] = -1;
cmd->fd_out[0] = -1;
cmd->fd_out[1] = -1;
tab = ft_split_charset_quoted(cmd_str, " ");
if (tab == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (1);
}
ft_remove_redirection(cmd_str);
if (ft_set_redirection(data, cmd, tab))
{
ft_freer_tab_ultimate(1, tab);
return (1);
}
ft_freer_tab_ultimate(1, tab);
return (0);
}