title: Does printf always flush the buffer on encountering a newline?
body: <p>My machine is running ubuntu 10.10, and I'm using the standard gnu C library. I was under the impression that printf flushed the buffer if there was a newline described in the format string, however the following code repeatedly seemed to buck that trend. Could someone clarify why the buffer is not being flushed.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;sys/wait.h&gt;
  
  int main()
  {
      int rc;
      close(1);
      close(2);
      printf("HI 1\n");
      fprintf(stderr, "ERROR\n");
  
      open("newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600);
      printf("WHAT?\n");
      fprintf(stderr, "I SAID ERROR\n");
  
      rc = fork();
  
      if (rc == 0)
      {
          printf("SAY AGAIN?\n");
          fprintf(stderr, "ERROR ERROR\n");
      }
      else
      {
          wait(NULL);
      }
  
      printf("BYE\n");
      fprintf(stderr, "HI 2\n");
  
      return 0;
  }
  </code></pre>
  
  <p>The contents of newfile.txt after running this program is as follows.</p>
  
  <pre><code>HI 1
  WHAT?
  SAY AGAIN?
  BYE
  HI 1
  WHAT?
  BYE
  </code></pre>