stix
stix

Reputation: 1146

How can I redirect a std::ofstream to std::cout?

I'm working with some code that uses a global debug logger that is of type std::ofstream*. I would like to redirect this to std::cout since I'm using the code in realtime, as opposed to a batch method for which it was designed.

Is it possible to redirect the global std::ofstream* pointer it uses to std::cout? I know std::ofstream inherits from std::ios, which allows one to change the stream buffer using the rdbuf() method, but unfortunately it appears std::ofstream redefines the rdbuf() method, which makes the following code not compile:

gOsTrace = new std::ofstream();
gOsTrace->rdbuf(std::cout.rdbuf());

Is there another way to redirect the gOsTrace object to point to cout?

Upvotes: 6

Views: 5610

Answers (1)

David G
David G

Reputation: 96810

The rdbuf() method of the concrete IOStream stream classes hide the one declared in std::ios. You will need an explicit qualification in order to find the base class overload:

gOsTrace->basic_ios<char>::rdbuf(std::cout.rdbuf());

Upvotes: 11

Related Questions