views:

53

answers:

2

I have inherited some really old VC6.0 code that I am upgrading to VS2008 for building a 64-bit app. One required feature that was implemented long, long ago is overriding std::cout so its output goes simultaneously to a console window and to a file. The implementation depended on the then-current VC98 library implementation of ostream and, of course, is now irretrievably broken with VS2008. It would be reasonable to accumulate all the output until program termination time and then dump it to a file. I got part of the way home by using freopen(), setvbuf(), and ios::sync_with_stdio(), but to my dismay, the internal library does not treat its buffer as a ring buffer; instead when it flushes to the output device it restarts at the beginning, so every flush wipes out all my accumulated output. Converting to a more standard logging function is not desirable, as there are over 1600 usages of "std::cout << " scattered throughout almost 60 files. I have considered overriding ostream's operator<< function, but I'm not sure if that will cover me, since there are global operator<< functions that can't be overridden. (Or can they?)

Any ideas on how to accomplish this?

A: 

what about -

#define cout MyLogger

?

shoosh
That looks like a variant on the operator<< overloading option. MyLogger would have to be of type ostream so all the existing std::cout<< usages would work, and that leaves open the question of the global operator<< functions, such as "ostream" I may end up having to give that a go, but reimplementing the ostream class wasn't on my schedule, if you get my drift!
RadlyEel
Undefined symbol `std::MyLogger`, i'm afraid.
MSalters
+2  A: 

You could write a custom stream buffer and attach it to cout with cout.rdbuf(). Your custom stream buffer would then tee the data to cout's original stream buffer and to a stream buffer stolen from an appropriate ofstream.

ofstream flog("log.txt");
teebuf tb(flog.rdbuf(), cout.rdbuf());
cout.rdbuf(&tb);

For your teeing stream buffer you can get an inspiration from this page.

avakar
Yes, that looks promising. I should know pretty soon if that works for me. Thanks.
RadlyEel
That works. I don't have enough rank here to give you an "UP" response, but please accept my thanks.
RadlyEel