简体   繁体   English

写入txt文件

[英]Writing in a txt file

In trying to read and write datas in a .txt file. 在尝试读写.txt文件中的数据时。 Reading is working fine, but each time i try to write, program overwrite on what it wrote before. 读取效果很好,但是每次我尝试编写时,程序都会覆盖之前的内容。 Only the last thing written remains. 只剩下最后写的东西。

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;

}

Any idea ? 任何想法 ? Is it because of "ios::trunc" ? 是因为“ ios :: trunc”吗? (i dunno what it means) (我不知道这是什么意思)

通过ios :: app替换ios :: trunc(附加在文件末尾)

If you want to write in file you should use ifstream. 如果要写入文件,则应使用ifstream。 However, since you are reading file too it would be better, if you would use just fstream. 但是,由于您也正在读取文件,因此,如果仅使用fstream会更好。

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

In linked page you can read about trunc, which you don't understand. 在链接的页面中,您可以了解不了解的trunc。

Sorry, if my English is bad. 抱歉,如果我的英语不好。 Still learning of it. 仍在学习中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM