diff --git a/redirection/check.c b/redirection/check.c index 5b9284a..449bce4 100644 --- a/redirection/check.c +++ b/redirection/check.c @@ -6,7 +6,7 @@ /* By: cchauvet fd_in[0] = ft_heredoc(data, redirection); - if (cmd->fd_in[0] == -2) + fd = ft_heredoc(data, redirection); + if (fd == -2) return (1); + else + { + if (cmd->fd_in[0] > 2) + close(cmd->fd_in[0]); + cmd->fd_in[0] = fd; + } } return (0); } @@ -27,12 +35,21 @@ static bool ft_check_heredoc(t_data *data, t_cmd *cmd, static bool ft_check_infile(t_data *data, t_cmd *cmd, char *redirection_identifier, char *redirection) { + int fd; + if (ft_strcmp(redirection_identifier, "<") == 0) { if (ft_file_is_readable(data, redirection)) - cmd->fd_in[0] = open(redirection, O_RDONLY); + { + fd = open(redirection, O_RDONLY); + if (cmd->fd_in[0] > 2) + close(cmd->fd_in[0]); + cmd->fd_in[0] = fd; + } else { + if (cmd->fd_in[0] > 2) + close(cmd->fd_in[0]); cmd->fd_in[0] = -2; return (1); } @@ -43,13 +60,22 @@ static bool ft_check_infile(t_data *data, t_cmd *cmd, static bool ft_check_outfile(t_data *data, t_cmd *cmd, char *redirection_identifier, char *redirection) { + int fd; + if (ft_strcmp(redirection_identifier, ">") == 0) { if (ft_file_is_writable(data, redirection)) - cmd->fd_out[0] = open(redirection, + { + fd = open(redirection, O_WRONLY | O_TRUNC | O_CREAT, 0644); + if (cmd->fd_out[0] > 2) + close(cmd->fd_out[0]); + cmd->fd_out[0] = fd; + } else { + if (cmd->fd_out[0] > 2) + close(cmd->fd_out[0]); cmd->fd_out[0] = -2; return (1); } @@ -60,13 +86,22 @@ static bool ft_check_outfile(t_data *data, t_cmd *cmd, static bool ft_check_outfile_append(t_data *data, t_cmd *cmd, char *redirection_identifier, char *redirection) { + int fd; + if (ft_strcmp(redirection_identifier, ">>") == 0) { if (ft_file_is_writable(data, redirection)) - cmd->fd_out[0] = open(redirection, + { + fd = open(redirection, O_WRONLY | O_APPEND | O_CREAT, 0644); + if (cmd->fd_out[0] > 2) + close(cmd->fd_out[0]); + cmd->fd_out[0] = fd; + } else { + if (cmd->fd_out[0] > 2) + close(cmd->fd_out[0]); cmd->fd_out[0] = -2; return (1); } @@ -78,7 +113,6 @@ bool ft_check_redirection(t_data *data, t_cmd *cmd, char *redirection_identifier, char *redirection) { char *str; - bool return_code; if (ft_is_in("<>", redirection[0])) { @@ -92,11 +126,12 @@ bool ft_check_redirection(t_data *data, t_cmd *cmd, return (1); } ft_quote_remover(str); - return_code = (ft_check_heredoc(data, cmd, redirection_identifier, str) + if (ft_check_heredoc(data, cmd, redirection_identifier, str) || ft_check_infile(data, cmd, redirection_identifier, str) || ft_check_outfile(data, cmd, redirection_identifier, str) || ft_check_outfile_append(data, cmd, redirection_identifier, - str)); + str)) + ; free(str); - return (return_code); + return (0); }