简体   繁体   中英

C++ How do i delete a specify line from a textfile?

As stated from my title, how can i delete a specify line from a textfile. My program has a HR user, which they can edit/remove users information. I am able to write into a file, but to delete from a specific line, i am clueless. Hopefully someone can give me an example of how to do it, thanks !

A example of my textfile

user;pass;1234;John;1111
user1;pass1;2345;May;2222
user2;pass2;3456;Mary;3333
user3;pass3;4567;Andy;4444
hr;hr;5678;Jonathan;5555
admin;admin;6789;Aili;6666
user10;pass10;7890;eggy;9999

and so i want to delete the contents of user3 which is at line 4 of my textfile,when the user inputs the username, which is user3.

Here is a pseudocode, I will let you work out the details:

    1. read the entire file into a vector
    2. delete that file
    3. create and write back the data to the file skipping the line that isn't required.

Use std::getline() in a loop to read a line from the file.

  • Load the file content into memory,
  • delete the line there,
  • and write the content back to file.

You could somewhat optimize this process by not loading the portion of the file before the line being deleted (though you'd still need to scan it to find the "target" line), but you won't be able to do much better than that without a specialized data structure.

If this is really important performance-wise, consider using a database instead of the plain file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM