简体   繁体   中英

Deleting a specific line in a txt file using istream/ofstream in c++

Here is the code I'm having a trouble with, I have a .txt file that contains a list of users and their passwords using this format: user;password . I need to search for a user in the file and then delete the line which contains this user.

    void deleteauser()
    {
    string user;
    cout<<"Which user do you wish to delete?";
    cin>>user;
    string line;
    string delimiter=";";
    string token,token1;
    ifstream infile;
    infile.open("users.txt",ios::in); 
    while (getline(infile,line,'\n'))
    {
        token = line.substr(0, line.find(delimiter));
        token1=line.substr(token.length(), line.find('\n'));
        if(token==user)
        {
                 //here  i need to delete the line of the user that has been found
        }   
    }
    infile.close();
    }

Read the input file, line by line, writing to a temporary file. When you find lines you don't want then just don't write them to the temporary file. When done rename the temporary file as the real file.

To edit a file you have 2 options:

  1. Read in every line and write out those you want to keep
  2. Seek to the part of the file you want deleted and replace the text with spaces (or similar)

You have the first half pretty much done - just write out what you read to a temporary file and delete/rename to make it the original.

For the second option, you can write to the input file at that point if you use an iofstream (be aware of buffering issues). The better option is to use seekp or seekg to get to the right point before overwriting the 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