title: Read File line by line in C mostly with Syscalls
body: <p>I'm trying to read and parse a file line by line.
  I only want to use simple syscalls (<code>read</code>, <code>open</code>, <code>close</code>, ...) and not <code>fgets</code> or <code>getc</code> because I wish to learn, in a way, fundamentals. (I looked some answers on similar questions but they all use <code>fgets</code> and such).</p>
  
  <p>Here's what I have at the moment:a function I wrote that will store 1024 chars in a buffer from a file.</p>
  
  <pre><code>int main(void) {
      const char *filename = "file.txt";
      int fd = open(filename, O_RDONLY);
      char *buffer = malloc(sizeof (char) * 1024); 
  
      read(fd, buffer, 1024);        
      printf("%s", buffer);
      close(fd);
      free(buffer);    
  }
  </code></pre>
  
  <p>How does one make a stop at a '\n' for instance?
  I know that once I know where to stop, I can use <code>lseek</code> with the right offset to continue reading my file where I stopped.</p>
  
  <p>I do not wish to store the whole file in my buffer and then parse it.
  I want to add a line in my buffer, then parse that line and realloc my buffer and keep on reading the file.</p>
  
  <p>I was thinking of something like this but I feel like it's badly optimized and not sure where to add the <code>lseek</code> afterwards:</p>
  
  <pre><code>char *line = malloc(sizeof (char) * 1024);
  read(fd, buffer, 1);
  int i = 0;
      while(*buffer != '\n' &amp;&amp; *buffer != '\0'){
          line[i] = *buffer;
          ++i;
          *buffer++;
          read(fd, buffer, 1); //Assuming i &lt; 1024 and *buffer != NULL
      }
  
  
    /* lseek somewhere after, probably should make 2 for loops 
     ** One loop till file isn't completly read
     ** Another loop inside that checks if the end of the line is reached
     ** At the end of second loop lseek to where we left
     */
  </code></pre>
  
  <p>Thanks :)</p>
  
  <p>EDIT: Title for clarifications.</p>