1

Is it possible (and if so, how?) to redirect stdout (and, optionally, stderr) temporarily to a file, and later recover the original stdout?

In a POSIX environment, I use dup and dup2 to store and replace STDOUT_FILENO. freopen isn't a good solution, since stdout cannot be recovered that way.

Is it possible to do this with the Windows API? I believe it is possible using the POSIX-like functions _DUP and _DUP2. Is there a solution that doesn't involve them?

Tordek
  • 10,628
  • 3
  • 36
  • 67
  • If you just want the stdout of a child process, then seems the CRT on windows has a [_popen()](http://msdn.microsoft.com/en-us/library/96ayss4b(v=vs.110).aspx) that will handle that case simply. – BrendanMcK Aug 17 '12 at 09:33
  • Hmm, actually this is awesome for a different part of the program, thanks! – Tordek Aug 17 '12 at 09:39

2 Answers2

1

On Windows, the reserved file name "CON" means the console output stream. To reattain normal STDOUT behavior on Windows, all you need do is call

freopen("CON","w",stdout);
Kaslai
  • 2,445
  • 17
  • 17
  • What if this process runs as a subprocess, and its stdout is supposed to be captured? Will CON point to the redirected stdout? – Tordek Aug 13 '12 at 00:50
  • 1
    No. This will always reroute it to the console I/O stream. I'll try Googling a method that retains the original STDOUT. – Kaslai Aug 13 '12 at 00:53
  • Is there a point as to why you want a Windows API specific solution? ``_dup()``, ``_dup2()``, and ``_fileno()`` work just fine – Kaslai Aug 13 '12 at 01:07
  • this answer should be pinned to stackoverflow, I searched for this for ~4 hours tried lots of methods this one is the only one mentioned CON magic! Thanks!!! –  Oct 09 '20 at 01:24
1

Take a look at the SetStdHandle Win32 API. Also, _dup and _dup2 are available.

EDIT

See the following StackOverflow posts.

Redirect stdout to an edit control (Win32)

practical examples use dup or dup2

Community
  • 1
  • 1
Garett
  • 16,632
  • 5
  • 55
  • 63
  • The problem with SetStdHandle is that it reroutes the output at a different level than ``freopen()`` and thus won't revert the changes. – Kaslai Aug 13 '12 at 01:06
  • Some additional searching led me to ``_get_osfhandle(_fileno(filestream))`` which will return the HANDLE to a file stream, which you can then use in ``SetStdHandle()``. Seems like a workable solution to me that only uses windows specific functionality ;) – Kaslai Aug 13 '12 at 01:13