get_next_line/get_next_line.c

76 lines
2.1 KiB
C
Raw Normal View History

2024-10-24 12:38:36 +02:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/23 20:32:46 by kcolin #+# #+# */
2024-11-06 17:57:34 +01:00
/* Updated: 2024/11/06 17:33:37 by kcolin ### ########.fr */
2024-10-24 12:38:36 +02:00
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <stdlib.h>
2024-11-01 12:26:07 +01:00
/*
static int num_allocs = 0;
static void *xmalloc(size_t size)
{
if (FAIL_AFTER > 0 && num_allocs++ >= FAIL_AFTER)
{
return 0;
}
return malloc(size);
}
#define malloc(x) xmalloc(x)
*/
2024-11-06 17:57:34 +01:00
char *read_at_least_one_line(char *buffer, int fd)
2024-10-31 13:13:38 +01:00
{
2024-11-06 17:57:34 +01:00
char *read_buffer;
int bytes_read;
2024-10-31 13:13:38 +01:00
2024-11-06 17:57:34 +01:00
read_buffer = malloc((BUFFER_SIZE + 1 ) * sizeof(char));
if (read_buffer == NULL)
2024-11-01 13:19:52 +01:00
return (NULL);
2024-11-06 17:57:34 +01:00
bytes_read = 1;
while (!ft_strchr(buffer, '\n') && 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);
2024-11-01 13:19:52 +01:00
}
free(read_buffer);
2024-11-06 17:57:34 +01:00
return (buffer);
2024-11-01 13:19:52 +01:00
}
2024-11-06 17:57:34 +01:00
#include <stdio.h>
2024-11-01 13:27:44 +01:00
2024-10-31 11:42:56 +01:00
char *get_next_line(int fd)
{
2024-10-31 13:13:38 +01:00
static char *buffer = NULL;
2024-11-06 17:57:34 +01:00
char *out;
size_t line_length;
2024-10-31 11:42:56 +01:00
2024-11-06 17:57:34 +01:00
if (fd < 0)
2024-10-31 14:22:52 +01:00
return (NULL);
2024-11-06 17:57:34 +01:00
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);
buffer = ft_substr(buffer, line_length, ft_strlen(buffer) - line_length);
return (out);
2024-10-24 12:38:36 +02:00
}