42_minishell/outfile.c
2023-02-15 20:52:27 +01:00

107 lines
2.5 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* outfile.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/15 18:01:07 by cchauvet #+# #+# */
/* Updated: 2023/02/15 20:48:39 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftx/libftx.h"
#include "minishell.h"
static int ft_outfile_is_valid(const char *line)
{
char **tab;
size_t i;
tab = ft_split_quoted(line, ' ');
if (tab == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (0);
}
i = 0;
while (tab[i + 1] != NULL)
i++;
if (tab[i][0] == '>')
{
ft_eprintf("minishell: %s: must be followed by an infile\n", tab[i]);
return (0);
}
ft_freer_tab_ultimate(1, tab);
return (1);
}
static int ft_get_outfile(const char *line)
{
size_t i;
int fd;
char **tab;
tab = ft_split_quoted(line, ' ');
if (tab == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (-2);
}
fd = 0;
i = 0;
while (tab[i + 1] != NULL)
{
if (ft_strcmp(">", tab[i]) == 0)
fd = ft_file_is_writable(ft_quote_remover(tab[i + 1]));
else if (ft_strcmp(">>", tab[i]) == 0)
fd = ft_file_is_appendable(ft_quote_remover(tab[i + 1]));
i++;
}
ft_freer_tab_ultimate(1, tab);
return (fd);
}
static int ft_remove_outfile(char *line)
{
size_t i;
size_t y;
char **tab;
tab = ft_split_quoted(line, ' ');
if (tab == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (1);
}
i = 0;
y = 0;
while (tab[i] != NULL)
{
if (tab[i][0] == '>')
{
ft_strshift(line + y, -1 * (ft_strlen(tab[i]) + 1));
i++;
ft_strshift(line + y, -1 * (ft_strlen(tab[i]) + 1));
}
else
y = y + ft_strlen(tab[i]);
i++;
}
ft_freer_tab_ultimate(1, tab);
return (0);
}
int ft_outfile(char *line)
{
int fd;
if (ft_outfile_is_valid(line) == 0)
return (-2);
fd = ft_get_outfile(line);
if (fd == -2)
return (-2);
ft_remove_outfile(line);
return (fd);
}