Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ostream and ofstream conversions

Tags:

People also ask

Is Ostream an ofstream?

ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.

What is Ostream in C++?

ostream class − The ostream class handles the output stream in c++ programming language. These output stream objects are used to write data as a sequence of characters on the screen. cout and puts handle the out streams in c++ programming language.

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).

Is ofstream a header file?

Explanation: In the above program, the header file fstream is imported to enable us to use ofstream and ifstream in the program. Then another header file iostream is imported to enable us to use cout and cin in the program. Then the standard namespace std is used.


My code has an ostream object that is accumulated by various modules and ultimately displayed to the console. I'd like ALSO to write this ostreamobject to a file, but do I have to rewrite all of that code using an ofstream object instead, or is there a way to convert one to the other (perhaps via a stringstream?)

For example, many of my existing functions look like

ostream& ClassObject::output(ostream& os) const
{
    os << "Details";
    return os;
}

Can I call this function with an ofstream object as the argument and have that ofstream object accumulate information instead?