Return to Topic Menu | Computer Science Main Page | MathBits.com  | Terms of Use | Resource CD

 

Adding Data to the End of a File

Inserting data somewhere in a sequential file would require that the entire file be rewritten.  It is possible, however, to add data to the end of a file without rewriting the file.  Adding data to the end of an existing file is called appending.    

fout.open("filename.dat", ios::app)  //open file for appending

//add names and ages to an existing file
#include <iostream.h>
#include <fstream.h>

If the file you open for appending does not exist, the operating system creates one just as if you had opened it using ios::out mode.

int main(void)
{
     apstring name, dummy;    
     int number, i, age;
     ofstream fout;

     cout<<"How many names do you want to add?";
     cin>>number;
     getline(cin,dummy);

     fout.open("name_age.dat",ios::app);    // open file for appending
     assert (!fout.fail( ));     

     for(i=1; i<=number; i++)
     {
         cout<<"Enter the name:  ";
         getline(cin,name);
         cout<<"Enter age:  ";
         cin>>age;
         getline(cin,age);

         fout<<name<<endl;   //send to file
         fout<<age<<endl;

     }
     fout.close( );      
//close file
     assert(!fout.fail( ));
     return 0;
}