📄 bookdel.cpp
字号:
//*******************************
// 删除书
//*******************************
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<windows.h>
#include"book.h"
int match(char *);
void bookdel()
{
char cname[51]={0},ch='0';
int flag=0;
book p; //临时对象
cout<<"\n\n\t请输入你要删除书的书名:";
cin>>cname;
cin.ignore();
cout<<endl;
flag=match(cname);
if(flag==0)
{
cout<<"\n\n\t查无此书!"<<endl;
system("pause");
return; //返回上一层菜单
}
//如果flag!=0则执行以下程序
fstream file1("book.dat",ios::in|ios::binary);
if(!file1) //错误处理及提示
{
cout<<"\n\t\t打开文件失败!"<<endl;
exit(1); //意外终止程序运行
}
//创建临时文件tt.dat
fstream file2("tt.dat",ios::in|ios::out|ios::binary|ios::trunc);
if(!file2) //错误处理及提示
{
cout<<"\n\t\t打开文件失败!"<<endl;
file1.close();
exit(1); //意外终止程序运行
}
while(!file1.eof())
{
file1.read((char*)&p,sizeof(p));
if(strcmp(cname,p.getbookname())==0)
break;
}
cout<<"\n\t你要删除的书的信息如下:"<<endl;
cout<<p;
cout<<endl<<"确实要删除吗?"<<endl;
cout<<"按y 键确认删除!按其他键取消本次删除!"<<endl;
cin>>ch;
cin.ignore();
cout<<endl;
if(ch!='y')
{
file1.close();
file2.close();
system("pause");
return;
}
file1.seekg(0l,ios::beg);
file1.read((char*)&p,sizeof(p));
while(!file1.eof())
{
if(strcmp(cname,p.getbookname())!=0)
file2.write((char*)&p,sizeof(p));
file1.read((char*)&p,sizeof(p));
}
file1.close();
//以ios::trunc方式打开文件book.dat目的是截空原文件中的数据
file1.open("book.dat",ios::out|ios::binary|ios::trunc);
if(!file1) //错误处理及提示
{
cout<<"\n\t\t删除操作失败!"<<endl;
file2.close();
exit(1); //意外终止程序运行
}
file2.seekg(0l,ios::beg);
file2.read((char*)&p,sizeof(p));
while(!file2.eof())
{
file1.write((char*)&p,sizeof(p));
file2.read((char*)&p,sizeof(p));
}
file1.close();
file2.close();
cout<<"\t\t删除成功!\n"<<endl;
system("pause");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -