From: Lukas Jiriste Date: Fri, 16 Feb 2024 23:10:04 +0000 (+0100) Subject: Make get_next_line able to free all its memory X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=0c6fb946da0bd3d8a0a15e4686020b3e103cdede;p=Libft.git Make get_next_line able to free all its memory Passing negative fd to get_next_line now signalizes to it that it should close (free) every buffer. --- diff --git a/ft_io/get_next_line.c b/ft_io/get_next_line.c index dcc2579..1523988 100644 --- a/ft_io/get_next_line.c +++ b/ft_io/get_next_line.c @@ -6,7 +6,7 @@ /* By: ljiriste +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/08/28 00:01:15 by ljiriste #+# #+# */ -/* Updated: 2023/12/09 15:52:02 by ljiriste ### ########.fr */ +/* Updated: 2024/02/17 00:05:19 by ljiriste ### ########.fr */ /* */ /* ************************************************************************** */ @@ -42,12 +42,38 @@ t_list *new_ft_node(int fd) return (node); } -// How to free? -// static in get_next_line? So it could be passed to select AND delete +static void delete_file_node(int fd, t_list **list) +{ + t_list *cur; + t_list *prev; + + prev = NULL; + cur = *list; + while (fd >= 0 && ((t_ft *)(cur->content))->fd != fd) + { + prev = cur; + cur = cur->next; + } + if (prev == NULL) + *list = cur->next; + else + prev->next = cur->next; + free(((t_ft *)(cur->content))->buffer); + free(cur->content); + free(cur); + return ; +} + static char *select_file_buffer(int fd, t_list **list) { t_list *local_head; + if (fd < 0) + { + while (*list != NULL) + delete_file_node(-1, list); + return (NULL); + } if (*list == NULL) { *list = new_ft_node(fd); @@ -66,28 +92,6 @@ static char *select_file_buffer(int fd, t_list **list) return (((t_ft *)(local_head->next->content))->buffer); } -static void delete_file_node(int fd, t_list **list) -{ - t_list *cur; - t_list *prev; - - prev = NULL; - cur = *list; - while (((t_ft *)(cur->content))->fd != fd) - { - prev = cur; - cur = cur->next; - } - if (prev == NULL) - *list = cur->next; - else - prev->next = cur->next; - free(((t_ft *)(cur->content))->buffer); - free(cur->content); - free(cur); - return ; -} - /* Concatenates res and buffer up to newline. Shifts buffer by the transfered characters. Returns 0 when buffer is empty (and needs filling with read). @@ -110,6 +114,7 @@ static int transfer_string(char **res, char *buffer) return (buffer[0] || nl); } +// Passing negative fd causes every buffer to close char *get_next_line(int fd) { static t_list *list; @@ -119,7 +124,7 @@ char *get_next_line(int fd) res = NULL; buffer = select_file_buffer(fd, &list); - while (!transfer_string(&res, buffer)) + while (buffer && !transfer_string(&res, buffer)) { if (buffer[0] == '\0') {