我目前正在使用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"因为当流打开并且我们用截断模式进行书写时,它总是会写在当前所在的内容之上。
我想要的是在我们写完之前每次都要清理,所以最后我只有最新的东西,在这种情况下&#34; abc&#34;。< / p>
目前的设计是如果文件不存在,它将仅在写入时创建,但不在读取时创建(如果文件不存在,读取将返回错误代码)。
我的写作功能是:
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;
}
在刷新数据之前有没有办法清除文件的当前内容?
答案 0 :(得分:0)
能够写入文件末尾使用标志ios :: app而不是。
你的代码充满了错误:
1-你还试图将一个类字符串写入文件,这是不正确的。如果你想这样做,请使用序列化。在你的情况下,只需将其转换为常量字符串。
2-您的写入和读取函数被定义为接受字符串的引用,但是您传递了值! (通过&#34; 12345&#34;和&#34; abc&#34;)
3-为什么要寻找输入指针? (seekg)?只要你想写?!! 你可能意味着seekp()寻求输出指针;即使在这种情况下出于什么原因这样做?如果你想在最后使用ios :: app附加文本到开头文件。 如果你想在任何写操作中清除内容,那么你应该有两个文件流,一个用于读取,另一个用于写入,因此用于写入的文件流使用标志ios :: out | IOS :: TRUNC。因为ios :: trunc在读/写模式下什么都不做。
4-如果你真的想通过引用传递那么你必须在main中声明字符串对象传递给它们的值(&#34; abc&#34;和&#34; 12345&#34;对于每一个)然后传递这些写入和读取的字符串不是值。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class MyFileClass
{
public:
MyFileClass( std::string file_name );
~MyFileClass() { m_file.close(); }
bool read ( std::string content );
bool write( std::string data );
private:
std::fstream m_file;
};
MyFileClass::MyFileClass( std::string file_name )
{
m_file.open( file_name.c_str(), ios::out | ios::in | ios::app);
if(!m_file)
cout << "Failed to open file!" << endl;
}
bool MyFileClass::write( const std::string data )
{
if ( !m_file.fail( ) )
{
m_file << data.c_str() << std::flush;
}
return m_file.fail( ) ? true : false;
}
int main()
{
std::string sFile = "data.dat";
MyFileClass sample_file(sFile);
sample_file.write("123456");
sample_file.write("abc");
return 0;
}