42_get_next_line/get_next_line.c

100 lines
2.3 KiB
C
Raw Normal View History

2022-10-25 20:27:09 -04:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/26 00:52:47 by cchauvet #+# #+# */
/* Updated: 2022/10/26 01:53:25 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
2022-10-25 18:44:33 -04:00
#include "get_next_line.h"
char *ft_getstash(int fd)
{
char *str;
int readed;
str = ft_calloc(BUFFER_SIZE, 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' && c != '\0')
return (-1);
return (i);
}
char *ft_getline(int fd)
{
char *stash;
char *buf;
size_t i;
stash = NULL;
i = 0;
while (ft_strchr(stash + i * BUFFER_SIZE, '\n'))
{
stash = ft_realloc(stash, (i + 1) * BUFFER_SIZE);
if (stash == NULL)
return (NULL);
buf = ft_getstash(fd);
if (buf == NULL)
{
free(stash);
return (NULL);
}
2022-10-25 20:27:09 -04:00
ft_strfcat(stash, buf);
2022-10-25 18:44:33 -04:00
if (stash[(i + 1) * BUFFER_SIZE -1] == '\0')
break ;
}
return (stash);
}
char *get_next_line(int fd)
{
static char *stash = NULL;
char *buf1;
char *buf2;
if (ft_strchr(stash, '\n') == -1)
{
buf1 = ft_getline(fd);
if (buf1 == NULL)
return (NULL);
2022-10-25 20:27:09 -04:00
stash = ft_realloc(stash, ft_strchr(buf1, 0) + ft_strchr(stash, 0) + 2);
2022-10-25 18:44:33 -04:00
if (stash == NULL)
return (NULL);
2022-10-25 20:27:09 -04:00
ft_strfcat(stash, buf1);
2022-10-25 18:44:33 -04:00
}
2022-10-25 20:27:09 -04:00
buf1 = ft_strndup(stash, ft_strchr(stash, '\n') + 1);
buf2 = ft_strndup(stash + ft_strchr(stash, '\n') + 1, ft_strchr(stash, 0));
2022-10-25 18:44:33 -04:00
free(stash);
stash = buf2;
if (stash == NULL || buf1 == NULL)
{
free(stash);
free(buf1);
return (NULL);
}
return (buf1);
}