I'm currently working with std::fstream
and have the following class:
(Note that the file is opened on constructor and should stay open during all read / write operation, only close when destructed).
MyFileClass
{
public:
MyFileClass( const std::string& file_name ) { m_file.open( file_name ) };
~MyFileClass() { m_file.close() };
bool read( std::string& content );
bool write( std::string& data );
private:
std::fstream m_file;
}
Now I have some sample code:
MyFileClass sample_file;
sample_file.write("123456");
sample_file.write("abc");
Result will be "abc456" because when the stream is open and we're writing with truncate mode it will always write on top of what's currently in there.
What I would like to have is to clean up everytime before we write so at the end I'll have only what's newest in there, in this case "abc".
And the current design is if the file is not there, it will be created only on write, but not on read (read will return error code if file is not present).
My write function is:
bool
MyFileClass::write( const std::string& data )
{
m_file.seekg( 0 );
if ( !m_file.fail( ) )
{
m_file << data << std::flush;
}
return m_file.fail( ) ? true : false;
}
Is there any way to clear the current content of the file before flushing the data?