42_minishell/infile.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_infile(char *line)
{
size_t i;
int fd;
char *path;
fd = 0;
i = 0;
while (line[i] != '\0')
{
if (line[i] == '<' && ft_is_in_quote(line, i) == 0)
{
i++;
if (fd != 0)
close(fd);
if (line[i] == '<')
{
i++;
path = ft_get_file_path(line + i);
if (path == NULL)
return (-1);
fd = ft_heredoc(path);
}
else
{
path = ft_get_file_path(line + i);
if (path == NULL)
return (-1);
if (ft_file_is_readable(path) == 0)
{
free(path);
return (-1);
}
fd = open(path, O_RDONLY);
}
free(path);
}
i++;
}
return (fd);
}
static int ft_remove_infile(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_infile(char *line)
{
int fd;
fd = ft_get_infile(line);
if (ft_remove_infile(line))
{
if (fd > 0)
close(fd);
return (-1);
}
return (fd);
}