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: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
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: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