简体   繁体   English

在C ++中使用istream / ofstream删除txt文件中的特定行

[英]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 . 这是我遇到麻烦的代码,我有一个.txt文件,其中包含使用以下格式的用户及其密码的列表: 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: 要编辑文件,您有2个选项:

  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). 对于第二个选项,如果使用iofstream,则可以在此时写入输入文件(请注意缓冲问题)。 The better option is to use seekp or seekg to get to the right point before overwriting the file. 更好的选择是在覆盖文件之前使用seekp或seekg到达正确的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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