I have ifstream and an ofstream that in runtime might be opened or not (depends on what the user enters in command line. i declare the variables anyway, and i have a method that opens the stream if needed.
my problem is at the end of the program i don’t know if i need to close them or not.
Is there anyway in c++ to know if a stream was opened? Like in Java you can give a stream the null value and then ask if its null (it means that it was never opened)..
Is it ok to close a stream that was never opened?
this is the code:
int main(int argc, char* argv[]) {
static std::ifstream ifs;
static std::ofstream ofs;
//might or might not open the streams:
OpenStreams(ifs,ofs,argc-1,argv);
........
//here i would like to close the streams at the end of the program
//or not (if they were not opened
return 0;
}
Thanks!
No
closecall needed – the streams close itself when they are open when they are destroyed. Also, thestaticthere looks suspicious.mainis called only once, so it doesn’t have any effect here (apart from pedantic standardese differences that don’t matter here, i think…. Definitely not in the case shown).That said, you can just call
closeif a stream is not opened –(I was looking at the spec forclosewill return a null pointer if it wasn’t open.basic_filebuf<>::close– the file streams’sclosereturnsvoid).File-streams can also handle non-open streams: If the stream wasn’t open, it sets the
failbit. You can check for that usingfail()(which tests whehter the failbit or badbit is set). But there isis_openanyway to test whether the stream is open, but you don’t need it for the above reasons.