简体   繁体   中英

Reading/ Writing from/to a file

I am working on an OOP project and I need to write into a file and I faced a problem that each time I do it the file is over written with only one object. How can I make it to write data of all the objects? I tried this but didnt work.

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();
}

Because you're opening the file again and again you overwrite the contents again and again.

You probably want to open the stream outside the for loop once and pass it by reference.

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