42_minishell/redirection/heredoc.c

94 lines
2.2 KiB
C
Raw Normal View History

2023-02-17 10:33:52 -05:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* heredoc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/17 15:36:26 by cchauvet #+# #+# */
2023-04-17 08:16:41 -04:00
/* Updated: 2023/04/17 12:14:11 by cchauvet ### ########.fr */
2023-02-17 10:33:52 -05:00
/* */
/* ************************************************************************** */
#include "./redirection_private.h"
2023-04-17 08:16:41 -04:00
#include <readline/readline.h>
#include <unistd.h>
2023-02-03 10:02:52 -05:00
2023-04-17 08:16:41 -04:00
static bool ft_fd_is_closed(int fd)
2023-02-23 09:14:08 -05:00
{
2023-04-17 08:16:41 -04:00
int fd2;
2023-02-23 09:14:08 -05:00
2023-04-17 08:16:41 -04:00
fd2 = dup(fd);
if (fd2 == -1)
return (1);
close(fd2);
return (0);
2023-02-23 09:14:08 -05:00
}
2023-03-29 13:07:57 -04:00
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);
}
2023-04-17 08:16:41 -04:00
int ft_heredoc2(t_data *data, char *line, char *stop, int fds[2])
2023-03-29 13:07:57 -04:00
{
2023-03-31 09:23:10 -04:00
if (line == NULL)
2023-03-31 09:29:06 -04:00
{
2023-04-17 08:16:41 -04:00
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);
}
2023-03-31 09:29:06 -04:00
}
2023-03-29 13:07:57 -04:00
if (ft_strcmp(line, stop) == 0)
2023-04-17 08:16:41 -04:00
return (1);
2023-03-29 13:07:57 -04:00
if (ft_format_and_write(data, line, fds[1]))
{
2023-04-17 08:16:41 -04:00
close(fds[0]);
fds[0] = -2;
2023-03-29 13:07:57 -04:00
return (1);
}
return (0);
}
int ft_heredoc(t_data *data, char *stop)
2023-02-03 10:02:52 -05:00
{
int fds[2];
2023-04-17 08:16:41 -04:00
int stdin_bak;
char *line;
2023-02-03 10:02:52 -05:00
2023-04-17 08:16:41 -04:00
stdin_bak = dup(0);
if (stdin_bak == -1)
return (1);
if (pipe(fds))
2023-02-03 10:02:52 -05:00
{
2023-04-17 08:16:41 -04:00
close(stdin_bak);
return (1);
2023-02-23 09:14:08 -05:00
}
2023-04-17 08:16:41 -04:00
line = readline("> ");
while (ft_heredoc2(data, line, stop, fds) == 0)
{
free(line);
line = readline("> ");
}
free(line);
2023-03-31 10:36:15 -04:00
close(fds[1]);
2023-04-17 08:16:41 -04:00
dup2(stdin_bak, 0);
close(stdin_bak);
return (fds[0]);
2023-02-23 09:14:08 -05:00
}