title: Unix HEAD command implementation in C fails on larger lines
body: <p>I am currently implementing the Unix <code>HEAD</code> command with C and using only system functions. So far, it works perfectly on files, which have lines with <strong>less</strong> length than the one that I specified for my <code>buffer</code>:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;fcntl.h&gt;
  
  #define LINES_TO_READ 10
  #define BUFF_SIZE 4096
  
  int main(int argc, char const *argv[]) {
      for (ssize_t i = 1; i &lt; argc; i++) {
          const char *filename = argv[i];
  
          int fd = open(filename, O_RDONLY);
  
          if (fd &lt; 0) {
              perror("open");
              return -1;
          }
  
          char ch, buffer[BUFF_SIZE];
          size_t index = 0, lines = 1;
          ssize_t rresult, wresult;
  
          // Read the file byte by byte
          while ((rresult = read(fd, &amp;ch, 1)) != 0) {
              if (rresult &lt; 0) {
                  perror("read");
                  return -1;
              }
  
              // Check if the current character is a new line (the line ends here)
              if (ch == '\n') {
                  buffer[index] = ch;
                  buffer[index + 1] = '\0';
                  ch = 0;
                  index = 0;
  
                  // Print the line
                  wresult = 0;
                  ssize_t buffer_length = strlen(buffer);
                  while (wresult != buffer_length) {
                      ssize_t res = write(STDOUT_FILENO, buffer + wresult, buffer_length - wresult);
  
                      if (wresult &lt; 0) {
                          perror("write");
                          return -1;
                      }
  
                      wresult += res;
                  }
  
                  // Stop if we read 10 lines already
                  if (lines == LINES_TO_READ) {
                      break;
                  }
  
                  lines++;
              } else {
                  buffer[index++] = ch;
              }
          }
  
          if (close(fd) &lt; 0) {
              perror("close");
              return -1;
          }
      }
  
      return 0;
  }
  </code></pre>
  
  <p>And it works on files, which have a line length with less than <code>BUFF_SIZE</code> (as now set, <code>4096</code>).</p>
  
  <p>How to avoid this and make it work for whatever the line length is?</p>