?? 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 + -