从文件中删除
Delete from a file
如果我在文件中有客户记录,如果我有两个客户名称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");
}
假设客户记录是文件中的一行,您需要:
- 分配要在文件中读取的内存。
- 将文件读入内存。
- 修改内存。
- 使用修改的内容覆盖文件。
- 释放您分配的内存。
我不知道
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;
}
}
所有的"大脑"都在读写功能中,选择逻辑非常简单。客户匹配但未写入文件,或者不匹配并写入文件。
所有读取和写入逻辑都与选择逻辑分开,可以轻松地重用于多种不同类型的搜索。
但是,您可能会发现缓存、读取一次并构建customer
的std::vector
进行操作而无需不断读取和重写文件的一些好处。
相关文章:
- 如何在输入新内容 c++ 之前删除文件中的所有内容
- 文件模式标志"ios::app"是否用于删除文件(如果文件已存在)?
- 查找并删除文件 C++ 中的整行
- 如何删除文件中的数字,通过 c++ fstream 的
- 以编程方式防止重命名或删除文件,但仍使其可写
- C++ 如何使用_rmdir删除文件?
- 关于从驱动器中删除文件的问题
- Linux 从永远在线的应用程序中创建和删除文件
- 用户使用C++中的删除功能删除文件
- 如何在C++中删除文件中的一部分文本
- 我可以删除 *.o文件(代码:: blocks)
- 为什么std ::删除文件始终返回-1
- C++ 使用数字删除文件 io 行
- 如何使用 c++ 删除文件夹及其内容
- 如何在 C++ 中的文件处理中删除文件
- 用数字删除文件
- Cygwin:打开句柄时删除文件
- 接收文件并删除文件中的重复项
- 删除文件 C++ 中字符串中最后一个出现的字符
- 在循环内删除文件时使提升recursive_directory_iterator无效