title: How to write redirected output to file inside loop in C?
body: <p>I am writing a C program on unix which should redirect it's output to the file, and write to it some text every second in infinite loop:</p>
  
  <pre><code>#include &lt;fcntl.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(void) {
      int outDes = open("./output.txt", O_APPEND | O_WRONLY);
      dup2(outDes, 1);
      while(1) {
          printf("output text\n");
          sleep(1);
      }
  }
  </code></pre>
  
  <p>But it writes nothing to the output file. I tried to change the 'while' loop for 'for' with 10 loops, and I found that it writes all 10 lines to the file at once after the series ends. It is not very good for me, while I need to have an infinite loop.</p>
  
  <p>When I'm not redirecting output, it is all ok, and new line appears every second on terminal. </p>
  
  <p>I also tried to put one </p>
  
  <pre><code>printf("text\n");
  </code></pre>
  
  <p>before redirecting output to the file. Then the program wrote the lines to the file in real time, which is good, but wrote there the first (non redirected) line too. I don't want this first line in my output file, I don't understand how it could be written into file when output was not redirected yet (maybe redirect remained there since last run?), and how it could cause that the lines are suddenly written in real time.</p>
  
  <p>Can anyone explain me how does it work?</p>