Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 244
stix Avatar asked Aug 06 '15 20:08

stix


People also ask

Is cout an Ofstream?

Yes it is. The original code has a memory leak if an exception is thrown while processing (*fp << "Hello World" << std::endl).

How do you write to stdout to a file in C++?

I/O Redirection in C++ For Example, to redirect the stdout to say a textfile, we could write : freopen ("text_file. txt", "w", stdout);

Does Ofstream append to file?

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.


1 Answers

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());
like image 152
David G Avatar answered Oct 08 '22 07:10

David G