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
?
Yes it is. The original code has a memory leak if an exception is thrown while processing (*fp << "Hello World" << std::endl).
I/O Redirection in C++ For Example, to redirect the stdout to say a textfile, we could write : freopen ("text_file. txt", "w", stdout);
In order for us to append to a file, we must put the ofstream() function in append mode, which we explain in the next paragraph. With the full line, ofstream writer("file1. txt", ios::app);, we now create a connection to open up the file1. txt file in order to append contents to the file.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With