title: WriteFile and WriteConsole
body: <p>I want to be able to use <code>WriteFile</code> or <code>WriteConsole</code> so the following 3 functions work:</p>
  
  <pre><code>&gt; Output.exe
  &gt; Output.exe &gt; File.txt &amp; type File.txt
  &gt; for /F "tokens=*" %A in ('Output.exe') do @echo %A
  </code></pre>
  
  <p>I managed to get the first two working with my current code. But now the for loop outputs: <code>The system cannot write to the specified device.</code></p>
  
  <p>I guess it doesn't like my BOM. <strong>How can I make my code work with the for loop?</strong></p>
  
  <p>Here's my current code.</p>
  
  <pre><code>DWORD   dwBytesWritten;
  DWORD   dwConMode;
  BOOL    bRedirectedToFile;
  WCHAR   str[] = L"Hello World";
  
  bRedirectedToFile = !GetConsoleMode(hStdOut, &amp;dwConMode);
  
  if (bRedirectedToFile)
  {
      LONG  zero = 0;
      DWORD pos  = SetFilePointer(hStdOut, 0, &amp;zero, FILE_CURRENT);
  
      if (pos == 0)
      {
          WORD Unicode = ((BYTE*)L"A")[0] == 0 ? 0xfffe : 0xfeff;
          WriteFile(hStdOut, &amp;Unicode, 2, &amp;dwBytesWritten, 0);
      }
  
      WriteFile(hStdOut, str, lstrlen(str) * sizeof(WCHAR), &amp;dwBytesWritten, 0);
  }
  else
  {
      WriteConsole(hStdOut, str, lstrlen(str), &amp;dwBytesWritten, 0);
  }
  </code></pre>