title: How to freopen() both stdout and stderr into a single output file under Windows
body: <p>I've got a Windows Win32/GUI application that sometimes prints interesting output to both <code>stdout</code> and <code>stderr</code>, so what I'd like to do is capture that output into a file for review after the application has exited.</p>
  
  <p>The problem is, I can successfully call <code>freopen_s()</code> to capture <code>stdout</code> output into a file, <strong>or</strong> I can use it to capture <code>stderr</code> output into a file, but trying to do both at once yields only a truncated file with munged data.</p>
  
  <p>Below is a simple program that reproduces the problem; if I comment out either one of the two <code>freopen_s()</code> calls, then I get the expected output in the <code>blah.txt</code> file that is created (i.e. one of the two text lines), but what I'd like is to end up with a <code>blah.txt</code> containing both text lines.</p>
  
  <p>Is that possible under Windows?  I could fall back to creating two different files (e.g. <code>blah_stdout.txt</code> and <code>blah_stderr.txt</code>) but I'd rather not, since then I'd have to manually reconstruct the relative order in which stdout and stderr output was generated.</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
     const char * outFileName = "blah.txt";
     FILE * junk1 = NULL, junk2 = NULL;
     if (freopen_s(&amp;junk1, outFileName, "w", stdout) != 0) abort();
     if (freopen_s(&amp;junk2, outFileName , "w", stderr) != 0) abort();
     printf("This text was printed to stdout and should appear in blah.txt\n");
     fprintf(stderr, "This text was printed to stderr and should appear in blah.txt\n");
     return 0;
  }
  </code></pre>