从/向文件读/写

时间:2016-05-13 22:42:23

标签: c++

我正在开发一个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();
}

1 个答案:

答案 0 :(得分:0)

因为您反复打开文件,所以反复覆盖内容。

您可能想要在for循环外打开一次流并通过引用传递它。