get_next_line/get_next_line.c
2024-11-08 15:27:05 +01:00

63 lines
1.9 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/23 20:32:46 by kcolin #+# #+# */
/* Updated: 2024/11/08 15:11:45 by kcolin ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <stdlib.h>
char *read_at_least_one_line(char *buffer, int fd)
{
char *read_buffer;
int bytes_read;
read_buffer = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (read_buffer == NULL)
return (NULL);
bytes_read = 1;
while (ft_strchr(buffer, '\n') == NULL && bytes_read > 0)
{
bytes_read = read(fd, read_buffer, BUFFER_SIZE);
if (bytes_read < 0)
{
free(buffer);
free(read_buffer);
return (NULL);
}
read_buffer[bytes_read] = '\0';
buffer = ft_strjoin(buffer, read_buffer);
if (buffer == NULL)
break ;
}
free(read_buffer);
return (buffer);
}
char *get_next_line(int fd)
{
static char *buffer = NULL;
char *out;
size_t line_length;
char *buf;
if (fd < 0)
return (NULL);
buffer = read_at_least_one_line(buffer, fd);
if (buffer == NULL)
return (NULL);
line_length = 0;
while (buffer[line_length] != '\0' && buffer[line_length] != '\n')
line_length++;
out = ft_substr(buffer, 0, line_length + 1);
buf = buffer;
buffer = ft_substr(buf, line_length + 1, ft_strlen(buffer) - line_length);
free(buf);
return (out);
}