How can I redirect a std::ofstream to std::cout?
Asked Answered
C

1

6

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?

Calamite answered 6/8, 2015 at 20:57 Comment(5)
Does the logger have to use std::ofstream* Can it not be the more generic std::ostream*. Then all you to do is make an assignment to this pointer with the new stream.Conversation
std::ios::tie? cplusplus.com/reference/ios/ios/tieInspirational
@SeverinPappadeux, All that does is flush it occasionally. For example, std::cin flushes std::cout when there's an input operation.Flaminius
Unfortunately, because it's not my code (I'm just linking against it and have limited ability to make changes), I am reluctant to change the logger type, especially given that it is a global used in many places, so the short answer is no, the logger can't be the more generic std::ostream...Calamite
Your sample code is illegal, new gives a pointer but you then use . on itMadeup
B
11

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());
Belldas answered 6/8, 2015 at 22:2 Comment(1)
Thanks! This works. It should be noted though, that it won't actually redirect to std::cout unless the ofstream successfully opens a file for writing. I.e. the default constructor as in my code will not redirect.Calamite

© 2022 - 2024 — McMap. All rights reserved.