42_minishell/infile.c

90 lines
1.4 KiB
C
Raw Normal View History

2023-02-02 11:27:26 -05:00
#include "minishell.h"
static int ft_get_infile(char *line)
{
size_t i;
2023-02-03 10:02:52 -05:00
int fd;
2023-02-02 11:27:26 -05:00
char *path;
2023-02-03 10:02:52 -05:00
fd = 0;
2023-02-02 11:27:26 -05:00
i = 0;
while (line[i] != '\0')
{
if (line[i] == '<' && ft_is_in_quote(line, i) == 0)
{
2023-02-03 10:02:52 -05:00
i++;
if (fd != 0)
close(fd);
if (line[i] == '<')
2023-02-02 11:27:26 -05:00
{
2023-02-03 10:02:52 -05:00
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);
2023-02-02 11:27:26 -05:00
}
2023-02-03 10:02:52 -05:00
free(path);
2023-02-02 11:27:26 -05:00
}
i++;
}
2023-02-03 10:02:52 -05:00
return (fd);
2023-02-02 11:27:26 -05:00
}
static int ft_remove_infile(char *line)
{
size_t i;
2023-02-02 12:40:41 -05:00
int separator;
2023-02-02 11:27:26 -05:00
i = 0;
while (line[i] != '\0')
{
if (line[i] == '<' && ft_is_in_quote(line, i) == 0)
{
2023-02-03 10:02:52 -05:00
while (line[i] == '<')
line[i++] = ' ';
2023-02-02 11:27:26 -05:00
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++] = ' ';
2023-02-02 12:40:41 -05:00
if (line[i] != '\0'
2023-02-02 11:27:26 -05:00
&& (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);
}