Browse Source

Initial commit

master
Exagone313 4 years ago
commit
367f1af3de
  1. 1
      auteur
  2. 75
      get_next_line.c
  3. 20
      get_next_line.h

1
auteur

@ -0,0 +1 @@
emartine

75
get_next_line.c

@ -0,0 +1,75 @@
#include "get_next_line.h"
#include <string.h>
static int gnl_copy_line(struct s_fd *fd, char **line, char bf[BUFF_SIZE],
int r)
{
int i;
int n;
char *t;
i = 0;
while (i < r && bf[i] != '\n')
i++;
if (!(t = malloc((fd->l ? fd->n : 0) + i + 1)))
return (-1);
n = 0;
if (fd->l)
{
n = fd->n;
memcpy(t, fd->l, fd->n); // FIXME ft_memcpy
free(fd->l); // FIXME
fd->l = 0;
}
memcpy(t + n, bf, i);
if (i < r)
{
t[n + i] = '\0';
*line = t;
return (1);
}
fd->l = t;
fd->n = n + r;
return (0);
}
int get_next_line(const int fd, char **line)
{
static struct s_fd li[ULIMIT_N_42 + 1] = {{.fd = -1, .l = 0, .n = 0}};
int i;
char bf[BUFF_SIZE];
int r;
if (!line || fd < 0 || fd == 1 || fd == 2)
return (-1);
i = 0;
while (li[i].fd >= 0 && li[i].fd != fd)
i++;
if (li[i].fd != fd)
li[i].fd = fd;
while (1)
{
if ((r = read(fd, bf, BUFF_SIZE)) == 0) // FIXME what if we had some lines saved in the previous buffer?
{
if (li[i].l)
free(li[i].l);
li[i].fd = -1;
li[i].l = 0;
}
if (r <= 0)
return (r);
if ((r = gnl_copy_line(&(li[i]), line, bf, r)))
return (r);
}
}
#include <stdio.h>
int main(){
char *line = {0};
int r = 1;
while (r == 1)
{
r = get_next_line(0, &line);
printf("%s\n", line);
}
}

20
get_next_line.h

@ -0,0 +1,20 @@
#ifndef GET_NEXT_LINE_H
# define GET_NEXT_LINE_H
# include <unistd.h>
# include <stdlib.h>
# define BUFF_SIZE 256
# define ULIMIT_N_42 4864
int get_next_line(const int fd, char **line);
struct s_fd
{
int fd;
char *l;
int n;
};
#endif
Loading…
Cancel
Save