42_minishell/outfile.c
Camille Chauvet 67fb6d0533 -m
2023-02-14 07:26:18 +01:00

90 lines
1.4 KiB
C

#include "minishell.h"
static int ft_get_outfile(char *line)
{
size_t i;
int append;
char *path;
path = NULL;
append = 0;
i = 0;
while (line[i] != '\0')
{
if (line[i] == '>' && ft_is_in_quote(line, i) == 0)
{
i++;
if (line[i] == '>')
{
i++;
append = 1;
}
else
append = 0;
if (path != NULL)
free(path);
path = ft_get_file_path(line + i);
if (path == NULL || ft_file_is_writeable(path) == 0)
{
free(path);
return (-1);
}
}
i++;
}
if (path == NULL)
return (-2);
if (append == 1)
i = open(path, O_APPEND | O_CREAT, 0664);
else
i = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0664);
free(path);
return (i);
}
static int ft_remove_outfile(char *line)
{
size_t i;
int separator;
i = 0;
while (line[i] != '\0')
{
if (line[i] == '>' && ft_is_in_quote(line, i) == 0)
{
while (line[i] == '>')
line[i++] = ' ';
while (line[i] == ' ')
i++;
separator = ft_is_in_quote(line, i);
if (separator == 0)
separator = ' ';
else if (separator == 1)
separator = '\'';
else
separator = '\"';
while (line[i] != separator && line[i] != '\0')
line[i++] = ' ';
if (line[i] != '\0'
&& (separator == '\'' || separator == '\"'))
line[i++] = ' ';
}
i++;
}
return (0);
}
int ft_outfile(char *line)
{
int fd;
fd = ft_get_outfile(line);
if (ft_remove_outfile(line))
{
if (fd > 0)
close(fd);
return (-1);
}
return (fd);
}