title: Null terminating char array in C and difference between using read and fgets
body: <p>I did something like this to read from standard input.</p>
  
  <pre><code>char *lines[50];
  char buffer[50];
  
  while((fgets(buffer, sizeof(buffer), stdin))!=NULL) {
      buffer[strlen(buffer)-1] = '\0';
      lines[i] = malloc(strlen(buffer));
      memcpy(lines[i++], buffer, strlen(buffer));
  }
  </code></pre>
  
  <p>I wanted to do something similar using the <code>read</code> system call.</p>
  
  <pre><code>while((nread=read(0, buffer, sizeof(buffer)))&gt;0) {
      buffer[strlen(buffer)-1] = '\0';
      lines[i] = malloc(strlen(buffer));
      memcpy(lines[i++], buffer, strlen(buffer));
  }
  </code></pre>
  
  <p>Resetting i to 0 and printing out the strings using <code>printf("%s", lines[i])</code>, I get correct results for the first method but do not always corresponding results in the second method. Why is this? </p>
  
  <p>Also, when reading from standard input using read, is it necessary to append a null character to the end of the string or does read do it for you?</p>
  
  <p>I directed input from a file containing the following:</p>
  
  <pre><code>This is test input
  This is another test input
  
  Not reading correctly, not reading correctly
  </code></pre>
  
  <p>When I print after getting input using <code>fgets()</code> I get the exact same as output.</p>
  
  <p>When I print after getting input using <code>read()</code> I get this:</p>
  
  <pre><code>This is test input
  This is another test input
  
  Not
  reading correctly, not reading correctly
  put
  
  No
  </code></pre>
  
  <hr>
  
  <p>ADDITIONAL NOTES:</p>
  
  <p>If I change <code>char buffer[50]</code> to something larger, the second case works, but I don't see why it shouldn't work for this particular instance. </p>
  
  <p>The problem seems to be that <code>read</code> reads all 50 characters when I redirect input from a file. Is there some way that read can read up to a newline character and stop there on each iteration? It seems to do this when receiving input from the console.</p>