ft_get_next_line.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* get_next_line1.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@students.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2016/01/11 15:09:42 by bchanot #+# #+# */
  9. /* Updated: 2016/07/22 23:59:06 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libft.h"
  13. #include <unistd.h>
  14. #include <stdlib.h>
  15. static char *ft_set_str(char *str)
  16. {
  17. while (*str != '\n' && *str != '\0')
  18. str++;
  19. if (*str == '\n' && str[1] != '\0')
  20. return (ft_strdup(++str));
  21. else
  22. return (NULL);
  23. }
  24. static void ft_add(char **line, char *rest)
  25. {
  26. size_t i;
  27. size_t len;
  28. char *tmp;
  29. i = 0;
  30. if (*line)
  31. {
  32. tmp = ft_strdup(*line);
  33. free(*line);
  34. len = ft_strlen(tmp) + ft_strlen(rest);
  35. *line = (char *)malloc(sizeof(char) * (len + 1));
  36. ft_strcpy(*line, tmp);
  37. free(tmp);
  38. while ((*line)[i])
  39. i++;
  40. }
  41. else
  42. {
  43. len = ft_strlen(rest);
  44. *line = (char *)malloc(sizeof(char) * (len + 1));
  45. }
  46. while (*rest != '\0' && *rest != '\n')
  47. (*line)[i++] = *rest++;
  48. (*line)[i] = '\0';
  49. }
  50. static int ft_take_rest(char **line, char **rest)
  51. {
  52. char *buf;
  53. if (*rest && ft_strchr(*rest, '\n'))
  54. {
  55. ft_add(line, *rest);
  56. buf = *rest;
  57. *rest = ft_set_str(buf);
  58. free(buf);
  59. return (1);
  60. }
  61. else if (*rest && !ft_strchr(*rest, '\n'))
  62. {
  63. *line = ft_strdup(*rest);
  64. free(*rest);
  65. *rest = NULL;
  66. }
  67. return (0);
  68. }
  69. static int ft_check(char **line, char **rest, int const fd)
  70. {
  71. if (line)
  72. *line = NULL;
  73. else
  74. return (-1);
  75. if (BUFF_SIZE <= 0 || fd < 0)
  76. return (-1);
  77. if (ft_take_rest(line, rest))
  78. return (1);
  79. return (0);
  80. }
  81. int ft_get_next_line(int const fd, char **line)
  82. {
  83. int check;
  84. int res;
  85. char *str;
  86. static char *rest;
  87. check = ft_check(line, &rest, fd);
  88. if (check != 0)
  89. return (check);
  90. str = ft_strnew(BUFF_SIZE);
  91. while ((res = read(fd, str, BUFF_SIZE)) > 0 && !ft_strchr(str, '\n'))
  92. {
  93. ft_add(line, str);
  94. ft_bzero(str, BUFF_SIZE + 1);
  95. }
  96. if (res > 0)
  97. {
  98. str[res] = '\0';
  99. ft_add(line, str);
  100. rest = ft_set_str(str);
  101. }
  102. free(str);
  103. res = (res > 1) ? 1 : res;
  104. return ((res == 0 && *line != NULL) ? 1 : res);
  105. }