5

I can do

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

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

downforme
  • 371
  • 2
  • 15

2 Answers2

6

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!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • @downforme: Even that will not compile. Please try to compile your code before posting. – Nawaz May 28 '14 at 19:27
  • `std::ostream& out1 = std::cout; std::ostream& out2 = std::ofstream("");` does compile – downforme May 28 '14 at 19:46
  • 1
    @downforme: No. `std::ostream& out2 = std::ofstream("");` will not compile in Standard C++. You're probably using MSVC++ (which allows such code)? – Nawaz May 28 '14 at 19:47
  • I have VS Express 2013 on Win7 32 – downforme May 28 '14 at 19:51
  • @downforme: See I told you. MSVC++ allows such code, as a compiler extension. This code, however, is not Standard C++. – Nawaz May 28 '14 at 19:53
5

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();
}
Ivan
  • 2,007
  • 11
  • 15
  • That worked. I have a base class that holds the ostream and subclasses that provide the actual stream and take care of shutdown – downforme May 28 '14 at 19:49