Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close ofstream after assigning to ostream?

I can do

std::ostream& out = condition ? std::cout : std::ofstream(filename);

but how do I close in case of out = std::ofstream(filename)?

like image 370
downforme Avatar asked Feb 12 '23 21:02

downforme


2 Answers

Forget close for a while, your code:

std::ostream& out = condition ? std::cout : of.open(filename);

would NOT compile to begin with. std::ofstream::open() does NOT return the stream — it returns void. You could fix this as:

std::ostream& out = condition ? std::cout : (of.open(filename), of);

Now coming back to closing the stream, well, you don't have to, because when the stream object goes out of scope (i.e when the destructor gets called), the destructor will close the file stream. So it is done automatically for you — well, in 99.99% cases, unless you're doing something unusual in which case you want to close it explicitly!

like image 114
Nawaz Avatar answered Feb 15 '23 11:02

Nawaz


As I understood you want to close file stream using out?

You don't need to close it explicitly. std::fstream is RAII object, so it will close an opened file automatically at the end of enclosing scope.

And of course, you can always cast out if you really need to close the file just now:

if( ptr = dynamic_cast<std::ofstream*>(out) ) {
    ptr->close();
}
like image 31
Ivan Grynko Avatar answered Feb 15 '23 11:02

Ivan Grynko