i'm trying to make a class to control a file stream: the fstream is one of the members and the constructor opens the stream for read/write.
however, once the constructor has run, the file is no longer open. this means i would have to reopen the fstream in each member function. is this by design? my professor told me it should be staying open till being closed or destructed.
#include <fstream>
#include <iostream>
usingnamespace std;
class rafile {
fstream iostream;
public:
rafile() { rafile("test.txt"); };
rafile(constchar *filename);
void testwrite();
};
rafile::rafile(constchar *filename) {
iostream.open(filename, ios::out | ios::in);
iostream << "constructor test" << endl; //this works, if the file exists
}
void rafile::testwrite() {
//iostream shows as good here, but not open
iostream << "test?" << endl; //this doesn't work
//obviously iostream is bad here, a flag has been thrown
}
int main() {
rafile scribe;
scribe.testwrite();
}
You're asking for trouble calling your stream iostream when you've also used usingnamespace std above it and included <iostream>.
The problem is this liine:
rafile() { rafile("test.txt"); };
That creates a temporary rafile which calls rafile::rafile(const char *filename), then is destroyed when it leaves. And your default rafile() doesn't do anything.
rafile() { rafile("test.txt"); };is not what you think it is. This creates a new object in the constructor that gets destroyed immediately. There is no way to call one constructor from another. You could either make a function "open(const char*)" and call it from both constructors, or add a default value to the second constructor. too slow..