Archived
1
0
This repository has been archived on 2024-10-25. You can view files and clone it, but cannot push or open issues or pull requests.
FDF/get_next_line/get_next_line.c

76 lines
1.8 KiB
C
Raw Normal View History

2023-12-12 13:28:15 +01:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adjoly <adjoly@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/01 17:11:59 by adjoly #+# #+# */
2023-12-18 17:19:34 +01:00
/* Updated: 2023/12/18 09:18:43 by adjoly ### ########.fr */
2023-12-12 13:28:15 +01:00
/* */
/* ************************************************************************** */
#include "get_next_line.h"
2023-12-18 17:19:34 +01:00
#include "../libft/libft.h"
2023-12-12 13:28:15 +01:00
char check_line(char *res, char *buf)
{
int i;
int j;
i = 0;
j = 0;
while (res[i] && res[i] != '\n')
i++;
if (res[i] == '\n')
{
i++;
while (res[i])
{
buf[j] = res[i];
i++;
j++;
}
buf[j] = 0;
res[i - j] = 0;
return (1);
}
return (0);
}
2023-12-18 17:19:34 +01:00
char *ft_read_error(char **buf, char *res)
{
free(*buf);
*buf = NULL;
if (res[0] != 0)
return (res);
free(res);
return (NULL);
}
2023-12-12 13:28:15 +01:00
char *get_next_line(int fd)
{
static char *buf;
char *res;
ssize_t bytes_read;
2023-12-18 17:19:34 +01:00
if (BUFFER_SIZE <= 0 || fd < 0 || fd > 1023)
return (NULL);
2023-12-12 13:28:15 +01:00
if (!buf)
buf = ft_calloc(sizeof(char), BUFFER_SIZE + 1);
2023-12-18 17:19:34 +01:00
res = ft_calloc(1, 1);
while (buf)
2023-12-12 13:28:15 +01:00
{
res = ft_strjoin(res, buf);
2023-12-18 17:19:34 +01:00
if (!res)
return (NULL);
2023-12-12 13:28:15 +01:00
if (check_line(res, buf))
return (res);
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read < 1)
2023-12-18 17:19:34 +01:00
return (ft_read_error(&buf, res));
2023-12-12 13:28:15 +01:00
buf[bytes_read] = 0;
}
return (NULL);
}