title: C - Get next line
body: <p>( I'm just authorized to use: malloc, free, read) <br />
  I'm trying to get the next line in a file with any BUF_SIZE but it's returning me the wrong value. <br />
  So, the returned (wrong value, missing firsts chars) value:</p>
  
  <pre><code>3
  1 - #include &lt;stdio.h&gt;
  1 - dlib.h&gt;
  1 - clude "libft/libft.h"
  1 - BUFF_SIZE  32
  </code></pre>
  
  <p>My source code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;fcntl.h&gt;
  #include "libft/libft.h"
  # define BUFF_SIZE  32
  
  int     get_next_line(int const fd, char **line)
  {
      char buffer[BUFF_SIZE + 1];
      size_t i;
      size_t size;
  
      if (!(*line = malloc(BUFF_SIZE)))
          return (-1);
      *line[0] = '\0';
      while (read(fd, buffer, BUFF_SIZE) &gt; 0)
      {
          buffer[BUFF_SIZE + 1] = '\0';
          if (buffer[0] == '\n')
              return (1);
          if (ft_strchr(buffer, '\n') != NULL)
          {
              i = 0;
              size = ft_strlen(*line);
              buffer[BUFF_SIZE + 1] = '\0';
              while (buffer[i] != '\0')
              {
                  if (buffer[i] == '\n')
                  {
                      if (!(*line = realloc(*line, i + size)))
                          return (-1);
                      buffer[i] = '\0';
                      ft_strncat(*line, buffer, i);
                      return (1);
                  }
                  i++;
              }
          }
          if (!(*line = realloc(*line, BUFF_SIZE)))
              return (-1);
          ft_strncat(*line, buffer, BUFF_SIZE);
      }
      return (0);
  }
  
  int     main(void)
  {
      int     fd;
      int     ret;
      char    *line;
  
      if ((fd = open("main.c", O_RDONLY)) &lt; 3 &amp;&amp; fd != 0)
          return (-1);
      printf("%d\n", fd);
      ret = get_next_line(fd, &amp;line);
      printf("%d - %s\n", ret, line);
      ret = get_next_line(fd, &amp;line);
      printf("%d - %s\n", ret, line);
      ret = get_next_line(fd, &amp;line);
      printf("%d - %s\n", ret, line);
      ret = get_next_line(fd, &amp;line);
      printf("%d - %s\n", ret, line);
      return (0);
  }
  </code></pre>