Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Test if a std::fstream is open

2 views
Skip to first unread message

Rune Allnor

unread,
Feb 7, 2010, 3:46:25 AM2/7/10
to
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::ofstream 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

Rune Allnor

unread,
Feb 7, 2010, 6:50:16 AM2/7/10
to
On 7 Feb, 09:46, Rune Allnor <all...@tele.ntnu.no> wrote:

> 2) How can one test whether the std::xfstream is already open?

Never mind, I eventually found the std::fstream::is_open() member
function.

Rune

0 new messages