minishell/src/executing/simple_cmd/builtin_echo.c

78 lines
2.1 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* builtin_echo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khais <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/04/03 13:59:13 by khais #+# #+# */
/* Updated: 2025/04/14 11:52:37 by khais ### ########.fr */
/* */
/* ************************************************************************** */
#include "builtins.h"
#include "libft.h"
#include "simple_cmd_execute.h"
#include <stdio.h>
static bool should_print_newline(t_wordlist **arg)
{
bool print_newline;
bool end_of_args;
size_t i;
print_newline = true;
while (*arg != NULL)
{
if ((*arg)->word->word[0] != '-')
break ;
i = 1;
end_of_args = (*arg)->word->word[i] == '\0';
if (end_of_args)
break ;
while ((*arg)->word->word[i] != '\0' && !end_of_args)
{
if ((*arg)->word->word[i++] != 'n')
end_of_args = true;
}
if (end_of_args)
break ;
print_newline = false;
(*arg) = (*arg)->next;
}
return (print_newline);
}
static t_builtin_type write_error(t_minishell *app)
{
app->last_return_value = 1;
perror("minishell: echo: write error");
return (BUILTIN_ECHO);
}
t_builtin_type builtin_echo(t_simple_cmd *cmd, t_minishell *app)
{
t_wordlist *arg;
bool print_newline;
arg = cmd->words->next;
print_newline = should_print_newline(&arg);
while (arg != NULL)
{
if (ft_printf("%s", arg->word->word) < 0)
return (write_error(app));
arg = arg->next;
if (arg != NULL)
{
if (ft_printf(" ") < 0)
return (write_error(app));
}
}
if (print_newline)
{
if (ft_printf("\n") < 0)
return (write_error(app));
}
app->last_return_value = 0;
return (BUILTIN_ECHO);
}