从文件中删除

问题描述:

如果我在一个文件中有一个客户记录如果我有两个客户名称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. 释放您分配的内存。
+0

'std :: string'都是可变长度的。所以你不能事先合理地分配必要的内存。我更喜欢一个解决方案,将所有行读入一个'std :: vector <:string>'找到要删除的行,将其从该向量中删除并将其写回文件。 –

+0

它工作正常,直到我必须删除两个同名客户 – kadrian

我不知道OP的文件格式,所以我不得不泛泛而谈。

定义客户结构

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

写入功能在客户读取或返回是否可以不假。也许,如果你有一个看起来像函数重载>>操作最简单:

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

Write函数写出来的客户或返回是否可以不假。同样,如果你超载<<运营商最简单。

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; 
    } 
} 

所有的“大脑”是在读取和写入功能和选择逻辑是死的简单。客户匹配并且不写入文件或不匹配并写入文件。

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

但是,您可能会发现缓存中的某些优点,只需读入一次即可构建std::vectorcustomers以便在不必连续读取和重写文件的情况下进行操作。

+0

我是新的我不明白上面的任何东西。 – kadrian

+0

大的收获是1.将客户存储在一个结构中。处理好的,明确定义的包中的数据要容易得多。 2.制作读取功能和写入功能,一次只能读取或写入一个客户。您可以独立测试和完善读取和写入功能,而无需担心其他代码中的错误会妨碍您的工作。然后,您可以根据读取和写入功能编写程序的其余部分,而不必担心读取和写入中的错误。这会导致3.将应用程序逻辑与实用程序逻辑分开。 – user4581301