42_get_next_line/get_next_line.c
2022-10-28 13:41:06 +02:00

100 lines
2.2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/26 00:52:47 by cchauvet #+# #+# */
/* Updated: 2022/10/28 13:37:18 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_getstash(int fd)
{
char *str;
int readed;
str = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
if (str == NULL)
return (NULL);
readed = read(fd, str, BUFFER_SIZE);
if (readed < 0)
{
free(str);
return (NULL);
}
return (str);
}
ssize_t ft_strchr(char *str, char c)
{
size_t i;
if (str == NULL)
return (-1);
i = 0;
while (str[i] != c && str[i] != '\0')
i++;
if (str[i] == '\0')
return (-1);
return (i);
}
char *ft_getline(int fd)
{
char *stash;
char *buf;
size_t i;
stash = NULL;
buf = NULL;
i = 0;
while (ft_strchr(stash + i, '\n') == -1)
{
i = i + ft_strlen(buf);
buf = ft_getstash(fd);
if (buf == NULL)
return (NULL);
if (buf[0] == '\0')
{
free(buf);
break ;
}
stash = ft_strfjoin(stash, buf);
if (stash == NULL)
return (NULL);
}
return (stash);
}
char *get_next_line(int fd)
{
static char *stash = NULL;
char *buf1;
char *buf2;
buf2 = stash;
if (ft_strchr(stash, '\n') == -1)
{
buf1 = ft_getline(fd);
if (buf1 == NULL)
return (NULL);
buf2 = ft_strfjoin(stash, buf1);
if (buf2 == NULL)
return (NULL);
}
buf1 = ft_strndup(buf2, ft_strchr(buf2, '\n') + 1);
stash = ft_strndup(buf2 + ft_strchr(buf2, '\n') + 1, ft_strlen(buf2));
free(buf2);
if (stash == NULL || buf1 == NULL)
{
free(stash);
free(buf1);
return (NULL);
}
return (buf1);
}