criddell
criddell

Reputation: 14599

Changing the value of stdout in a C++ program

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

Upvotes: 3

Views: 4362

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754640

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.)

Upvotes: 4

Adam Rosenfield
Adam Rosenfield

Reputation: 400512

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.

Upvotes: 6

Related Questions