How to close ofstream after assigning to ostream?

对着背影说爱祢 提交于 2019-12-10 18:07:40

问题


I can do

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

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


回答1:


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();
}



回答2:


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!



来源:https://stackoverflow.com/questions/23919912/how-to-close-ofstream-after-assigning-to-ostream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!