Bad mess, please ignore
This commit is contained in:
commit
60514beb45
5 changed files with 215 additions and 0 deletions
102
get_next_line.c
Normal file
102
get_next_line.c
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
/* ************************************************************************** */
|
||||
/* */
|
||||
/* ::: :::::::: */
|
||||
/* get_next_line.c :+: :+: :+: */
|
||||
/* +:+ +:+ +:+ */
|
||||
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
|
||||
/* +#+#+#+#+#+ +#+ */
|
||||
/* Created: 2024/10/23 20:32:46 by kcolin #+# #+# */
|
||||
/* Updated: 2024/10/24 12:34:49 by kcolin ### ########.fr */
|
||||
/* */
|
||||
/* ************************************************************************** */
|
||||
|
||||
#include "get_next_line.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
static char *ft_realloc(char *ptr, size_t new_size, size_t old_size)
|
||||
{
|
||||
char *outptr;
|
||||
size_t i;
|
||||
|
||||
outptr = malloc(new_size);
|
||||
if (outptr != NULL)
|
||||
{
|
||||
i = 0;
|
||||
while (i < old_size)
|
||||
{
|
||||
outptr[i] = ptr[i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
free(ptr);
|
||||
return (outptr);
|
||||
}
|
||||
|
||||
static char *ft_strchr(const char *s, int c)
|
||||
{
|
||||
int i;
|
||||
|
||||
i = 0;
|
||||
while (s[i] != '\0')
|
||||
{
|
||||
if (s[i] == (char)c)
|
||||
return ((char *)s + i);
|
||||
i++;
|
||||
}
|
||||
if ((char)c == '\0')
|
||||
return ((char *)s + i);
|
||||
return (0);
|
||||
}
|
||||
|
||||
char *get_next_line(int fd)
|
||||
{
|
||||
static char *buffer = NULL;
|
||||
static size_t buf_size = BUFFER_SIZE;
|
||||
static size_t length = 0;
|
||||
int num_bytes_read;
|
||||
char *newline_addr;
|
||||
char *out;
|
||||
long i;
|
||||
|
||||
if (buffer == NULL)
|
||||
{
|
||||
buffer = malloc(BUFFER_SIZE * sizeof(char));
|
||||
buf_size = BUFFER_SIZE;
|
||||
length = 0;
|
||||
}
|
||||
if (buffer == NULL)
|
||||
return (NULL);
|
||||
num_bytes_read = 1;
|
||||
while (num_bytes_read != 0)
|
||||
{
|
||||
if (length == buf_size)
|
||||
{
|
||||
buffer = ft_realloc(buffer, sizeof(char) * buf_size * 1.5, buf_size);
|
||||
if (buffer == NULL)
|
||||
return (NULL);
|
||||
buf_size *= 1.5;
|
||||
}
|
||||
num_bytes_read = read(fd, buffer + length, buf_size - length);
|
||||
if (num_bytes_read < 0)
|
||||
{
|
||||
free(buffer);
|
||||
buffer = NULL;
|
||||
return (NULL);
|
||||
}
|
||||
length += num_bytes_read;
|
||||
newline_addr = ft_strchr(buffer, '\n');
|
||||
if (newline_addr != NULL)
|
||||
{
|
||||
out = malloc((newline_addr - buffer + 1) * sizeof(char));
|
||||
out[(newline_addr - buffer)] = '\0';
|
||||
i = 0;
|
||||
while (i < (newline_addr - buffer))
|
||||
{
|
||||
out[i] = buffer[i];
|
||||
i++;
|
||||
}
|
||||
return (out);
|
||||
}
|
||||
}
|
||||
return (buffer);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue