title: Why does stdout need explicit flushing when redirected to file?
body: <p>The behaviour of <code>printf()</code> seems to depend on the location of <code>stdout</code>.</p>
  
  <ol>
  <li>If <code>stdout</code> is sent to the console, then <code>printf()</code> is line-buffered and is flushed after a newline is printed.</li>
  <li>If <code>stdout</code> is redirected to a file, the buffer is not flushed unless <code>fflush()</code> is called.</li>
  <li>Moreover, if <code>printf()</code> is used before <code>stdout</code> is redirected to file, subsequent writes (to the file) are line-buffered and are flushed after newline.</li>
  </ol>
  
  <p>When is <code>stdout</code> line-buffered, and when does <code>fflush()</code> need to be called?</p>
  
  <h3>Minimal example of each:</h3>
  
  <pre><code>void RedirectStdout2File(const char* log_path) {
      int fd = open(log_path, O_RDWR|O_APPEND|O_CREAT,S_IRWXU|S_IRWXG|S_IRWXO);
      dup2(fd,STDOUT_FILENO);
      if (fd != STDOUT_FILENO) close(fd);
  }
  
  int main_1(int argc, char* argv[]) {
      /* Case 1: stdout is line-buffered when run from console */
      printf("No redirect; printed immediately\n");
      sleep(10);
  }
  
  int main_2a(int argc, char* argv[]) {
      /* Case 2a: stdout is not line-buffered when redirected to file */
      RedirectStdout2File(argv[0]);
      printf("Will not go to file!\n");
      RedirectStdout2File("/dev/null");
  }
  int main_2b(int argc, char* argv[]) {
      /* Case 2b: flushing stdout does send output to file */
      RedirectStdout2File(argv[0]);
      printf("Will go to file if flushed\n");
      fflush(stdout);
      RedirectStdout2File("/dev/null");
  }
  
  int main_3(int argc, char* argv[]) {
      /* Case 3: printf before redirect; printf is line-buffered after */
      printf("Before redirect\n");
      RedirectStdout2File(argv[0]);
      printf("Does go to file!\n");
      RedirectStdout2File("/dev/null");
  }
  </code></pre>