Csi
Csi

Reputation: 526

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)

Upvotes: 1

Views: 126

Answers (2)

mazabin
mazabin

Reputation: 11

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.

Upvotes: 1

user4624062
user4624062

Reputation:

Repalce ios::trunc by ios::app (append at the end of file)

Upvotes: 3

Related Questions