I have a list of names and I want to write them to file called (newfile) and then push them in vector and then i want to add a name to a list so i will push it in the same vector and then iam trying to write again the update list in the same file. how can i delete the previous lines in the file and write a new lines.the other thing when i want to compare new name if its exists in the list and when i check with the vector it always check with the original list. Here is my codes for both functions.Please can any one help.Thanks
void loadfile(){
ifstream myfile;
string line;
int a=0;
myfile.open("newfile.txt");
if (myfile.is_open())
{
// Read the file until it's finished, displaying lines as we go.
while (!myfile.eof())
{
getline(myfile, line, '\n'); // getline reads a line at a time
residents.push_back(line);
a++;
}
myfile.close();
}
else // Some kind of error opening the file
{
cout << "ERROR: Could not open the newfile: " <<myfile << endl;
exit(1);
}
}
void UpdateFile(){
ofstream myfile;
myfile.open("newfile.txt");
if (myfile.is_open())
{
for (int a=0; a<(residents.size()); a++)
myfile << residents[a] << endl;
myfile.close();
}
else
{
cout << "ERROR: could not open file: " << "newfile.txt" << endl;cout "If absent, please create an EMPTY dat file named " << "newfile.txt" << " in directory." << endl;
}
}