42_minishell/redirection/redirection.c

116 lines
2.7 KiB
C
Raw Permalink Normal View History

2023-03-28 09:55:08 -04:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* redirection.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/27 13:44:22 by cchauvet #+# #+# */
2023-04-13 09:26:52 -04:00
/* Updated: 2023/04/13 13:26:06 by cchauvet ### ########.fr */
2023-03-28 09:55:08 -04:00
/* */
/* ************************************************************************** */
2023-03-13 09:23:27 -04:00
#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);
}
2023-03-29 13:07:57 -04:00
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)
2023-03-13 09:23:27 -04:00
{
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;
2023-03-29 13:07:57 -04:00
else
2023-03-13 10:12:50 -04:00
continue ;
2023-03-29 13:07:57 -04:00
ft_skip(cmd_str, &i, &start);
2023-03-13 09:23:27 -04:00
if (start != -1)
2023-03-20 08:18:20 -04:00
{
2023-03-29 13:07:57 -04:00
ft_strshift(cmd_str + start, -1 * (i - start));
2023-03-20 08:18:20 -04:00
i = start;
}
2023-03-13 09:23:27 -04:00
}
}
int ft_set_redirection(t_data *data, t_cmd *cmd, char **tab)
{
size_t i;
i = 0;
while (tab[i + 1] != NULL)
{
2023-04-05 08:13:56 -04:00
if (ft_check_redirection(data, cmd, tab[i], tab[i + 1]))
return (1);
2023-03-13 09:23:27 -04:00
i++;
}
if (ft_is_in("<>", tab[i][0]))
{
2023-04-14 10:17:35 -04:00
ft_eprintf("bozoshell: %s: must be followed by a file\n", tab[i]);
return (1);
}
2023-03-13 09:23:27 -04:00
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;
2023-04-13 09:26:52 -04:00
tab = ft_split_charset_quoted(cmd_str, " \t");
2023-03-13 09:23:27 -04:00
if (tab == NULL)
{
2023-04-14 10:17:35 -04:00
ft_eprintf("bozoshell: malloc failed\n");
2023-03-13 09:23:27 -04:00
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);
}