C ++ Delete line from .txt file

I am trying to remove a line from my .txt file. The file contains all the information about the account.

The line says "newAccount" and is created when the account is created. I use this to start downloading the tutorial the first time I log in. After the lesson, I want to delete this line so that in the next entry you do not receive a tutorial.

Here is the code snippet: (doesn't work)

void loginScreen(string user){ system("CLS"); cout << "Hello " + user << endl; ifstream file(user + ".txt"); string line1; getline(file, line1); // Begin reading your stream here string line2; getline(file, line2); if(line2 == "newAccount"){ cout << "Your account is new"; char cUser[200]; strcpy_s(cUser, user.c_str()); std::ofstream newFile( user + ".txt.new" ); // Do output...!!!!!!! newFile << line1; newFile.close(); if ( newFile ) { remove( cUser + ".txt" ); rename( cUser + ".txt", cUser + ".txt" ); } else { std::cerr << "Write error on output" << std::endl; } } } 

EDIT:

I edited my code and it still does not work:

 const string oldFileName(user + ".txt"); const string newFileName(user + ".txt.new"); std::ofstream newFile( user + ".txt.new" ); // Do output...!!!!!!! newFile << line1; newFile.close(); if(line2 == "newAccount"){ ofstream newFile(newFileName.c_str()); // c++11 allows std::string if (newFile){ if (0 == remove( oldFileName.c_str() )){ if (0 != rename( newFileName.c_str(), oldFileName.c_str() )){ // Handle rename failure. } }else{ // Handle remove failure. } } 
+4
source share
1 answer

It:

 rename( cUser + ".txt", cUser + ".txt" ); 

incorrect for two reasons:

  • this is pointer arithmetic, not a string constraint, since cUser is char[]
  • even that was the correct concatenation, the old file name and the new file name are the same

There is no reason to use strcpy_s() , use operator+ for std::string :

 const std::string oldFileName(user + ".txt"); const std::string newFileName(user + ".txt.new"); std::ofstream newFile(newFileName.c_str()); // c++11 allows std::string if (newFile && newFile << line1) { newFile.close(); if (newFile) { if (0 == remove( oldFileName.c_str() )) { if (0 != rename( newFileName.c_str(), oldFileName.c_str() )) { // Handle rename failure. } } else { // Handle remove failure. } } } 

Remember file.close() before trying to remove() it.

Always check the result of I / O operations, the code does not confirm that when you open file or if getline() successful:

 ifstream file(user + ".txt"); if (file.is_open()) { string line1, line2; if (getline(file, line1) && getline(file, line2)) { // Successfully read two lines. } } 
+2
source

Source: https://habr.com/ru/post/1480438/


All Articles