Test if a std::fstream is open

R

Rune Allnor

Hi all.

Suppose I have a std::fstream, that my application needs to
close and start over (e.g. a log file that needs to be closed and a
new one started, every now and then).

I have attempted to do things along such lines as:

std::eek:fstream log;

if (time_to_start_new_log_file())
{
std::string fname = new_log_file_name();

// Troublesome test ////////////////////////
if (log) // Test if the log file is already open

{
log.close();
}
log.open(fname.c_str());
}

This does not work as intended.

I always interpreted the if(log) test as a test if the file
is open, but can't find anything definitive in Stroustrup's
"The C++ Programming Language".

However, in his "Programming. Principle and Practice
using C++" Stroustrup says about the test (p. 385)
that is checks whether the opening operation resulted
in the stream being "... in a good() state:

ifstream if(name);
if (!if) // oops! we couldn't open that file ... "

In other words, it seems the test if(log) returns the
value of the std::ios_base::goodbit, which is a completely
different thing than the open/close state.

So:

1) What does the test if(log) above actually test for?
2) How can one test whether the std::xfstream is already open?

And for good measure,

3) Is there anything about closing files in the standard
std::xfstream destructors? Or do I need to to add some kind of

if(*this,isOpen()) this->close();

test in the desctructors of classes derived from std::xfstream?

Rune
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top