0

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;
	}
	}
2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
0

>> how can i delete the previous lines in the file and write a new lines

You will have to rewrite the entire file. It's not possible to insert new lines somewhere in the middle of a text file without rewriting it. You already have the vector, so just interate through it and write the strings to the file.

As for your other question -- can't say what's wrong from the code snippet you posted. Will need to see the entire program.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.