Reputation: 7
I would like to write to a text file from a class that has a ofstream as member. How is it done? Why doesnt the below work?
#include <fstream>
class A {
public:
A(char const* file);
A(A&);
void operator = (A&);
void writeTofile();
std::ofstream stream;
};
A::A(char const* file): stream(file)
{
stream.open(file);
stream << "Hello World!" << std::endl;
stream.close();
}
void A::writeTofile()
{
stream << "Hello Again!" << std::endl;
}
int main()
{
char const* file = "foo.txt";
A a = A(file);
a.writeTofile();
return 0;
}
Upvotes: 0
Views: 509
Reputation: 96810
You have two problems:
You're calling close()
on a file stream that is needed for further input.
The constructor of your A
class opens the file, writes "Hello, World"
to standard output, and then closes the file. When you call writeToFile()
afterwards, the text can't be written to the file because it has already been closed.
You don't need to explicitly call close()
on a file stream any way, since the stream's destructor will close the file automatically when the stream goes out of scope. There's no need to do it manually unless you want to open a file with a different name.
Streams cannot be copied.
This code here:
A a = A(file);
Performs copy-initialization. It is unlike direct-initialization (A a(file)
) in that it initializes an object by copying the right side of its initializer. The constructor chosen to perform this copy depends on the type of the righthand side and the availability of viable constructors.
Normally the copy-constructor would be used for such a copy (the compiler provides one for you by default), but since you provided your own constructor A::A(A&)
, it disabled the creation of a compiler-generated copy-constructor. A temporary instance of A
(A(file)
) cannot be converted to a reference to an A
(lookup references in C++). The same goes for the other constructor you provided, there's no conversion from A
to const char*
.
If you remove the custom constructor you will still find an error. This is because C++ IOStream objects cannot be copied (they have a "deleted" copy-constructor). Therefore, since std::ofstream
is a member of a class, that class too has a deleted copy-constructor.
There are two solutions:
A a(file)
)Upvotes: 1
Reputation: 58
Your problem is that you close the stream in the constructor of A, so when it is accessed in writeToFile()
, the stream is closed and is not accepting any more input.
Try moving stream.close();
to the destructor, and you should be fine:
A::~A()
{
stream.close();
}
Upvotes: 0
Reputation: 1342
You closed the stream in the contructor of A, so it is not accepting any more input
A::A(char const* file): stream(file)
{
...
stream.close();
}
Try moving it to the destructor:
A::~A()
{
stream.close();
}
Upvotes: 0