Return to Topic Menu | Computer Science Main Page |  | 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."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?";
     getline(cin,dummy);"name_age.dat",ios::app);    // open file for appending
     assert (! ));     

     for(i=1; i<=number; i++)
         cout<<"Enter the name:  ";
         cout<<"Enter age:  ";

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

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