在txt文件中写入

时间:2015-05-10 13:24:40

标签: c++ iostream

尝试在.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;

}

有什么想法吗?是因为&#34; ios :: trunc&#34; ? (我不知道这意味着什么)

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

如果你想写入文件,你应该使用ifstream。但是,由于你正在阅读文件,如果你只使用fstream,那就更好了。

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

在链接页面中,您可以阅读有关您不理解的截断的信息。

抱歉,如果我的英语不好。还在学习它。