I can do
std::ostream& out = condition ? std::cout : std::ofstream(filename);
but how do I close in case of out = std::ofstream(filename)
?
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!
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();
}
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