views:

1406

answers:

2

I have a Windows C++ program that is doing something like:

  FILE* pf = ...;
  *stdout = *pf;    // stdout is defined in stdio.h

I'm looking for an explanation about what happens when you change the value of the stdout file handle. Is this just a way of redirecting stdout?

-cr

+6  A: 

Yes, when you change stdout, you're effectively redirecting it elsewhere. However, you should not directly assign to stdout like that. If you want to redirect stdout, you should instead use freopen().

You should never directly manipulate FILE objects - you should treat them as opaque types, and only interact with them via the functions in the <stdio> library. Jonathan lists some good reasons why.

From the C99 standard, section 7.19.3, paragraph 6:

The address of the FILE object used to control a stream may be significant; a copy of a FILE object need not serve in place of the original.

Adam Rosenfield
I didn't write this code. It's in some sample code from a toolkit vendor.
criddell
+3  A: 

If you change stdout by assignment instead of by using the tool designated (in C, freopen() as Adam Rosenfield said - and by extension, in C++), then you leave yourself open to all sorts of liabilities.

  • It is not clear that cout will also be redirected.
  • You will likely leak a file descriptor (which may not matter).
  • You might not flush the original stdout properly - losing information.
  • You might leak memory associated with the original file pointer (which again may not matter).
  • If anything closes pf, then you are liable for double-free errors (crashes).

It is far better to do the job cleanly.

(Demo code isn't necessarily written by, or even scrutinized by, the most experienced people in a vendor's coding team. If it looks dubious, that may be because it is dubious.)

Jonathan Leffler