42_get_next_line/get_next_line_bonus.c

101 lines
2.2 KiB
C
Raw Normal View History

2022-11-14 09:53:40 -05:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/26 00:52:47 by cchauvet #+# #+# */
2022-11-23 09:28:59 -05:00
/* Updated: 2022/11/23 15:19:15 by cchauvet ### ########.fr */
2022-11-14 09:53:40 -05:00
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.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 < 1)
{
free(str);
return (NULL);
}
return (str);
}
char *ft_getline(int fd)
{
char *stash;
char *buf;
stash = NULL;
buf = NULL;
while (ft_strchr(stash, '\n') == -1)
{
buf = ft_getstash(fd);
if (buf == NULL)
return (stash);
stash = ft_strfjoin(stash, buf);
if (stash == NULL)
return (NULL);
}
return (stash);
}
char *ft_getreturn(char *str)
{
int i;
if (str == NULL)
return (NULL);
i = ft_strchr(str, '\n') + 1;
if (i == 0)
i = ft_strlen(str);
return (ft_strndup(str, i));
}
char *ft_getextra(char *str)
{
int i;
int j;
if (str == NULL)
return (NULL);
i = ft_strchr(str, '\n') + 1;
if (i == 0)
return (NULL);
j = ft_strlen(str + i);
return (ft_strndup(str + i, j));
}
char *get_next_line(int fd)
{
2022-11-23 09:28:59 -05:00
static char *stash[1024] = {0};
2022-11-14 09:53:40 -05:00
char *buf1;
char *buf2;
2022-11-23 09:28:59 -05:00
if (fd > 1023)
return (NULL);
2022-11-14 09:53:40 -05:00
buf2 = stash[fd];
if (ft_strchr(stash[fd], '\n') == -1)
{
buf1 = ft_getline(fd);
buf2 = ft_strfjoin(stash[fd], buf1);
}
buf1 = ft_getreturn(buf2);
stash[fd] = ft_getextra(buf2);
2022-11-23 09:28:59 -05:00
if (buf1 == NULL || buf2 == NULL)
2022-11-14 09:53:40 -05:00
{
free(stash[fd]);
free(buf1);
}
2022-11-23 09:28:59 -05:00
free(buf2);
2022-11-14 09:53:40 -05:00
return (buf1);
}