Open your output file using the same name as when you opened it for input. If you are only going to write new elements to the file, then you would want to open the file in append mode so that new data gets added to the end of the existing file. However, it can be just as easy to simply overwriting the contents completely with the data (old list plus any new elements). This would be needed especially if you ever decided to implement deletion of elements to your program. As an example, the following program read in a bunch of integers into a vector, display them to the user, asks for a new integer from the user which will be added to the vector, and rewrites the file with the contents of the vector:
Code:
#include <fstream>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<int> intVect;
ifstream in("Data.Txt");
// Read through file and store data into vector.
copy(istream_iterator<int>(in),istream_iterator<int>(),back_inserter(intVect));
in.close();
// Output contents of vector to screen.
copy(intVect.begin(),intVect.end(),ostream_iterator<int>(cout," "));
// Ask user for new integer to store.
int val;
cout << "\nEnter new integer: ";
cin >> val;
intVect.push_back(val);
// Write vector back to file overwritting existing contents.
ofstream out("Data.Txt");
copy(intVect.begin(),intVect.end(),ostream_iterator<int>(out," "));
out.close();
return 0;
}
Assuming Data.Txt start out containing "5 13 24" then sample output could look like this:
Code:
5 13 24
Enter new integer: 43
After running a second time:
Code:
5 13 24 43
Enter new integer: 64
After running a third time:
Code:
5 13 24 43 64
Enter new integer: 31
Etc... etc... as you see all the existing data is still there because we write everything back out to the file every time. Now... for large amounts of data you may not want to do this.