fstream question

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.

(i'm using g++ from MinGW, gcc 4.5.0)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <fstream>
#include <iostream>

using namespace std;

class rafile {
	fstream iostream;
public:
	rafile() { rafile("test.txt"); };
	rafile(const char *filename);
	void testwrite();
};

rafile::rafile(const char *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 using namespace 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..
Last edited on
aha, thanks... and this is just a test script, my actual project uses different names. thanks for the pointer though
1
2
3
4
5
6
7
8
9
10
11
class rafile {
	
fstream files;
public:
	rafile()
	{ 
		files("deneme.txt"); // How do I need to create.
	}
	rafile(const char *filename);
	void testwrite();
};


1
2
3
4
5
6
7
8
class rafile {
	
fstream files;
public:
    rafile() : files("deneme.txt"){
         //...
   }
};
Is the way to call a constructor of a member.
Topic archived. No new replies allowed.