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 95 96 97 98 99 100 101 102
| #include "libft/libft.h"
int ft_strpos(const char *str, char c)
{
char *cpstr;
int i;
i = 0;
cpstr = (char *)str;
while (*cpstr != '\0' || *cpstr == c)
{
cpstr++;
i++;
}
return (i);
}
void ft_add_line(char **line, char **tmp, long len)
{
char *thistmp;
long leni;
if (line == NULL)
line = (char **)ft_memalloc(sizeof(char **));
leni = ft_strlen(*line);
*line = (char *)ft_realloc(*line, leni, leni + len + 1);
if (*line)
{
*line[leni + len] = '\0';
ft_strncat (*line, *tmp, len);
thistmp = ft_strnew(BUF_SIZE * sizeof(char *));
if (thistmp)
{
ft_strncat(thistmp, (*tmp) + len + 1, BUF_SIZE - len - 1);
free(*tmp);
*tmp = thistmp;
}
}
}
void ft_read(int const *fd, char **line, char **tmp, long *ret)
{
int stop;
stop = 0;
if (*tmp == NULL)
{
*tmp = ft_strnew(BUF_SIZE * sizeof(char *));
*ret = read(*fd, tmp, BUF_SIZE);
}
*line = ft_strnew(BUF_SIZE * sizeof(char *));
while (*line != NULL && *ret == BUF_SIZE && !stop)
{
if (ft_strchr(*tmp, '\n') != 0)
{
ft_add_line(line, tmp, ft_strpos(*tmp, '\n'));
stop = 1;
}
else
{
ft_add_line(line, tmp, BUF_SIZE);
*ret = read(*fd, *tmp, BUF_SIZE);
}
}
}
int get_next_line(int const fd, char **line)
{
long ret;
static char *current;
if (fd < 0 || line == NULL)
return (-1);
ret = BUF_SIZE;
(void)ft_read(&fd, line, ¤t, &ret);
if (ret != BUF_SIZE && ret > 0)
ft_add_line (line, ¤t, ret - 1);
return (1);
}
int main(void)
{
int fd;
char ** line;
if ( fd > 1 )
{
(char **)line = (char **)ft_memalloc ( 2 );
fd = open("libft/test", O_RDONLY);
while (get_next_line (fd, line) > 0)
{
printf("%s--",*line);
}
free (line);
close(fd);
}
return (0);
} |
Partager