42_minishell/infile.c
2023-02-02 17:27:26 +01:00

76 lines
1.2 KiB
C

#include "minishell.h"
static int ft_get_infile(char *line)
{
size_t i;
char *path;
path = NULL;
i = 0;
while (line[i] != '\0')
{
if (line[i] == '<' && ft_is_in_quote(line, i) == 0)
{
if (path != NULL)
free(path);
path = ft_get_file_path(line + i);
if (path == NULL || ft_file_is_readable(path) == 0)
{
free(path);
return (-1);
}
}
i++;
}
if (path == NULL)
return (-2);
i = open(path, O_RDONLY);
free(path);
return (i);
}
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)
{
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);
}