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?

Quentin
  • 62,093
  • 7
  • 131
  • 191
stix
  • 1,140
  • 13
  • 36
  • 9
    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. – Martin York Aug 06 '15 at 21:02
  • std::ios::tie? http://www.cplusplus.com/reference/ios/ios/tie/ – Severin Pappadeux Aug 06 '15 at 21:02
  • 2
    @SeverinPappadeux, All that does is flush it occasionally. For example, `std::cin` flushes `std::cout` when there's an input operation. – chris Aug 06 '15 at 21:04
  • 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... – stix Aug 06 '15 at 21:07
  • Your sample code is illegal, `new` gives a pointer but you then use `.` on it – M.M Aug 06 '15 at 23:31

1 Answers1

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());
David G
  • 94,763
  • 41
  • 167
  • 253
  • 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. – stix Aug 07 '15 at 17:04