试图读取和写入.txt文件中的数据。阅读工作正常,但每次我尝试写入时,都会覆盖之前写入的内容。只有最后写的东西仍然存在。在txt文件中写入
void trace(Board& tab)
{
ofstream file("trace.txt", ios::in | ios::trunc);
Position pos(0,0);
Position& p = pos;
if(file)
{
for (int i = 0; i < tab.getNbline(); i++)
{
for(int j = 0; j < tab.getNbcolumn(); j++)
{
p.setposition(i,j);
if(i == tab.getEmptyline() && j == tab.getEmptycolumn())
{
file << setw(tab.getNbcolumn()) << tab.getValue(p);
if (j == tab.getNbcolumn()-1)
{
file << endl;
}
}
else
{
file << setw(tab.getNbcolumn()) << tab.getValue(p);
if (j == tab.getNbcolumn()-1)
{
file << endl;
}
}
}
}
file.close();
}
else cerr << "Cannot open file" << endl;
}
void trace_message(string str)
{
ofstream file("trace.txt", ios::in | ios::trunc);
if(file)
{
file << str << endl;
file.close();
}
else cerr << "Cannot open file" << endl;
}
任何想法?是否因为“ios :: trunc”? (我不知道这是什么意思)
这里回答。 http://www.cplusplus.com/doc/tutorial/files/ – 911