简体   繁体   中英

Writing in a txt file

In trying to read and write datas in a .txt file. 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" ? (i dunno what it means)

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

If you want to write in file you should use ifstream. However, since you are reading file too it would be better, if you would use just fstream.

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

In linked page you can read about trunc, which you don't understand.

Sorry, if my English is bad. Still learning of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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