[英]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.