42_minishell/redirection/heredoc.c
2023-04-17 12:16:41 +00:00

94 lines
2.2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* heredoc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/17 15:36:26 by cchauvet #+# #+# */
/* Updated: 2023/04/17 12:14:11 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "./redirection_private.h"
#include <readline/readline.h>
#include <unistd.h>
static bool ft_fd_is_closed(int fd)
{
int fd2;
fd2 = dup(fd);
if (fd2 == -1)
return (1);
close(fd2);
return (0);
}
static int ft_format_and_write(t_data *data, const char *str, int fd)
{
char *line_clean;
line_clean = ft_env_filler(data, str);
if (line_clean == NULL)
return (1);
ft_putendl_fd(line_clean, fd);
free(line_clean);
return (0);
}
int ft_heredoc2(t_data *data, char *line, char *stop, int fds[2])
{
if (line == NULL)
{
if (ft_fd_is_closed(0))
{
close(fds[0]);
fds[0] = -2;
return (1);
}
else
{
ft_eprintf("\nbozoshell: warning: here-document at line 1%s",
"delimited by end-of-file (wanted `adfsd')\n");
return (1);
}
}
if (ft_strcmp(line, stop) == 0)
return (1);
if (ft_format_and_write(data, line, fds[1]))
{
close(fds[0]);
fds[0] = -2;
return (1);
}
return (0);
}
int ft_heredoc(t_data *data, char *stop)
{
int fds[2];
int stdin_bak;
char *line;
stdin_bak = dup(0);
if (stdin_bak == -1)
return (1);
if (pipe(fds))
{
close(stdin_bak);
return (1);
}
line = readline("> ");
while (ft_heredoc2(data, line, stop, fds) == 0)
{
free(line);
line = readline("> ");
}
free(line);
close(fds[1]);
dup2(stdin_bak, 0);
close(stdin_bak);
return (fds[0]);
}