写在一个txt文件中

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::trunc 替换为 ios::app(追加到文件末尾)

如果你想写入文件,你应该使用 ifstream。但是,由于您也在读取文件,所以如果您只使用 fstream 会更好。

http://www.cplusplus.com/reference/fstream/ofstream/ofstream/

在链接页面中,您可以阅读有关 trunc 的内容,但您不了解。

对不起,如果我的英语不好。还在学习中。