get_next_line.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* get_next_line.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: mazimi <mazimi@student.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2015/02/11 23:17:53 by mazimi #+# #+# */
  9. /* Updated: 2015/12/17 17:01:59 by mazimi ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "../get_next_line.h"
  13. int get_next_line(int const fd, char **line)
  14. {
  15. char *tmp;
  16. static char *rst[256];
  17. int ret;
  18. if (fd < 0 || BUFF_SIZE < 1 || !line)
  19. return (-1);
  20. tmp = (rst[fd]) ? ft_strdup(rst[fd]) : ft_strnew(0);
  21. ret = get(fd, tmp, rst, line);
  22. if (ret == -1)
  23. return (-1);
  24. return (ret == 0 ? 0 : 1);
  25. }
  26. int get(int const fd, char *tmp, char **rst, char **line)
  27. {
  28. char *buf;
  29. int ret;
  30. ret = 1;
  31. if (ft_strchr(tmp, '\n') != NULL)
  32. rst[fd] = gnl(tmp);
  33. else
  34. {
  35. buf = ft_strnew(BUFF_SIZE);
  36. while ((ret = read(fd, buf, BUFF_SIZE)) > 0)
  37. {
  38. buf[ret] = '\0';
  39. tmp = ft_strjoinf(tmp, buf, 1);
  40. if (ft_strchr(tmp, '\n') != NULL)
  41. {
  42. (rst[fd] != NULL) ? free(rst[fd]) : NULL;
  43. rst[fd] = gnl(tmp);
  44. ft_strdel(&buf);
  45. break ;
  46. }
  47. }
  48. }
  49. *line = ft_strdup(tmp);
  50. ft_strdel(&tmp);
  51. return (ret);
  52. }
  53. char *gnl(char *tmp)
  54. {
  55. char *tmp2;
  56. tmp2 = ft_strchr(tmp, '\n');
  57. tmp[ft_strlen(tmp) - ft_strlen(tmp2)] = '\0';
  58. return (ft_strdup(tmp2 + 1));
  59. }