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.
get_next_line/get_next_line.c

86 lines
2.0 KiB
C
Raw Normal View History

2023-12-01 23:05:16 +01:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adjoly <adjoly@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/01 17:11:59 by adjoly #+# #+# */
2023-12-11 05:09:21 +01:00
/* Updated: 2023/12/08 18:17:17 by adjoly ### ########.fr */
2023-12-01 23:05:16 +01:00
/* */
/* ************************************************************************** */
#include "get_next_line.h"
2023-12-11 05:09:21 +01:00
char check_line(char *res, char *buf)
2023-12-01 23:05:16 +01:00
{
int i;
2023-12-11 05:09:21 +01:00
int j;
2023-12-01 23:05:16 +01:00
i = 0;
2023-12-11 05:09:21 +01:00
j = 0;
while (res[i] && res[i] != '\n')
2023-12-01 23:05:16 +01:00
i++;
2023-12-11 05:09:21 +01:00
if (res[i] == '\n')
{
i++;
while (res[i])
{
buf[j] = res[i];
i++;
j++;
}
buf[j] = 0;
res[i - j] = 0;
return (1);
}
2023-12-01 23:05:16 +01:00
return (0);
}
2023-12-06 10:22:57 +01:00
char *get_next_line(int fd)
2023-12-01 23:05:16 +01:00
{
2023-12-06 10:22:57 +01:00
static char *buf;
char *res;
2023-12-11 05:09:21 +01:00
ssize_t bytes_read;
2023-12-01 23:05:16 +01:00
2023-12-06 11:45:25 +01:00
res = ft_calloc(1, 1);
2023-12-06 10:22:57 +01:00
if (!buf)
2023-12-11 05:09:21 +01:00
buf = ft_calloc(sizeof(char), BUFFER_SIZE + 1);
2023-12-06 16:48:37 +01:00
while (buf && res)
2023-12-01 23:05:16 +01:00
{
2023-12-11 05:09:21 +01:00
res = ft_strjoin(res, buf);
if (check_line(res, buf))
return (res);
2023-12-06 10:22:57 +01:00
bytes_read = read(fd, buf, BUFFER_SIZE);
2023-12-06 16:48:37 +01:00
if (bytes_read < 1)
2023-12-01 23:05:16 +01:00
{
2023-12-06 10:22:57 +01:00
free(buf);
2023-12-01 23:05:16 +01:00
buf = NULL;
2023-12-11 05:09:21 +01:00
if (res[0] != 0)
return (res);
free(res);
2023-12-06 10:22:57 +01:00
return (NULL);
2023-12-01 23:05:16 +01:00
}
2023-12-11 05:09:21 +01:00
buf[bytes_read] = 0;
2023-12-01 23:05:16 +01:00
}
2023-12-06 16:48:37 +01:00
return (NULL);
2023-12-01 23:05:16 +01:00
}
2023-12-11 05:09:21 +01:00
/*#include <unistd.h>
2023-12-01 23:05:16 +01:00
void ft_putstr(char *str){if (str == NULL){return ;}int i = 0;while(str[i]){write(1, &str[i], 1);i++;}}
#include <fcntl.h>
2023-12-06 10:22:57 +01:00
#include <stdio.h>
2023-12-01 23:05:16 +01:00
int main(void)
{
char *ln;
int fd;
fd = open("test.txt", O_RDONLY);
2023-12-11 05:09:21 +01:00
while (ln)
{
2023-12-01 23:05:16 +01:00
ln = get_next_line(fd);
ft_putstr(ln);
free(ln);
2023-12-11 05:09:21 +01:00
}
2023-12-08 11:31:17 +01:00
close(fd);
2023-12-11 05:09:21 +01:00
}*/