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

99 lines
2.3 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-06 10:22:57 +01:00
/* Updated: 2023/12/04 18:44:34 by adjoly ### ########.fr */
2023-12-01 23:05:16 +01:00
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int check_line(char *buf)
{
int i;
i = 0;
2023-12-06 10:22:57 +01:00
while (buf[i] && buf[i] != '\n')
2023-12-01 23:05:16 +01:00
i++;
if (buf[i] == '\n')
2023-12-06 10:22:57 +01:00
return (i + (buf[i] == '\n'));
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;
char *tmp;
int size;
int bytes_read;
2023-12-01 23:05:16 +01:00
2023-12-06 10:22:57 +01:00
if (BUFFER_SIZE <= 0 || fd < 0)
return (NULL);
res = malloc(1);
if (!res)
return (NULL);
res[0] = '\0';
if (!buf)
{
buf = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buf)
return (NULL);
buf[0] = '\0';
}
while (1)
2023-12-01 23:05:16 +01:00
{
2023-12-06 10:22:57 +01:00
tmp = ft_strjoin(res, buf);
2023-12-01 23:05:16 +01:00
if (!tmp)
2023-12-06 10:22:57 +01:00
return (NULL);
free(res);
res = tmp;
size = check_line(res);
bytes_read = read(fd, buf, BUFFER_SIZE);
buf[bytes_read] = 0;
if (bytes_read == 0 && ft_strlen(res) != 0)
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-06 10:22:57 +01:00
return (res);
}
else if (bytes_read == 0)
return (NULL);
if (size != 0)
{
tmp = ft_strjoin(res, buf);
if (!tmp)
return (NULL);
free(res);
res = tmp;
ft_strlcpy(buf, &res[size], ft_strlen(&res[size]));
buf[ft_strlen(&res[size])] = 0;
res[size] = 0;
return (res);
2023-12-01 23:05:16 +01:00
}
}
}
#include <unistd.h>
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);
while (1)
{
ln = get_next_line(fd);
if (ln == NULL)
2023-12-06 10:22:57 +01:00
return (0);
2023-12-01 23:05:16 +01:00
ft_putstr(ln);
free(ln);
}
}