get_next_line/get_next_line_bonus.c
Etienne Rey-bethbeder c3e321b3ab Ajout get_next_line
2022-11-16 13:32:26 +01:00

117 lines
2.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/15 23:42:35 by erey-bet #+# #+# */
/* Updated: 2022/11/16 13:20:26 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *read_line(int fd)
{
char *buff;
int y;
buff = ft_calloc(BUFFER_SIZE + 1, 1);
if (buff == NULL)
return (NULL);
y = read(fd, buff, BUFFER_SIZE);
if (y == -1)
{
free(buff);
return (NULL);
}
buff[y] = '\0';
return (buff);
}
static char *join_str(char *s1, char *s2)
{
char *n_str;
int i;
int len;
len = ft_strlen(s1);
n_str = ft_calloc(len + ft_strlen(s2) + 1, 1);
if (n_str == NULL)
return (NULL);
i = -1;
if (s1 != NULL)
while (s1[++i])
n_str[i] = s1[i];
i = -1;
while (s2[++i])
n_str[i + len] = s2[i];
n_str[i + len] = '\0';
free(s1);
free(s2);
return (n_str);
}
static char *get_text(char *save)
{
int i;
char *new_s;
i = 0;
while (save[i] && save[i] != '\n')
i++;
if (save[i] == '\n')
i++;
new_s = ft_calloc(i + 1, 1);
if (new_s == NULL)
return (NULL);
ft_strlcpy(new_s, save, i + 1);
ft_strlcpy(save, save + i, ft_strlen(save));
return (new_s);
}
static void *make_free(char *buff, char **save, int choice)
{
if (choice == 1)
{
free(buff);
free(*save);
}
else
{
free(*save);
*save = NULL;
}
return (NULL);
}
static char *get_next_line(int fd)
{
char *buff;
char *str;
static char *save[1024];
if (fd < 0 || fd >= 1024)
return (NULL);
buff = NULL;
while (buff == NULL || ft_strchr(save[fd], '\n') == -1)
{
buff = read_line(fd);
if (buff == NULL || (ft_strlen(buff) == 0 && ft_strlen(save[fd]) == 0))
return (make_free(buff, &save[fd], 1));
if (ft_strlen(buff) == 0)
{
free(buff);
break;
}
save[fd] = join_str(save[fd], buff);
if (save[fd] == NULL)
return (NULL);
}
str = get_text(save[fd]);
if (ft_strlen(save[fd]) == 0)
make_free(NULL, &save[fd], 2);
return (str);
}