Reputation: 255
I have written a class for handling text files and it looks like this.
#include <fstream>
#include "String.h"
class TextFile
{
std::fstream stream;
public:
TextFile(const String& filename)
{
stream.open(filename.data(), std::ios::in | std::ios::out);
std::cout << "File opened " << filename.data() << " " << stream.is_open() << std::endl;
}
~TextFile()
{
close();
}
template <typename T>
TextFile& operator<<(const T& data)
{
stream << data;
return *this;
}
TextFile& operator<<(const String& s)
{
stream << s.data();
return *this;
}
template <typename T>
TextFile& operator>>(T& data)
{
stream >> data;
return *this;
}
void close()
{
if (stream.is_open())
stream.close();
}
};
I intentionally used fstream and not ifstream or ofstream, because at the time of opening the file, I do not yet know whether I will write to it or read from it. I would then use the TextFile in one of two ways:
TextFile file("somefile.txt")
file << "hello world";
file.close();
TextFile file("somefile.txt")
file >> someString;
file.close();
My issue with this is that it won't open the file, unless it already exists. It only does that if I add std::ios::app to the arguments, but I don't want to append. I want the file to be created, if it doesn't exist, and overwrite its contents if it already does. How do I do this right?
Upvotes: 0
Views: 67