1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| #include "get_next_line.h"
char *ft_get_line(char *save)
{
int i;
char *s;
i = 0;
if (!save[i])
return (NULL);
while (save[i] && save[i] != '\n')
i++;
s = (char *)malloc(sizeof(char) * (i + 2));
if (!s)
return (NULL);
i = 0;
while (save[i] && save[i] != '\n')
{
s[i] = save[i];
i++;
}
if (save[i] == '\n')
{
s[i] = save[i];
i++;
}
s[i] = '\0';
return (s);
}
char *ft_save(char *save)
{
int i;
int c;
char *s;
i = 0;
while (save[i] && save[i] != '\n')
i++;
if (!save[i])
{
free(save);
return (NULL);
}
s = (char *)malloc(sizeof(char) * (ft_strlen(save) - i + 1));
if (!s)
return (NULL);
i++;
c = 0;
while (save[i])
s[c++] = save[i++];
s[c] = '\0';
free(save);
return (s);
}
char *ft_read_and_save(int fd, char *save)
{
char *buff;
int read_bytes;
buff = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buff)
return (NULL);
read_bytes = 1;
while (!ft_strchr(save, '\n') && read_bytes != 0)
{
read_bytes = read(fd, buff, BUFFER_SIZE);
if (read_bytes == -1)
{
free(buff);
return (NULL);
}
buff[read_bytes] = '\0';
save = ft_strjoin(save, buff);
}
free(buff);
return (save);
}
char *get_next_line(int fd)
{
char *line;
static char *save;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
save = ft_read_and_save(fd, save);
if (!save)
return (NULL);
line = ft_get_line(save);
save = ft_save(save);
return (line);
} |
Partager