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_bonus.c

75 lines
1.8 KiB
C
Raw Normal View History

2023-12-12 13:28:15 +01:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.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/15 05:51:22 by adjoly ### ########.fr */
2023-12-12 13:28:15 +01:00
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
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[1024];
char *res;
2023-12-18 17:19:34 +01:00
ssize_t bytes_read;
2023-12-12 13:28:15 +01:00
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[fd])
buf[fd] = ft_calloc(sizeof(char), BUFFER_SIZE + 1);
2023-12-18 17:19:34 +01:00
res = ft_calloc(1, 1);
2023-12-12 13:28:15 +01:00
while (buf[fd] && res)
{
2023-12-18 17:19:34 +01:00
res = ft_strjoin(res, buf[fd]);
if (!res)
return (NULL);
2023-12-12 13:28:15 +01:00
if (check_line(res, buf[fd]))
return (res);
bytes_read = read(fd, buf[fd], BUFFER_SIZE);
if (bytes_read < 1)
2023-12-18 17:19:34 +01:00
return (ft_read_error(&buf[fd], res));
2023-12-12 13:28:15 +01:00
buf[fd][bytes_read] = 0;
}
return (NULL);
}