Howard said:
Well, that's true, given the actual design of the filestream. But it's
certainly *concievable* to envision a filestream class design that
maintained the filename as a member which could be queried. Of course, that
would mean using something like "is.name", not just "is", but it's
possible.
Possible it certainly is, in fact its trivial. Would it be desireable,
probably not. The issue here is why provide access to a provided constant
string filename parameter? The OP can just as well pass a variable to the
ifstream and then manipulate the variable without bothering the ifstream or
object. I would think that efficiency is a primary concerns in the design of
such a mutating object.
Well, that's a bit over-dramatic, in my opinion. Nobody said anything about
changing the name while the stream is open, did they? And even if one were
able to attempt to change the variable while the file was open, that doesn't
mean that the world would come crashing down. It *might* screw up a given
file system if the filename were changed while the file was open, but the OS
could (and likely does) forbid that anyway, which would mean that even if
the filestream class allowed the attempt to change it, the actual action
would fail in that instance, most likely with an exception of some sort,
which it could catch as needed.
-Howard
Which brings us back to the crux of the problem. I can understand checking a
file stream's error condition bits, but why a *supplied* parameter?
#include <iostream>
#include <fstream>
#include <string>
class FileStream
{
const std::string m_filename;
std::ifstream m_ifs;
std::string m_sdata;
public:
FileStream(std::string s) : m_filename(s), m_ifs(), m_sdata("") { }
~FileStream() { }
std::string getFilename() const
{
return m_filename;
}
const std::string getData()
{
m_ifs.open(m_filename.c_str());
if (!m_ifs)
{
m_sdata = "error opening file " + m_filename;
return m_sdata;
}
std::getline(m_ifs, m_sdata);
return m_sdata;
}
};
int main()
{
std::string s("data.dat");
FileStream fs(s);
std::cout << fs.getFilename() << std::endl;
std::cout << fs.getData();
return 0;
}
output:
data.dat
the only data string
whats wrong with...
int main()
{
std::string s("data.dat");
FileStream fs(s);
std::cout << s << std::endl;
std::cout << fs.getData();
return 0;
}
and forego having to provide the getFilename() member function?