【发布时间】:2017-02-20 08:32:34
【问题描述】:
我目前正在使用std::fstream 并有以下课程:
(请注意,文件是在构造函数上打开的,并且应该在所有读/写操作期间保持打开状态,只有在被破坏时才会关闭)。
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;
}
现在我有一些示例代码:
MyFileClass sample_file;
sample_file.write("123456");
sample_file.write("abc");
结果将是“abc456”,因为当流打开并且我们使用截断模式写入时,它总是会在当前的内容之上写入。
我想要的是每次在我们写之前都要清理一下,所以最后我只会有最新的东西,在这种情况下是“abc”。
当前的设计是如果文件不存在,它只会在写入时创建,而不是在读取时创建(如果文件不存在,读取将返回错误代码)。
我的写函数是:
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;
}
有什么方法可以在刷新数据之前清除文件的当前内容?
【问题讨论】:
-
C++ 不提供截断已打开文件的方法。见stackoverflow.com/questions/20809113/…
-
除了重新打开文件,没有。
标签: c++ file-io iostream fstream