title: Feeding input with multiple newlines to read() in C - first character "consumed?"
body: <p>I am trying to read input from STDIN, using the system call read() function.  I am using a dynamically allocated buffer.</p>
  
  <p>I have stripped much of the details from this function - all the error-checking, all the reallocation, etc.  None of that affects the error in question.  Here is the code:</p>
  
  <pre><code>int main(void) {
      char *buff;
  
      long buf_count = 0;
      long buf_capacity = 8192;
      buff = (char *)malloc(buf_capacity);
  
      long read_count;
      while ((read_count = read(0, buff, (buf_capacity - buf_count))) != 0) {
          buf_count += read_count;
      }
  
      for (int i = 0; i &lt; buf_count; i++)
          putchar(buff[i]);
  }
  </code></pre>
  
  <p>The code from <code>long read_count;</code> to the end of the while loop is problematic.  When I read in from STDIN, I can input long strings without a problem.  But if I input a string with several newlines in it, I will be given erroneous output.  For example, if I put in the string</p>
  
  <pre><code>1
  2
  3
  </code></pre>
  
  <p>with all of its newlines, then I will receive as output only this.</p>
  
  <pre><code>3
  </code></pre>
  
  <p>If I put in the string</p>
  
  <pre><code>12345
  
  </code></pre>
  
  <p>with that extra newline (there are two), then I will get something like this.</p>
  
  <pre><code>
  2345
  </code></pre>
  
  <p>... hence the title.
  Neither of these behaviors are what I want, of course.  And I know that the problem is with my use of read(), for if I replace the code that calls read() with something like:</p>
  
  <pre><code>int ch;
  int i = 0;
  while ((ch = getchar()) != EOF)
  {
      buff[i++] = ch;
  }
  buf_count = i;
  </code></pre>
  
  <p>...then the output will be as expected.  If I put in 1 2 3 with newlines on each number, it will give me all of the string with numbers and newlines, exactly as I typed it.</p>
  
  <p>What have I done wrong?</p>