从文件中删除

Delete from a file

本文关键字:删除 文件      更新时间:2023-10-16

如果我在文件中有客户记录,如果我有两个客户名称John Doe,但他们有不同的电话号码,如何从该文件中删除客户记录。基本上我想知道如何使用姓名和电话号码从文件中删除客户记录。这是我的代码。

void deleteCustomerData() {
  string name, customerInfo, customerData;
  string email;
  string phoneNumber;
  string address;
  string deleteCustomer;
  int skip = 0;
  cout << "Enter the name of the Customer record you want to delete: " << endl;
  getline(cin, name);
  cout << "Enter the phone number of the Customer record you want to delete: " << endl;
  getline(cin, customerData);
  ifstream customerFile;
  ofstream tempFile;
  int tracker = 0;
  customerFile.open("customer.txt");
  tempFile.open("tempCustomer.txt");
  while (getline(customerFile, customerInfo)) {
    if ((customerInfo != name) && !(skip > 0)) {
      if ((customerInfo != "{" && customerInfo != "}")) {
        if (tracker == 0) {
          tempFile << "{" << endl << "{" << endl;
        }
        tempFile << customerInfo << endl;
        tracker++;
        if (tracker == 4)
        {
          tempFile << "}" << endl << "}" << endl;
          tracker = 0;
        }
      }
    }
    else
    {
      if (skip == 0)
        skip = 3;
      else
        --skip;
    }
  }
  cout << "The record with the name " << name << " has been deleted " << endl;
  customerFile.close();
  tempFile.close();
  remove("customer.txt");
  rename("tempCustomer.txt", "customer.txt");
}

假设客户记录是文件中的一行,您需要:

  1. 分配要在文件中读取的内存。
  2. 将文件读入内存。
  3. 修改内存。
  4. 使用修改的内容覆盖文件。
  5. 释放您分配的内存。
我不知道

OP的文件格式,所以我必须泛泛而谈。

定义客户结构

struct customer
{
    string name;
    string email;
    string phoneNumber;
    string address;
};

写入函数以读取客户,如果不能,则返回 false。如果您使用如下所示的函数重载 >> 运算符,则可能最简单:

std::istream & operator>>(std::istream & in, customer & incust)

写入函数以写出客户,如果不能,则返回 false。同样,如果重载<<运算符,则最容易。

std::ostream & operator<<(std::ostream & out, const customer & outcust)
使用流运算符

可以利用流的布尔运算符来判断读取或写入是否成功。

然后使用读写功能实现以下内容:

while read in a complete customer from input file
    if customer.name != deletename or customer.phoneNumber!= deletenumber 
        Write customer to output file 

英语:只要我能从输入文件中读取客户,如果他们不是我要删除的客户,我会将客户写入输出文件。

使用重载的流运算符,这可以像

customer cust;
while (infile >> cust)
{
    if (cust.name != deletename || cust.phoneNumber != deletenumber)
    {
        outfile << cust;
    }
}

所有的"大脑"都在读写功能中,选择逻辑非常简单。客户匹配但未写入文件,或者不匹配并写入文件。

所有读取和写入逻辑都与选择逻辑分开,可以轻松地重用于多种不同类型的搜索。

但是,您可能会发现缓存、读取一次并构建customerstd::vector进行操作而无需不断读取和重写文件的一些好处。