[英]Writing in a txt file
在尝试读写.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”吗? (我不知道这是什么意思)
通过ios :: app替换ios :: trunc(附加在文件末尾)
如果要写入文件,则应使用ifstream。 但是,由于您也正在读取文件,因此,如果仅使用fstream会更好。
http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
在链接的页面中,您可以了解不了解的trunc。
抱歉,如果我的英语不好。 仍在学习中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.