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
Program to append to the contents of a file
#include <iostream.h>
#include <fstream.h>
int main(void)
{
string 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;
} |