从文件读取/向文件写入

Reading/ Writing from/to a file

本文关键字:文件 读取      更新时间:2023-10-16

我正在处理一个OOP项目,我需要写入一个文件,每次写入时都会遇到一个问题,即文件只被一个对象重写。如何才能写入所有对象的数据?我试过了,但没用。

virtual void save(ofstream outfile) = 0;`// the base class
void AND2::save(ofstream outf) //derived
{
    outf.open("test.txt");
    outf << Component::getype() << " ";
    outf<< Component::getid() << " ";
    outf << Component:: graphicsinfomration().x1 << " ";
    outf<< Component::graphicsinfomration().x2 << " ";
    outf << graphicsinfomration().y1 << " ";
    outf << graphicsinfomration().y2 << " ";
    outf << endl;
    outf.close();
}
else          
{
    ofstream outf;
    for (int i = 0; i < (pApp->getcompcount()); i++)
    {
        //ask user to enter text name
        c[i]->save( outf);
    }
    pOut->ClearStatusBar();
}

因为您一次又一次地打开文件,所以会一次又一遍地覆盖内容。

您可能希望在for循环之外打开一次流,然后通过引用传递它。